blob: c1f14a9b9bc12b37b185c5d918fbf162d4cad8a6 [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");
Chris Lattnerf1af9472007-10-09 22:58:09 +0000372
373 if (PP.getLangOptions().ObjC1) {
Steve Naroff3b8e8912007-10-17 17:53:50 +0000374 // Predefine all the ObjC goodies (traditionally declared in <objc/objc.h>).
375 // We define the following header guard for source compatibility. It has
376 // the effect of ignoring any explicit inclusion of <objc/objc.h>:-)
377 DefineBuiltinMacro(Buf, "_OBJC_OBJC_H_=1");
378 DefineBuiltinMacro(Buf, "OBJC_EXPORT=extern");
379 DefineBuiltinMacro(Buf, "OBJC_IMPORT=extern");
380 const char *ObjcType;
381 ObjcType = "typedef struct objc_class *Class;\n";
382 Buf.insert(Buf.end(), ObjcType, ObjcType+strlen(ObjcType));
383 ObjcType = "typedef struct objc_object { Class isa; } *id;\n";
384 Buf.insert(Buf.end(), ObjcType, ObjcType+strlen(ObjcType));
385 ObjcType = "typedef struct objc_selector *SEL;\n";
386 Buf.insert(Buf.end(), ObjcType, ObjcType+strlen(ObjcType));
387 ObjcType = "typedef id (*IMP)(id, SEL, ...);\n";
388 Buf.insert(Buf.end(), ObjcType, ObjcType+strlen(ObjcType));
389 ObjcType = "typedef signed char BOOL;\n";
390 Buf.insert(Buf.end(), ObjcType, ObjcType+strlen(ObjcType));
391 DefineBuiltinMacro(Buf, "YES=(BOOL)1");
392 DefineBuiltinMacro(Buf, "NO=(BOOL)0");
393 DefineBuiltinMacro(Buf, "Nil=0");
394 DefineBuiltinMacro(Buf, "nil=0");
Chris Lattnerf1af9472007-10-09 22:58:09 +0000395 }
396
Chris Lattnerd19144b2007-10-10 17:48:53 +0000397 // Add __builtin_va_list typedef.
398 {
399 const char *VAList = PP.getTargetInfo().getVAListDeclaration();
400 Buf.insert(Buf.end(), VAList, VAList+strlen(VAList));
401 Buf.push_back('\n');
402 }
Chris Lattner53b0dab2007-10-09 22:10:18 +0000403
404 // Get the target #defines.
405 PP.getTargetInfo().getTargetDefines(Buf);
406
407 // Compiler set macros.
408 DefineBuiltinMacro(Buf, "__APPLE_CC__=5250");
409 DefineBuiltinMacro(Buf, "__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__=1030");
410 DefineBuiltinMacro(Buf, "__GNUC_MINOR__=0");
411 DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
412 DefineBuiltinMacro(Buf, "__GNUC__=4");
413 DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
414 DefineBuiltinMacro(Buf, "__VERSION__=\"4.0.1 (Apple Computer, Inc. "
415 "build 5250)\"");
416
417 // Build configuration options.
418 DefineBuiltinMacro(Buf, "__DYNAMIC__=1");
419 DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");
420 DefineBuiltinMacro(Buf, "__NO_INLINE__=1");
421 DefineBuiltinMacro(Buf, "__PIC__=1");
422
423
424 if (PP.getLangOptions().CPlusPlus) {
425 DefineBuiltinMacro(Buf, "__DEPRECATED=1");
426 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
427 DefineBuiltinMacro(Buf, "__GNUG__=4");
428 DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
429 DefineBuiltinMacro(Buf, "__cplusplus=1");
430 DefineBuiltinMacro(Buf, "__private_extern__=extern");
431 }
432
433 // FIXME: Should emit a #line directive here.
434}
435
436
437/// EnterMainSourceFile - Enter the specified FileID as the main source file,
438/// which implicitly adds the builting defines etc.
439void Preprocessor::EnterMainSourceFile(unsigned MainFileID) {
440 // Enter the main file source buffer.
441 EnterSourceFile(MainFileID, 0);
442
443
444 std::vector<char> PrologFile;
445 PrologFile.reserve(4080);
446
447 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
448 InitializePredefinedMacros(*this, PrologFile);
449
450 // Add on the predefines from the driver.
451 PrologFile.insert(PrologFile.end(), Predefines,Predefines+strlen(Predefines));
452
453 // Memory buffer must end with a null byte!
454 PrologFile.push_back(0);
455
456 // Now that we have emitted the predefined macros, #includes, etc into
457 // PrologFile, preprocess it to populate the initial preprocessor state.
458 llvm::MemoryBuffer *SB =
459 llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(),
460 "<predefines>");
461 assert(SB && "Cannot fail to create predefined source buffer");
462 unsigned FileID = SourceMgr.createFileIDForMemBuffer(SB);
463 assert(FileID && "Could not create FileID for predefines?");
464
465 // Start parsing the predefines.
466 EnterSourceFile(FileID, 0);
467}
Chris Lattner97ba77c2007-07-16 06:48:38 +0000468
Reid Spencer5f016e22007-07-11 17:01:13 +0000469//===----------------------------------------------------------------------===//
470// Source File Location Methods.
471//===----------------------------------------------------------------------===//
472
473/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
474/// return null on failure. isAngled indicates whether the file reference is
475/// for system #include's or not (i.e. using <> instead of "").
476const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
477 const char *FilenameEnd,
478 bool isAngled,
479 const DirectoryLookup *FromDir,
480 const DirectoryLookup *&CurDir) {
481 // If the header lookup mechanism may be relative to the current file, pass in
482 // info about where the current file is.
483 const FileEntry *CurFileEnt = 0;
484 if (!FromDir) {
Chris Lattner9dc1f532007-07-20 16:37:10 +0000485 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
486 CurFileEnt = SourceMgr.getFileEntryForLoc(FileLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000487 }
488
489 // Do a standard file entry lookup.
490 CurDir = CurDirLookup;
491 const FileEntry *FE =
492 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
493 isAngled, FromDir, CurDir, CurFileEnt);
494 if (FE) return FE;
495
496 // Otherwise, see if this is a subframework header. If so, this is relative
497 // to one of the headers on the #include stack. Walk the list of the current
498 // headers on the #include stack and pass them to HeaderInfo.
499 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattner9dc1f532007-07-20 16:37:10 +0000500 CurFileEnt = SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc());
Reid Spencer5f016e22007-07-11 17:01:13 +0000501 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
502 CurFileEnt)))
503 return FE;
504 }
505
506 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
507 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
508 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattner9dc1f532007-07-20 16:37:10 +0000509 CurFileEnt = SourceMgr.getFileEntryForLoc(ISEntry.TheLexer->getFileLoc());
Reid Spencer5f016e22007-07-11 17:01:13 +0000510 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
511 CurFileEnt)))
512 return FE;
513 }
514 }
515
516 // Otherwise, we really couldn't find the file.
517 return 0;
518}
519
520/// isInPrimaryFile - Return true if we're in the top-level file, not in a
521/// #include.
522bool Preprocessor::isInPrimaryFile() const {
523 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000524 return IncludeMacroStack.empty();
Reid Spencer5f016e22007-07-11 17:01:13 +0000525
526 // If there are any stacked lexers, we're in a #include.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000527 assert(IncludeMacroStack[0].TheLexer &&
528 !IncludeMacroStack[0].TheLexer->Is_PragmaLexer &&
529 "Top level include stack isn't our primary lexer?");
530 for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
Reid Spencer5f016e22007-07-11 17:01:13 +0000531 if (IncludeMacroStack[i].TheLexer &&
532 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000533 return false;
534 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000535}
536
537/// getCurrentLexer - Return the current file lexer being lexed from. Note
538/// that this ignores any potentially active macro expansions and _Pragma
539/// expansions going on at the time.
540Lexer *Preprocessor::getCurrentFileLexer() const {
541 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
542
543 // Look for a stacked lexer.
544 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
545 Lexer *L = IncludeMacroStack[i-1].TheLexer;
546 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
547 return L;
548 }
549 return 0;
550}
551
552
553/// EnterSourceFile - Add a source file to the top of the include stack and
554/// start lexing tokens from it instead of the current buffer. Return true
555/// on failure.
556void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000557 const DirectoryLookup *CurDir) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000558 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
559 ++NumEnteredSourceFiles;
560
561 if (MaxIncludeStackDepth < IncludeMacroStack.size())
562 MaxIncludeStackDepth = IncludeMacroStack.size();
563
Chris Lattner25bdb512007-07-20 16:52:03 +0000564 Lexer *TheLexer = new Lexer(SourceLocation::getFileLoc(FileID, 0), *this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000565 EnterSourceFileWithLexer(TheLexer, CurDir);
566}
567
568/// EnterSourceFile - Add a source file to the top of the include stack and
569/// start lexing tokens from it instead of the current buffer.
570void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
571 const DirectoryLookup *CurDir) {
572
573 // Add the current lexer to the include stack.
574 if (CurLexer || CurMacroExpander)
575 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
576 CurMacroExpander));
577
578 CurLexer = TheLexer;
579 CurDirLookup = CurDir;
580 CurMacroExpander = 0;
581
582 // Notify the client, if desired, that we are in a new source file.
583 if (Callbacks && !CurLexer->Is_PragmaLexer) {
584 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
585
586 // Get the file entry for the current file.
587 if (const FileEntry *FE =
Chris Lattner9dc1f532007-07-20 16:37:10 +0000588 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Reid Spencer5f016e22007-07-11 17:01:13 +0000589 FileType = HeaderInfo.getFileDirFlavor(FE);
590
Chris Lattner9dc1f532007-07-20 16:37:10 +0000591 Callbacks->FileChanged(CurLexer->getFileLoc(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000592 PPCallbacks::EnterFile, FileType);
593 }
594}
595
596
597
598/// EnterMacro - Add a Macro to the top of the include stack and start lexing
599/// tokens from it instead of the current buffer.
Chris Lattnerd2177732007-07-20 16:59:19 +0000600void Preprocessor::EnterMacro(Token &Tok, MacroArgs *Args) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000601 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
602 CurMacroExpander));
603 CurLexer = 0;
604 CurDirLookup = 0;
605
Chris Lattner9594acf2007-07-15 00:25:26 +0000606 if (NumCachedMacroExpanders == 0) {
607 CurMacroExpander = new MacroExpander(Tok, Args, *this);
608 } else {
609 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
610 CurMacroExpander->Init(Tok, Args);
611 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000612}
613
614/// EnterTokenStream - Add a "macro" context to the top of the include stack,
615/// which will cause the lexer to start returning the specified tokens. Note
616/// that these tokens will be re-macro-expanded when/if expansion is enabled.
617/// This method assumes that the specified stream of tokens has a permanent
618/// owner somewhere, so they do not need to be copied.
Chris Lattnerd2177732007-07-20 16:59:19 +0000619void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000620 // Save our current state.
621 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
622 CurMacroExpander));
623 CurLexer = 0;
624 CurDirLookup = 0;
625
626 // Create a macro expander to expand from the specified token stream.
Chris Lattner9594acf2007-07-15 00:25:26 +0000627 if (NumCachedMacroExpanders == 0) {
628 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
629 } else {
630 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
631 CurMacroExpander->Init(Toks, NumToks);
632 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000633}
634
635/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
636/// lexer stack. This should only be used in situations where the current
637/// state of the top-of-stack lexer is known.
638void Preprocessor::RemoveTopOfLexerStack() {
639 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
Chris Lattner9594acf2007-07-15 00:25:26 +0000640
641 if (CurMacroExpander) {
642 // Delete or cache the now-dead macro expander.
643 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
644 delete CurMacroExpander;
645 else
646 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
647 } else {
648 delete CurLexer;
649 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000650 CurLexer = IncludeMacroStack.back().TheLexer;
651 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
652 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
653 IncludeMacroStack.pop_back();
654}
655
656//===----------------------------------------------------------------------===//
657// Macro Expansion Handling.
658//===----------------------------------------------------------------------===//
659
Chris Lattnercc1a8752007-10-07 08:44:20 +0000660/// setMacroInfo - Specify a macro for this identifier.
661///
662void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
663 if (MI == 0) {
664 if (II->hasMacroDefinition()) {
665 Macros.erase(II);
666 II->setHasMacroDefinition(false);
667 }
668 } else {
669 Macros[II] = MI;
670 II->setHasMacroDefinition(true);
671 }
672}
673
Reid Spencer5f016e22007-07-11 17:01:13 +0000674/// RegisterBuiltinMacro - Register the specified identifier in the identifier
675/// table and mark it as a builtin macro to be expanded.
676IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
677 // Get the identifier.
678 IdentifierInfo *Id = getIdentifierInfo(Name);
679
680 // Mark it as being a macro that is builtin.
681 MacroInfo *MI = new MacroInfo(SourceLocation());
682 MI->setIsBuiltinMacro();
Chris Lattnercc1a8752007-10-07 08:44:20 +0000683 setMacroInfo(Id, MI);
Reid Spencer5f016e22007-07-11 17:01:13 +0000684 return Id;
685}
686
687
688/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
689/// identifier table.
690void Preprocessor::RegisterBuiltinMacros() {
691 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
692 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
693 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
694 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
695 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
696
697 // GCC Extensions.
698 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
699 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
700 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
701}
702
703/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
704/// in its expansion, currently expands to that token literally.
705static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
Chris Lattnercc1a8752007-10-07 08:44:20 +0000706 const IdentifierInfo *MacroIdent,
707 Preprocessor &PP) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000708 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
709
710 // If the token isn't an identifier, it's always literally expanded.
711 if (II == 0) return true;
712
713 // If the identifier is a macro, and if that macro is enabled, it may be
714 // expanded so it's not a trivial expansion.
Chris Lattnercc1a8752007-10-07 08:44:20 +0000715 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000716 // Fast expanding "#define X X" is ok, because X would be disabled.
717 II != MacroIdent)
718 return false;
719
720 // If this is an object-like macro invocation, it is safe to trivially expand
721 // it.
722 if (MI->isObjectLike()) return true;
723
724 // If this is a function-like macro invocation, it's safe to trivially expand
725 // as long as the identifier is not a macro argument.
726 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
727 I != E; ++I)
728 if (*I == II)
729 return false; // Identifier is a macro argument.
730
731 return true;
732}
733
734
735/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
736/// lexed is a '('. If so, consume the token and return true, if not, this
737/// method should have no observable side-effect on the lexed tokens.
738bool Preprocessor::isNextPPTokenLParen() {
739 // Do some quick tests for rejection cases.
740 unsigned Val;
741 if (CurLexer)
742 Val = CurLexer->isNextPPTokenLParen();
743 else
744 Val = CurMacroExpander->isNextTokenLParen();
745
746 if (Val == 2) {
Chris Lattner0ea793e2007-07-19 00:07:36 +0000747 // We have run off the end. If it's a source file we don't
748 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
749 // macro stack.
750 if (CurLexer)
751 return false;
752 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000753 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
754 if (Entry.TheLexer)
755 Val = Entry.TheLexer->isNextPPTokenLParen();
756 else
757 Val = Entry.TheMacroExpander->isNextTokenLParen();
Chris Lattner0ea793e2007-07-19 00:07:36 +0000758
759 if (Val != 2)
760 break;
761
762 // Ran off the end of a source file?
763 if (Entry.TheLexer)
764 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000765 }
766 }
767
768 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
769 // have found something that isn't a '(' or we found the end of the
770 // translation unit. In either case, return false.
771 if (Val != 1)
772 return false;
773
Chris Lattnerd2177732007-07-20 16:59:19 +0000774 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000775 LexUnexpandedToken(Tok);
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000776 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000777 return true;
778}
779
780/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
781/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattnerd2177732007-07-20 16:59:19 +0000782bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Reid Spencer5f016e22007-07-11 17:01:13 +0000783 MacroInfo *MI) {
784
785 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
786 if (MI->isBuiltinMacro()) {
787 ExpandBuiltinMacro(Identifier);
788 return false;
789 }
790
791 // If this is the first use of a target-specific macro, warn about it.
792 if (MI->isTargetSpecific()) {
793 MI->setIsTargetSpecific(false); // Don't warn on second use.
794 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
795 diag::port_target_macro_use);
796 }
797
798 /// Args - If this is a function-like macro expansion, this contains,
799 /// for each macro argument, the list of tokens that were provided to the
800 /// invocation.
801 MacroArgs *Args = 0;
802
803 // If this is a function-like macro, read the arguments.
804 if (MI->isFunctionLike()) {
805 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner2b64fdc2007-07-19 16:11:58 +0000806 // name isn't a '(', this macro should not be expanded. Otherwise, consume
807 // it.
Reid Spencer5f016e22007-07-11 17:01:13 +0000808 if (!isNextPPTokenLParen())
809 return true;
810
811 // Remember that we are now parsing the arguments to a macro invocation.
812 // Preprocessor directives used inside macro arguments are not portable, and
813 // this enables the warning.
814 InMacroArgs = true;
815 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
816
817 // Finished parsing args.
818 InMacroArgs = false;
819
820 // If there was an error parsing the arguments, bail out.
821 if (Args == 0) return false;
822
823 ++NumFnMacroExpanded;
824 } else {
825 ++NumMacroExpanded;
826 }
827
828 // Notice that this macro has been used.
829 MI->setIsUsed(true);
830
831 // If we started lexing a macro, enter the macro expansion body.
832
833 // If this macro expands to no tokens, don't bother to push it onto the
834 // expansion stack, only to take it right back off.
835 if (MI->getNumTokens() == 0) {
836 // No need for arg info.
837 if (Args) Args->destroy();
838
839 // Ignore this macro use, just return the next token in the current
840 // buffer.
841 bool HadLeadingSpace = Identifier.hasLeadingSpace();
842 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
843
844 Lex(Identifier);
845
846 // If the identifier isn't on some OTHER line, inherit the leading
847 // whitespace/first-on-a-line property of this token. This handles
848 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
849 // empty.
850 if (!Identifier.isAtStartOfLine()) {
Chris Lattnerd2177732007-07-20 16:59:19 +0000851 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
852 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000853 }
854 ++NumFastMacroExpanded;
855 return false;
856
857 } else if (MI->getNumTokens() == 1 &&
Chris Lattnercc1a8752007-10-07 08:44:20 +0000858 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
859 *this)){
Reid Spencer5f016e22007-07-11 17:01:13 +0000860 // Otherwise, if this macro expands into a single trivially-expanded
861 // token: expand it now. This handles common cases like
862 // "#define VAL 42".
863
864 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
865 // identifier to the expanded token.
866 bool isAtStartOfLine = Identifier.isAtStartOfLine();
867 bool hasLeadingSpace = Identifier.hasLeadingSpace();
868
869 // Remember where the token is instantiated.
870 SourceLocation InstantiateLoc = Identifier.getLocation();
871
872 // Replace the result token.
873 Identifier = MI->getReplacementToken(0);
874
875 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattnerd2177732007-07-20 16:59:19 +0000876 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
877 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000878
879 // Update the tokens location to include both its logical and physical
880 // locations.
881 SourceLocation Loc =
882 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
883 Identifier.setLocation(Loc);
884
885 // If this is #define X X, we must mark the result as unexpandible.
886 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
Chris Lattnercc1a8752007-10-07 08:44:20 +0000887 if (getMacroInfo(NewII) == MI)
Chris Lattnerd2177732007-07-20 16:59:19 +0000888 Identifier.setFlag(Token::DisableExpand);
Reid Spencer5f016e22007-07-11 17:01:13 +0000889
890 // Since this is not an identifier token, it can't be macro expanded, so
891 // we're done.
892 ++NumFastMacroExpanded;
893 return false;
894 }
895
896 // Start expanding the macro.
897 EnterMacro(Identifier, Args);
898
899 // Now that the macro is at the top of the include stack, ask the
900 // preprocessor to read the next token from it.
901 Lex(Identifier);
902 return false;
903}
904
905/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
906/// invoked to read all of the actual arguments specified for the macro
907/// invocation. This returns null on error.
Chris Lattnerd2177732007-07-20 16:59:19 +0000908MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Reid Spencer5f016e22007-07-11 17:01:13 +0000909 MacroInfo *MI) {
910 // The number of fixed arguments to parse.
911 unsigned NumFixedArgsLeft = MI->getNumArgs();
912 bool isVariadic = MI->isVariadic();
913
914 // Outer loop, while there are more arguments, keep reading them.
Chris Lattnerd2177732007-07-20 16:59:19 +0000915 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000916 Tok.setKind(tok::comma);
917 --NumFixedArgsLeft; // Start reading the first arg.
918
919 // ArgTokens - Build up a list of tokens that make up each argument. Each
920 // argument is separated by an EOF token. Use a SmallVector so we can avoid
921 // heap allocations in the common case.
Chris Lattnerd2177732007-07-20 16:59:19 +0000922 llvm::SmallVector<Token, 64> ArgTokens;
Reid Spencer5f016e22007-07-11 17:01:13 +0000923
924 unsigned NumActuals = 0;
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000925 while (Tok.is(tok::comma)) {
Chris Lattner2b64fdc2007-07-19 16:11:58 +0000926 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
927 // that we already consumed the first one.
Reid Spencer5f016e22007-07-11 17:01:13 +0000928 unsigned NumParens = 0;
929
930 while (1) {
931 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
932 // an argument value in a macro could expand to ',' or '(' or ')'.
933 LexUnexpandedToken(Tok);
934
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000935 if (Tok.is(tok::eof)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000936 Diag(MacroName, diag::err_unterm_macro_invoc);
937 // Do not lose the EOF. Return it to the client.
938 MacroName = Tok;
939 return 0;
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000940 } else if (Tok.is(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000941 // If we found the ) token, the macro arg list is done.
942 if (NumParens-- == 0)
943 break;
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000944 } else if (Tok.is(tok::l_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000945 ++NumParens;
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000946 } else if (Tok.is(tok::comma) && NumParens == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000947 // Comma ends this argument if there are more fixed arguments expected.
948 if (NumFixedArgsLeft)
949 break;
950
951 // If this is not a variadic macro, too many args were specified.
952 if (!isVariadic) {
953 // Emit the diagnostic at the macro name in case there is a missing ).
954 // Emitting it at the , could be far away from the macro name.
955 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
956 return 0;
957 }
958 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000959 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000960 // If this is a comment token in the argument list and we're just in
961 // -C mode (not -CC mode), discard the comment.
962 continue;
963 }
964
965 ArgTokens.push_back(Tok);
966 }
967
968 // Empty arguments are standard in C99 and supported as an extension in
969 // other modes.
970 if (ArgTokens.empty() && !Features.C99)
971 Diag(Tok, diag::ext_empty_fnmacro_arg);
972
973 // Add a marker EOF token to the end of the token list for this argument.
Chris Lattnerd2177732007-07-20 16:59:19 +0000974 Token EOFTok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000975 EOFTok.startToken();
976 EOFTok.setKind(tok::eof);
977 EOFTok.setLocation(Tok.getLocation());
978 EOFTok.setLength(0);
979 ArgTokens.push_back(EOFTok);
980 ++NumActuals;
981 --NumFixedArgsLeft;
982 };
983
984 // Okay, we either found the r_paren. Check to see if we parsed too few
985 // arguments.
986 unsigned MinArgsExpected = MI->getNumArgs();
987
988 // See MacroArgs instance var for description of this.
989 bool isVarargsElided = false;
990
991 if (NumActuals < MinArgsExpected) {
992 // There are several cases where too few arguments is ok, handle them now.
993 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
994 // Varargs where the named vararg parameter is missing: ok as extension.
995 // #define A(x, ...)
996 // A("blah")
997 Diag(Tok, diag::ext_missing_varargs_arg);
998
999 // Remember this occurred if this is a C99 macro invocation with at least
1000 // one actual argument.
1001 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
1002 } else if (MI->getNumArgs() == 1) {
1003 // #define A(x)
1004 // A()
1005 // is ok because it is an empty argument.
1006
1007 // Empty arguments are standard in C99 and supported as an extension in
1008 // other modes.
1009 if (ArgTokens.empty() && !Features.C99)
1010 Diag(Tok, diag::ext_empty_fnmacro_arg);
1011 } else {
1012 // Otherwise, emit the error.
1013 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
1014 return 0;
1015 }
1016
1017 // Add a marker EOF token to the end of the token list for this argument.
1018 SourceLocation EndLoc = Tok.getLocation();
1019 Tok.startToken();
1020 Tok.setKind(tok::eof);
1021 Tok.setLocation(EndLoc);
1022 Tok.setLength(0);
1023 ArgTokens.push_back(Tok);
1024 }
1025
1026 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
1027}
1028
1029/// ComputeDATE_TIME - Compute the current time, enter it into the specified
1030/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
1031/// the identifier tokens inserted.
1032static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
1033 Preprocessor &PP) {
1034 time_t TT = time(0);
1035 struct tm *TM = localtime(&TT);
1036
1037 static const char * const Months[] = {
1038 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
1039 };
1040
1041 char TmpBuffer[100];
1042 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
1043 TM->tm_year+1900);
1044 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
1045
1046 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
1047 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
1048}
1049
1050/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1051/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattnerd2177732007-07-20 16:59:19 +00001052void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001053 // Figure out which token this is.
1054 IdentifierInfo *II = Tok.getIdentifierInfo();
1055 assert(II && "Can't be a macro without id info!");
1056
1057 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
1058 // lex the token after it.
1059 if (II == Ident_Pragma)
1060 return Handle_Pragma(Tok);
1061
1062 ++NumBuiltinMacroExpanded;
1063
1064 char TmpBuffer[100];
1065
1066 // Set up the return result.
1067 Tok.setIdentifierInfo(0);
Chris Lattnerd2177732007-07-20 16:59:19 +00001068 Tok.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001069
1070 if (II == Ident__LINE__) {
1071 // __LINE__ expands to a simple numeric value.
Chris Lattner9dc1f532007-07-20 16:37:10 +00001072 sprintf(TmpBuffer, "%u", SourceMgr.getLogicalLineNumber(Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001073 unsigned Length = strlen(TmpBuffer);
1074 Tok.setKind(tok::numeric_constant);
1075 Tok.setLength(Length);
1076 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
1077 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1078 SourceLocation Loc = Tok.getLocation();
1079 if (II == Ident__BASE_FILE__) {
1080 Diag(Tok, diag::ext_pp_base_file);
Chris Lattner9dc1f532007-07-20 16:37:10 +00001081 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc);
1082 while (NextLoc.isValid()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001083 Loc = NextLoc;
Chris Lattner9dc1f532007-07-20 16:37:10 +00001084 NextLoc = SourceMgr.getIncludeLoc(Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001085 }
1086 }
1087
1088 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Chris Lattner9dc1f532007-07-20 16:37:10 +00001089 std::string FN = SourceMgr.getSourceName(SourceMgr.getLogicalLoc(Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001090 FN = '"' + Lexer::Stringify(FN) + '"';
1091 Tok.setKind(tok::string_literal);
1092 Tok.setLength(FN.size());
1093 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
1094 } else if (II == Ident__DATE__) {
1095 if (!DATELoc.isValid())
1096 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1097 Tok.setKind(tok::string_literal);
1098 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1099 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
1100 } else if (II == Ident__TIME__) {
1101 if (!TIMELoc.isValid())
1102 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1103 Tok.setKind(tok::string_literal);
1104 Tok.setLength(strlen("\"hh:mm:ss\""));
1105 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
1106 } else if (II == Ident__INCLUDE_LEVEL__) {
1107 Diag(Tok, diag::ext_pp_include_level);
1108
1109 // Compute the include depth of this token.
1110 unsigned Depth = 0;
Chris Lattner9dc1f532007-07-20 16:37:10 +00001111 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation());
1112 for (; Loc.isValid(); ++Depth)
1113 Loc = SourceMgr.getIncludeLoc(Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001114
1115 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1116 sprintf(TmpBuffer, "%u", Depth);
1117 unsigned Length = strlen(TmpBuffer);
1118 Tok.setKind(tok::numeric_constant);
1119 Tok.setLength(Length);
1120 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
1121 } else if (II == Ident__TIMESTAMP__) {
1122 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1123 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1124 Diag(Tok, diag::ext_pp_timestamp);
1125
1126 // Get the file that we are lexing out of. If we're currently lexing from
1127 // a macro, dig into the include stack.
1128 const FileEntry *CurFile = 0;
1129 Lexer *TheLexer = getCurrentFileLexer();
1130
1131 if (TheLexer)
Chris Lattner9dc1f532007-07-20 16:37:10 +00001132 CurFile = SourceMgr.getFileEntryForLoc(TheLexer->getFileLoc());
Reid Spencer5f016e22007-07-11 17:01:13 +00001133
1134 // If this file is older than the file it depends on, emit a diagnostic.
1135 const char *Result;
1136 if (CurFile) {
1137 time_t TT = CurFile->getModificationTime();
1138 struct tm *TM = localtime(&TT);
1139 Result = asctime(TM);
1140 } else {
1141 Result = "??? ??? ?? ??:??:?? ????\n";
1142 }
1143 TmpBuffer[0] = '"';
1144 strcpy(TmpBuffer+1, Result);
1145 unsigned Len = strlen(TmpBuffer);
1146 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
1147 Tok.setKind(tok::string_literal);
1148 Tok.setLength(Len);
1149 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
1150 } else {
1151 assert(0 && "Unknown identifier!");
1152 }
1153}
1154
1155//===----------------------------------------------------------------------===//
1156// Lexer Event Handling.
1157//===----------------------------------------------------------------------===//
1158
1159/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
1160/// identifier information for the token and install it into the token.
Chris Lattnerd2177732007-07-20 16:59:19 +00001161IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
Reid Spencer5f016e22007-07-11 17:01:13 +00001162 const char *BufPtr) {
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001163 assert(Identifier.is(tok::identifier) && "Not an identifier!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001164 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
1165
1166 // Look up this token, see if it is a macro, or if it is a language keyword.
1167 IdentifierInfo *II;
1168 if (BufPtr && !Identifier.needsCleaning()) {
1169 // No cleaning needed, just use the characters from the lexed buffer.
1170 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
1171 } else {
1172 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Chris Lattnerc35717a2007-07-13 17:10:38 +00001173 llvm::SmallVector<char, 64> IdentifierBuffer;
1174 IdentifierBuffer.resize(Identifier.getLength());
1175 const char *TmpBuf = &IdentifierBuffer[0];
Reid Spencer5f016e22007-07-11 17:01:13 +00001176 unsigned Size = getSpelling(Identifier, TmpBuf);
1177 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
1178 }
1179 Identifier.setIdentifierInfo(II);
1180 return II;
1181}
1182
1183
1184/// HandleIdentifier - This callback is invoked when the lexer reads an
1185/// identifier. This callback looks up the identifier in the map and/or
1186/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnerd2177732007-07-20 16:59:19 +00001187void Preprocessor::HandleIdentifier(Token &Identifier) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001188 assert(Identifier.getIdentifierInfo() &&
1189 "Can't handle identifiers without identifier info!");
1190
1191 IdentifierInfo &II = *Identifier.getIdentifierInfo();
1192
1193 // If this identifier was poisoned, and if it was not produced from a macro
1194 // expansion, emit an error.
1195 if (II.isPoisoned() && CurLexer) {
1196 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
1197 Diag(Identifier, diag::err_pp_used_poisoned_id);
1198 else
1199 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
1200 }
1201
1202 // If this is a macro to be expanded, do it.
Chris Lattnercc1a8752007-10-07 08:44:20 +00001203 if (MacroInfo *MI = getMacroInfo(&II)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001204 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
1205 if (MI->isEnabled()) {
1206 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1207 return;
1208 } else {
1209 // C99 6.10.3.4p2 says that a disabled macro may never again be
1210 // expanded, even if it's in a context where it could be expanded in the
1211 // future.
Chris Lattnerd2177732007-07-20 16:59:19 +00001212 Identifier.setFlag(Token::DisableExpand);
Reid Spencer5f016e22007-07-11 17:01:13 +00001213 }
1214 }
1215 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
1216 // If this identifier is a macro on some other target, emit a diagnostic.
1217 // This diagnosic is only emitted when macro expansion is enabled, because
1218 // the macro would not have been expanded for the other target either.
1219 II.setIsOtherTargetMacro(false); // Don't warn on second use.
1220 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
1221 diag::port_target_macro_use);
1222
1223 }
1224
1225 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
1226 // then we act as if it is the actual operator and not the textual
1227 // representation of it.
1228 if (II.isCPlusPlusOperatorKeyword())
1229 Identifier.setIdentifierInfo(0);
1230
1231 // Change the kind of this identifier to the appropriate token kind, e.g.
1232 // turning "for" into a keyword.
1233 Identifier.setKind(II.getTokenID());
1234
1235 // If this is an extension token, diagnose its use.
1236 // FIXME: tried (unsuccesfully) to shut this up when compiling with gnu99
1237 // For now, I'm just commenting it out (while I work on attributes).
1238 if (II.isExtensionToken() && Features.C99)
1239 Diag(Identifier, diag::ext_token_used);
1240}
1241
1242/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1243/// the current file. This either returns the EOF token or pops a level off
1244/// the include stack and keeps going.
Chris Lattnerd2177732007-07-20 16:59:19 +00001245bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001246 assert(!CurMacroExpander &&
1247 "Ending a file when currently in a macro!");
1248
1249 // See if this file had a controlling macro.
1250 if (CurLexer) { // Not ending a macro, ignore it.
1251 if (const IdentifierInfo *ControllingMacro =
1252 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
1253 // Okay, this has a controlling macro, remember in PerFileInfo.
1254 if (const FileEntry *FE =
Chris Lattner9dc1f532007-07-20 16:37:10 +00001255 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Reid Spencer5f016e22007-07-11 17:01:13 +00001256 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
1257 }
1258 }
1259
1260 // If this is a #include'd file, pop it off the include stack and continue
1261 // lexing the #includer file.
1262 if (!IncludeMacroStack.empty()) {
1263 // We're done with the #included file.
1264 RemoveTopOfLexerStack();
1265
1266 // Notify the client, if desired, that we are in a new source file.
1267 if (Callbacks && !isEndOfMacro && CurLexer) {
1268 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1269
1270 // Get the file entry for the current file.
1271 if (const FileEntry *FE =
Chris Lattner9dc1f532007-07-20 16:37:10 +00001272 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Reid Spencer5f016e22007-07-11 17:01:13 +00001273 FileType = HeaderInfo.getFileDirFlavor(FE);
1274
1275 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1276 PPCallbacks::ExitFile, FileType);
1277 }
1278
1279 // Client should lex another token.
1280 return false;
1281 }
1282
1283 Result.startToken();
1284 CurLexer->BufferPtr = CurLexer->BufferEnd;
1285 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
1286 Result.setKind(tok::eof);
1287
1288 // We're done with the #included file.
1289 delete CurLexer;
1290 CurLexer = 0;
1291
1292 // This is the end of the top-level file. If the diag::pp_macro_not_used
Chris Lattnercc1a8752007-10-07 08:44:20 +00001293 // diagnostic is enabled, look for macros that have not been used.
Reid Spencer5f016e22007-07-11 17:01:13 +00001294 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
Chris Lattnercc1a8752007-10-07 08:44:20 +00001295 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
1296 Macros.begin(), E = Macros.end(); I != E; ++I) {
1297 if (!I->second->isUsed())
1298 Diag(I->second->getDefinitionLoc(), diag::pp_macro_not_used);
Reid Spencer5f016e22007-07-11 17:01:13 +00001299 }
1300 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001301 return true;
1302}
1303
1304/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
1305/// the current macro expansion or token stream expansion.
Chris Lattnerd2177732007-07-20 16:59:19 +00001306bool Preprocessor::HandleEndOfMacro(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001307 assert(CurMacroExpander && !CurLexer &&
1308 "Ending a macro when currently in a #include file!");
1309
Chris Lattner9594acf2007-07-15 00:25:26 +00001310 // Delete or cache the now-dead macro expander.
1311 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
1312 delete CurMacroExpander;
1313 else
1314 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
Reid Spencer5f016e22007-07-11 17:01:13 +00001315
1316 // Handle this like a #include file being popped off the stack.
1317 CurMacroExpander = 0;
1318 return HandleEndOfFile(Result, true);
1319}
1320
1321
1322//===----------------------------------------------------------------------===//
1323// Utility Methods for Preprocessor Directive Handling.
1324//===----------------------------------------------------------------------===//
1325
1326/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1327/// current line until the tok::eom token is found.
1328void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattnerd2177732007-07-20 16:59:19 +00001329 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001330 do {
1331 LexUnexpandedToken(Tmp);
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001332 } while (Tmp.isNot(tok::eom));
Reid Spencer5f016e22007-07-11 17:01:13 +00001333}
1334
1335/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
1336static bool isCXXNamedOperator(const std::string &Spelling) {
1337 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
1338 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
1339 Spelling == "or" || Spelling == "xor";
1340}
1341
1342/// ReadMacroName - Lex and validate a macro name, which occurs after a
1343/// #define or #undef. This sets the token kind to eom and discards the rest
1344/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1345/// this is due to a a #define, 2 if #undef directive, 0 if it is something
1346/// else (e.g. #ifdef).
Chris Lattnerd2177732007-07-20 16:59:19 +00001347void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001348 // Read the token, don't allow macro expansion on it.
1349 LexUnexpandedToken(MacroNameTok);
1350
1351 // Missing macro name?
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001352 if (MacroNameTok.is(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +00001353 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1354
1355 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1356 if (II == 0) {
1357 std::string Spelling = getSpelling(MacroNameTok);
1358 if (isCXXNamedOperator(Spelling))
1359 // C++ 2.5p2: Alternative tokens behave the same as its primary token
1360 // except for their spellings.
1361 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
1362 else
1363 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
1364 // Fall through on error.
1365 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
1366 // Error if defining "defined": C99 6.10.8.4.
1367 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattner0edde552007-10-07 08:04:56 +00001368 } else if (isDefineUndef && II->hasMacroDefinition() &&
Chris Lattnercc1a8752007-10-07 08:44:20 +00001369 getMacroInfo(II)->isBuiltinMacro()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001370 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
1371 if (isDefineUndef == 1)
1372 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1373 else
1374 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
1375 } else {
1376 // Okay, we got a good identifier node. Return it.
1377 return;
1378 }
1379
1380 // Invalid macro name, read and discard the rest of the line. Then set the
1381 // token kind to tok::eom.
1382 MacroNameTok.setKind(tok::eom);
1383 return DiscardUntilEndOfDirective();
1384}
1385
1386/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1387/// not, emit a diagnostic and consume up until the eom.
1388void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001389 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001390 Lex(Tmp);
1391 // There should be no tokens after the directive, but we allow them as an
1392 // extension.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001393 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00001394 Lex(Tmp);
1395
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001396 if (Tmp.isNot(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001397 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1398 DiscardUntilEndOfDirective();
1399 }
1400}
1401
1402
1403
1404/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1405/// decided that the subsequent tokens are in the #if'd out portion of the
1406/// file. Lex the rest of the file, until we see an #endif. If
1407/// FoundNonSkipPortion is true, then we have already emitted code for part of
1408/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1409/// is true, then #else directives are ok, if not, then we have already seen one
1410/// so a #else directive is a duplicate. When this returns, the caller can lex
1411/// the first valid token.
1412void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
1413 bool FoundNonSkipPortion,
1414 bool FoundElse) {
1415 ++NumSkipped;
1416 assert(CurMacroExpander == 0 && CurLexer &&
1417 "Lexing a macro, not a file?");
1418
1419 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1420 FoundNonSkipPortion, FoundElse);
1421
1422 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1423 // disabling warnings, etc.
1424 CurLexer->LexingRawMode = true;
Chris Lattnerd2177732007-07-20 16:59:19 +00001425 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001426 while (1) {
1427 CurLexer->Lex(Tok);
1428
1429 // If this is the end of the buffer, we have an error.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001430 if (Tok.is(tok::eof)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001431 // Emit errors for each unterminated conditional on the stack, including
1432 // the current one.
1433 while (!CurLexer->ConditionalStack.empty()) {
1434 Diag(CurLexer->ConditionalStack.back().IfLoc,
1435 diag::err_pp_unterminated_conditional);
1436 CurLexer->ConditionalStack.pop_back();
1437 }
1438
1439 // Just return and let the caller lex after this #include.
1440 break;
1441 }
1442
1443 // If this token is not a preprocessor directive, just skip it.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001444 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
Reid Spencer5f016e22007-07-11 17:01:13 +00001445 continue;
1446
1447 // We just parsed a # character at the start of a line, so we're in
1448 // directive mode. Tell the lexer this so any newlines we see will be
1449 // converted into an EOM token (this terminates the macro).
1450 CurLexer->ParsingPreprocessorDirective = true;
1451 CurLexer->KeepCommentMode = false;
1452
1453
1454 // Read the next token, the directive flavor.
1455 LexUnexpandedToken(Tok);
1456
1457 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1458 // something bogus), skip it.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001459 if (Tok.isNot(tok::identifier)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001460 CurLexer->ParsingPreprocessorDirective = false;
1461 // Restore comment saving mode.
1462 CurLexer->KeepCommentMode = KeepComments;
1463 continue;
1464 }
1465
1466 // If the first letter isn't i or e, it isn't intesting to us. We know that
1467 // this is safe in the face of spelling differences, because there is no way
1468 // to spell an i/e in a strange way that is another letter. Skipping this
1469 // allows us to avoid looking up the identifier info for #define/#undef and
1470 // other common directives.
1471 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1472 char FirstChar = RawCharData[0];
1473 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1474 FirstChar != 'i' && FirstChar != 'e') {
1475 CurLexer->ParsingPreprocessorDirective = false;
1476 // Restore comment saving mode.
1477 CurLexer->KeepCommentMode = KeepComments;
1478 continue;
1479 }
1480
1481 // Get the identifier name without trigraphs or embedded newlines. Note
1482 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1483 // when skipping.
1484 // TODO: could do this with zero copies in the no-clean case by using
1485 // strncmp below.
1486 char Directive[20];
1487 unsigned IdLen;
1488 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1489 IdLen = Tok.getLength();
1490 memcpy(Directive, RawCharData, IdLen);
1491 Directive[IdLen] = 0;
1492 } else {
1493 std::string DirectiveStr = getSpelling(Tok);
1494 IdLen = DirectiveStr.size();
1495 if (IdLen >= 20) {
1496 CurLexer->ParsingPreprocessorDirective = false;
1497 // Restore comment saving mode.
1498 CurLexer->KeepCommentMode = KeepComments;
1499 continue;
1500 }
1501 memcpy(Directive, &DirectiveStr[0], IdLen);
1502 Directive[IdLen] = 0;
1503 }
1504
1505 if (FirstChar == 'i' && Directive[1] == 'f') {
1506 if ((IdLen == 2) || // "if"
1507 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1508 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
1509 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1510 // bother parsing the condition.
1511 DiscardUntilEndOfDirective();
1512 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
1513 /*foundnonskip*/false,
1514 /*fnddelse*/false);
1515 }
1516 } else if (FirstChar == 'e') {
1517 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
1518 CheckEndOfDirective("#endif");
1519 PPConditionalInfo CondInfo;
1520 CondInfo.WasSkipping = true; // Silence bogus warning.
1521 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1522 InCond = InCond; // Silence warning in no-asserts mode.
1523 assert(!InCond && "Can't be skipping if not in a conditional!");
1524
1525 // If we popped the outermost skipping block, we're done skipping!
1526 if (!CondInfo.WasSkipping)
1527 break;
1528 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
1529 // #else directive in a skipping conditional. If not in some other
1530 // skipping conditional, and if #else hasn't already been seen, enter it
1531 // as a non-skipping conditional.
1532 CheckEndOfDirective("#else");
1533 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1534
1535 // If this is a #else with a #else before it, report the error.
1536 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
1537
1538 // Note that we've seen a #else in this conditional.
1539 CondInfo.FoundElse = true;
1540
1541 // If the conditional is at the top level, and the #if block wasn't
1542 // entered, enter the #else block now.
1543 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1544 CondInfo.FoundNonSkip = true;
1545 break;
1546 }
1547 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
1548 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1549
1550 bool ShouldEnter;
1551 // If this is in a skipping block or if we're already handled this #if
1552 // block, don't bother parsing the condition.
1553 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
1554 DiscardUntilEndOfDirective();
1555 ShouldEnter = false;
1556 } else {
1557 // Restore the value of LexingRawMode so that identifiers are
1558 // looked up, etc, inside the #elif expression.
1559 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1560 CurLexer->LexingRawMode = false;
1561 IdentifierInfo *IfNDefMacro = 0;
1562 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
1563 CurLexer->LexingRawMode = true;
1564 }
1565
1566 // If this is a #elif with a #else before it, report the error.
1567 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
1568
1569 // If this condition is true, enter it!
1570 if (ShouldEnter) {
1571 CondInfo.FoundNonSkip = true;
1572 break;
1573 }
1574 }
1575 }
1576
1577 CurLexer->ParsingPreprocessorDirective = false;
1578 // Restore comment saving mode.
1579 CurLexer->KeepCommentMode = KeepComments;
1580 }
1581
1582 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1583 // of the file, just stop skipping and return to lexing whatever came after
1584 // the #if block.
1585 CurLexer->LexingRawMode = false;
1586}
1587
1588//===----------------------------------------------------------------------===//
1589// Preprocessor Directive Handling.
1590//===----------------------------------------------------------------------===//
1591
1592/// HandleDirective - This callback is invoked when the lexer sees a # token
1593/// at the start of a line. This consumes the directive, modifies the
1594/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1595/// read is the correct one.
Chris Lattnerd2177732007-07-20 16:59:19 +00001596void Preprocessor::HandleDirective(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
1598
1599 // We just parsed a # character at the start of a line, so we're in directive
1600 // mode. Tell the lexer this so any newlines we see will be converted into an
1601 // EOM token (which terminates the directive).
1602 CurLexer->ParsingPreprocessorDirective = true;
1603
1604 ++NumDirectives;
1605
1606 // We are about to read a token. For the multiple-include optimization FA to
1607 // work, we have to remember if we had read any tokens *before* this
1608 // pp-directive.
1609 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1610
1611 // Read the next token, the directive flavor. This isn't expanded due to
1612 // C99 6.10.3p8.
1613 LexUnexpandedToken(Result);
1614
1615 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1616 // #define A(x) #x
1617 // A(abc
1618 // #warning blah
1619 // def)
1620 // If so, the user is relying on non-portable behavior, emit a diagnostic.
1621 if (InMacroArgs)
1622 Diag(Result, diag::ext_embedded_directive);
1623
1624TryAgain:
1625 switch (Result.getKind()) {
1626 case tok::eom:
1627 return; // null directive.
1628 case tok::comment:
1629 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1630 LexUnexpandedToken(Result);
1631 goto TryAgain;
1632
1633 case tok::numeric_constant:
1634 // FIXME: implement # 7 line numbers!
1635 DiscardUntilEndOfDirective();
1636 return;
1637 default:
1638 IdentifierInfo *II = Result.getIdentifierInfo();
1639 if (II == 0) break; // Not an identifier.
1640
1641 // Ask what the preprocessor keyword ID is.
1642 switch (II->getPPKeywordID()) {
1643 default: break;
1644 // C99 6.10.1 - Conditional Inclusion.
1645 case tok::pp_if:
1646 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1647 case tok::pp_ifdef:
1648 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1649 case tok::pp_ifndef:
1650 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1651 case tok::pp_elif:
1652 return HandleElifDirective(Result);
1653 case tok::pp_else:
1654 return HandleElseDirective(Result);
1655 case tok::pp_endif:
1656 return HandleEndifDirective(Result);
1657
1658 // C99 6.10.2 - Source File Inclusion.
1659 case tok::pp_include:
1660 return HandleIncludeDirective(Result); // Handle #include.
1661
1662 // C99 6.10.3 - Macro Replacement.
1663 case tok::pp_define:
1664 return HandleDefineDirective(Result, false);
1665 case tok::pp_undef:
1666 return HandleUndefDirective(Result);
1667
1668 // C99 6.10.4 - Line Control.
1669 case tok::pp_line:
1670 // FIXME: implement #line
1671 DiscardUntilEndOfDirective();
1672 return;
1673
1674 // C99 6.10.5 - Error Directive.
1675 case tok::pp_error:
1676 return HandleUserDiagnosticDirective(Result, false);
1677
1678 // C99 6.10.6 - Pragma Directive.
1679 case tok::pp_pragma:
1680 return HandlePragmaDirective();
1681
1682 // GNU Extensions.
1683 case tok::pp_import:
1684 return HandleImportDirective(Result);
1685 case tok::pp_include_next:
1686 return HandleIncludeNextDirective(Result);
1687
1688 case tok::pp_warning:
1689 Diag(Result, diag::ext_pp_warning_directive);
1690 return HandleUserDiagnosticDirective(Result, true);
1691 case tok::pp_ident:
1692 return HandleIdentSCCSDirective(Result);
1693 case tok::pp_sccs:
1694 return HandleIdentSCCSDirective(Result);
1695 case tok::pp_assert:
1696 //isExtension = true; // FIXME: implement #assert
1697 break;
1698 case tok::pp_unassert:
1699 //isExtension = true; // FIXME: implement #unassert
1700 break;
1701
1702 // clang extensions.
1703 case tok::pp_define_target:
1704 return HandleDefineDirective(Result, true);
1705 case tok::pp_define_other_target:
1706 return HandleDefineOtherTargetDirective(Result);
1707 }
1708 break;
1709 }
1710
1711 // If we reached here, the preprocessing token is not valid!
1712 Diag(Result, diag::err_pp_invalid_directive);
1713
1714 // Read the rest of the PP line.
1715 DiscardUntilEndOfDirective();
1716
1717 // Okay, we're done parsing the directive.
1718}
1719
Chris Lattnerd2177732007-07-20 16:59:19 +00001720void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Reid Spencer5f016e22007-07-11 17:01:13 +00001721 bool isWarning) {
1722 // Read the rest of the line raw. We do this because we don't want macros
1723 // to be expanded and we don't require that the tokens be valid preprocessing
1724 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1725 // collapse multiple consequtive white space between tokens, but this isn't
1726 // specified by the standard.
1727 std::string Message = CurLexer->ReadToEndOfLine();
1728
1729 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
1730 return Diag(Tok, DiagID, Message);
1731}
1732
1733/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1734///
Chris Lattnerd2177732007-07-20 16:59:19 +00001735void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001736 // Yes, this directive is an extension.
1737 Diag(Tok, diag::ext_pp_ident_directive);
1738
1739 // Read the string argument.
Chris Lattnerd2177732007-07-20 16:59:19 +00001740 Token StrTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001741 Lex(StrTok);
1742
1743 // If the token kind isn't a string, it's a malformed directive.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001744 if (StrTok.isNot(tok::string_literal) &&
1745 StrTok.isNot(tok::wide_string_literal))
Reid Spencer5f016e22007-07-11 17:01:13 +00001746 return Diag(StrTok, diag::err_pp_malformed_ident);
1747
1748 // Verify that there is nothing after the string, other than EOM.
1749 CheckEndOfDirective("#ident");
1750
1751 if (Callbacks)
1752 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
1753}
1754
1755//===----------------------------------------------------------------------===//
1756// Preprocessor Include Directive Handling.
1757//===----------------------------------------------------------------------===//
1758
1759/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1760/// checked and spelled filename, e.g. as an operand of #include. This returns
1761/// true if the input filename was in <>'s or false if it were in ""'s. The
1762/// caller is expected to provide a buffer that is large enough to hold the
1763/// spelling of the filename, but is also expected to handle the case when
1764/// this method decides to use a different buffer.
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001765bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001766 const char *&BufStart,
1767 const char *&BufEnd) {
1768 // Get the text form of the filename.
Reid Spencer5f016e22007-07-11 17:01:13 +00001769 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1770
1771 // Make sure the filename is <x> or "x".
1772 bool isAngled;
1773 if (BufStart[0] == '<') {
1774 if (BufEnd[-1] != '>') {
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001775 Diag(Loc, diag::err_pp_expects_filename);
Reid Spencer5f016e22007-07-11 17:01:13 +00001776 BufStart = 0;
1777 return true;
1778 }
1779 isAngled = true;
1780 } else if (BufStart[0] == '"') {
1781 if (BufEnd[-1] != '"') {
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001782 Diag(Loc, diag::err_pp_expects_filename);
Reid Spencer5f016e22007-07-11 17:01:13 +00001783 BufStart = 0;
1784 return true;
1785 }
1786 isAngled = false;
1787 } else {
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001788 Diag(Loc, diag::err_pp_expects_filename);
Reid Spencer5f016e22007-07-11 17:01:13 +00001789 BufStart = 0;
1790 return true;
1791 }
1792
1793 // Diagnose #include "" as invalid.
1794 if (BufEnd-BufStart <= 2) {
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001795 Diag(Loc, diag::err_pp_empty_filename);
Reid Spencer5f016e22007-07-11 17:01:13 +00001796 BufStart = 0;
1797 return "";
1798 }
1799
1800 // Skip the brackets.
1801 ++BufStart;
1802 --BufEnd;
1803 return isAngled;
1804}
1805
Chris Lattner706ab502007-07-23 04:56:47 +00001806/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1807/// from a macro as multiple tokens, which need to be glued together. This
1808/// occurs for code like:
1809/// #define FOO <a/b.h>
1810/// #include FOO
1811/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1812///
1813/// This code concatenates and consumes tokens up to the '>' token. It returns
1814/// false if the > was found, otherwise it returns true if it finds and consumes
1815/// the EOM marker.
1816static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
1817 Preprocessor &PP) {
1818 Token CurTok;
1819
1820 PP.Lex(CurTok);
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001821 while (CurTok.isNot(tok::eom)) {
Chris Lattner706ab502007-07-23 04:56:47 +00001822 // Append the spelling of this token to the buffer. If there was a space
1823 // before it, add it now.
1824 if (CurTok.hasLeadingSpace())
1825 FilenameBuffer.push_back(' ');
1826
1827 // Get the spelling of the token, directly into FilenameBuffer if possible.
1828 unsigned PreAppendSize = FilenameBuffer.size();
1829 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
1830
1831 const char *BufPtr = &FilenameBuffer[PreAppendSize];
1832 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
1833
1834 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1835 if (BufPtr != &FilenameBuffer[PreAppendSize])
1836 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1837
1838 // Resize FilenameBuffer to the correct size.
1839 if (CurTok.getLength() != ActualLen)
1840 FilenameBuffer.resize(PreAppendSize+ActualLen);
1841
1842 // If we found the '>' marker, return success.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001843 if (CurTok.is(tok::greater))
Chris Lattner706ab502007-07-23 04:56:47 +00001844 return false;
1845
1846 PP.Lex(CurTok);
1847 }
1848
1849 // If we hit the eom marker, emit an error and return true so that the caller
1850 // knows the EOM has been read.
1851 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
1852 return true;
1853}
1854
Reid Spencer5f016e22007-07-11 17:01:13 +00001855/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1856/// file to be included from the lexer, then include it! This is a common
1857/// routine with functionality shared between #include, #include_next and
1858/// #import.
Chris Lattnerd2177732007-07-20 16:59:19 +00001859void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
Reid Spencer5f016e22007-07-11 17:01:13 +00001860 const DirectoryLookup *LookupFrom,
1861 bool isImport) {
1862
Chris Lattnerd2177732007-07-20 16:59:19 +00001863 Token FilenameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001864 CurLexer->LexIncludeFilename(FilenameTok);
1865
Reid Spencer5f016e22007-07-11 17:01:13 +00001866 // Reserve a buffer to get the spelling.
1867 llvm::SmallVector<char, 128> FilenameBuffer;
Chris Lattner706ab502007-07-23 04:56:47 +00001868 const char *FilenameStart, *FilenameEnd;
1869
1870 switch (FilenameTok.getKind()) {
1871 case tok::eom:
1872 // If the token kind is EOM, the error has already been diagnosed.
1873 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001874
Chris Lattner706ab502007-07-23 04:56:47 +00001875 case tok::angle_string_literal:
Chris Lattnerf11ccfc2007-07-23 22:23:52 +00001876 case tok::string_literal: {
Chris Lattner706ab502007-07-23 04:56:47 +00001877 FilenameBuffer.resize(FilenameTok.getLength());
1878 FilenameStart = &FilenameBuffer[0];
1879 unsigned Len = getSpelling(FilenameTok, FilenameStart);
1880 FilenameEnd = FilenameStart+Len;
1881 break;
Chris Lattnerf11ccfc2007-07-23 22:23:52 +00001882 }
Chris Lattner706ab502007-07-23 04:56:47 +00001883
1884 case tok::less:
1885 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1886 // case, glue the tokens together into FilenameBuffer and interpret those.
1887 FilenameBuffer.push_back('<');
1888 if (ConcatenateIncludeName(FilenameBuffer, *this))
1889 return; // Found <eom> but no ">"? Diagnostic already emitted.
1890 FilenameStart = &FilenameBuffer[0];
1891 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
1892 break;
1893 default:
1894 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1895 DiscardUntilEndOfDirective();
1896 return;
1897 }
1898
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001899 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +00001900 FilenameStart, FilenameEnd);
1901 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1902 // error.
Chris Lattner706ab502007-07-23 04:56:47 +00001903 if (FilenameStart == 0) {
1904 DiscardUntilEndOfDirective();
Reid Spencer5f016e22007-07-11 17:01:13 +00001905 return;
Chris Lattner706ab502007-07-23 04:56:47 +00001906 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001907
1908 // Verify that there is nothing after the filename, other than EOM. Use the
1909 // preprocessor to lex this in case lexing the filename entered a macro.
1910 CheckEndOfDirective("#include");
1911
1912 // Check that we don't have infinite #include recursion.
1913 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
1914 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1915
1916 // Search include directories.
1917 const DirectoryLookup *CurDir;
1918 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
1919 isAngled, LookupFrom, CurDir);
1920 if (File == 0)
1921 return Diag(FilenameTok, diag::err_pp_file_not_found,
1922 std::string(FilenameStart, FilenameEnd));
1923
1924 // Ask HeaderInfo if we should enter this #include file.
1925 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1926 // If it returns true, #including this file will have no effect.
1927 return;
1928 }
1929
1930 // Look up the file, create a File ID for it.
1931 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
1932 if (FileID == 0)
1933 return Diag(FilenameTok, diag::err_pp_file_not_found,
1934 std::string(FilenameStart, FilenameEnd));
1935
1936 // Finally, if all is good, enter the new file!
1937 EnterSourceFile(FileID, CurDir);
1938}
1939
1940/// HandleIncludeNextDirective - Implements #include_next.
1941///
Chris Lattnerd2177732007-07-20 16:59:19 +00001942void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001943 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
1944
1945 // #include_next is like #include, except that we start searching after
1946 // the current found directory. If we can't do this, issue a
1947 // diagnostic.
1948 const DirectoryLookup *Lookup = CurDirLookup;
1949 if (isInPrimaryFile()) {
1950 Lookup = 0;
1951 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1952 } else if (Lookup == 0) {
1953 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1954 } else {
1955 // Start looking up in the next directory.
1956 ++Lookup;
1957 }
1958
1959 return HandleIncludeDirective(IncludeNextTok, Lookup);
1960}
1961
1962/// HandleImportDirective - Implements #import.
1963///
Chris Lattnerd2177732007-07-20 16:59:19 +00001964void Preprocessor::HandleImportDirective(Token &ImportTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001965 Diag(ImportTok, diag::ext_pp_import_directive);
1966
1967 return HandleIncludeDirective(ImportTok, 0, true);
1968}
1969
1970//===----------------------------------------------------------------------===//
1971// Preprocessor Macro Directive Handling.
1972//===----------------------------------------------------------------------===//
1973
1974/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1975/// definition has just been read. Lex the rest of the arguments and the
1976/// closing ), updating MI with what we learn. Return true if an error occurs
1977/// parsing the arg list.
1978bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner25c96482007-07-14 22:46:43 +00001979 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
1980
Chris Lattnerd2177732007-07-20 16:59:19 +00001981 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001982 while (1) {
1983 LexUnexpandedToken(Tok);
1984 switch (Tok.getKind()) {
1985 case tok::r_paren:
1986 // Found the end of the argument list.
Chris Lattner25c96482007-07-14 22:46:43 +00001987 if (Arguments.empty()) { // #define FOO()
1988 MI->setArgumentList(Arguments.begin(), Arguments.end());
1989 return false;
1990 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001991 // Otherwise we have #define FOO(A,)
1992 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1993 return true;
1994 case tok::ellipsis: // #define X(... -> C99 varargs
1995 // Warn if use of C99 feature in non-C99 mode.
1996 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1997
1998 // Lex the token after the identifier.
1999 LexUnexpandedToken(Tok);
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002000 if (Tok.isNot(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002001 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2002 return true;
2003 }
2004 // Add the __VA_ARGS__ identifier as an argument.
Chris Lattner25c96482007-07-14 22:46:43 +00002005 Arguments.push_back(Ident__VA_ARGS__);
Reid Spencer5f016e22007-07-11 17:01:13 +00002006 MI->setIsC99Varargs();
Chris Lattner25c96482007-07-14 22:46:43 +00002007 MI->setArgumentList(Arguments.begin(), Arguments.end());
Reid Spencer5f016e22007-07-11 17:01:13 +00002008 return false;
2009 case tok::eom: // #define X(
2010 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2011 return true;
2012 default:
2013 // Handle keywords and identifiers here to accept things like
2014 // #define Foo(for) for.
2015 IdentifierInfo *II = Tok.getIdentifierInfo();
2016 if (II == 0) {
2017 // #define X(1
2018 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
2019 return true;
2020 }
2021
2022 // If this is already used as an argument, it is used multiple times (e.g.
2023 // #define X(A,A.
Chris Lattner25c96482007-07-14 22:46:43 +00002024 if (std::find(Arguments.begin(), Arguments.end(), II) !=
2025 Arguments.end()) { // C99 6.10.3p6
Reid Spencer5f016e22007-07-11 17:01:13 +00002026 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
2027 return true;
2028 }
2029
2030 // Add the argument to the macro info.
Chris Lattner25c96482007-07-14 22:46:43 +00002031 Arguments.push_back(II);
Reid Spencer5f016e22007-07-11 17:01:13 +00002032
2033 // Lex the token after the identifier.
2034 LexUnexpandedToken(Tok);
2035
2036 switch (Tok.getKind()) {
2037 default: // #define X(A B
2038 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2039 return true;
2040 case tok::r_paren: // #define X(A)
Chris Lattner25c96482007-07-14 22:46:43 +00002041 MI->setArgumentList(Arguments.begin(), Arguments.end());
Reid Spencer5f016e22007-07-11 17:01:13 +00002042 return false;
2043 case tok::comma: // #define X(A,
2044 break;
2045 case tok::ellipsis: // #define X(A... -> GCC extension
2046 // Diagnose extension.
2047 Diag(Tok, diag::ext_named_variadic_macro);
2048
2049 // Lex the token after the identifier.
2050 LexUnexpandedToken(Tok);
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002051 if (Tok.isNot(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002052 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2053 return true;
2054 }
2055
2056 MI->setIsGNUVarargs();
Chris Lattner25c96482007-07-14 22:46:43 +00002057 MI->setArgumentList(Arguments.begin(), Arguments.end());
Reid Spencer5f016e22007-07-11 17:01:13 +00002058 return false;
2059 }
2060 }
2061 }
2062}
2063
2064/// HandleDefineDirective - Implements #define. This consumes the entire macro
2065/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
2066/// true, then this is a "#define_target", otherwise this is a "#define".
2067///
Chris Lattnerd2177732007-07-20 16:59:19 +00002068void Preprocessor::HandleDefineDirective(Token &DefineTok,
Reid Spencer5f016e22007-07-11 17:01:13 +00002069 bool isTargetSpecific) {
2070 ++NumDefined;
2071
Chris Lattnerd2177732007-07-20 16:59:19 +00002072 Token MacroNameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002073 ReadMacroName(MacroNameTok, 1);
2074
2075 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002076 if (MacroNameTok.is(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +00002077 return;
Chris Lattnerc215bd62007-07-14 22:11:41 +00002078
Reid Spencer5f016e22007-07-11 17:01:13 +00002079 // If we are supposed to keep comments in #defines, reenable comment saving
2080 // mode.
2081 CurLexer->KeepCommentMode = KeepMacroComments;
2082
2083 // Create the new macro.
2084 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
2085 if (isTargetSpecific) MI->setIsTargetSpecific();
2086
2087 // If the identifier is an 'other target' macro, clear this bit.
2088 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2089
2090
Chris Lattnerd2177732007-07-20 16:59:19 +00002091 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002092 LexUnexpandedToken(Tok);
2093
2094 // If this is a function-like macro definition, parse the argument list,
2095 // marking each of the identifiers as being used as macro arguments. Also,
2096 // check other constraints on the first token of the macro body.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002097 if (Tok.is(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002098 // If there is no body to this macro, we have no special handling here.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002099 } else if (Tok.is(tok::l_paren) && !Tok.hasLeadingSpace()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002100 // This is a function-like macro definition. Read the argument list.
2101 MI->setIsFunctionLike();
2102 if (ReadMacroDefinitionArgList(MI)) {
2103 // Forget about MI.
2104 delete MI;
2105 // Throw away the rest of the line.
2106 if (CurLexer->ParsingPreprocessorDirective)
2107 DiscardUntilEndOfDirective();
2108 return;
2109 }
2110
2111 // Read the first token after the arg list for down below.
2112 LexUnexpandedToken(Tok);
2113 } else if (!Tok.hasLeadingSpace()) {
2114 // C99 requires whitespace between the macro definition and the body. Emit
2115 // a diagnostic for something like "#define X+".
2116 if (Features.C99) {
2117 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
2118 } else {
2119 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
2120 // one in some cases!
2121 }
2122 } else {
2123 // This is a normal token with leading space. Clear the leading space
2124 // marker on the first token to get proper expansion.
Chris Lattnerd2177732007-07-20 16:59:19 +00002125 Tok.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002126 }
2127
2128 // If this is a definition of a variadic C99 function-like macro, not using
2129 // the GNU named varargs extension, enabled __VA_ARGS__.
2130
2131 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
2132 // This gets unpoisoned where it is allowed.
2133 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
2134 if (MI->isC99Varargs())
2135 Ident__VA_ARGS__->setIsPoisoned(false);
2136
2137 // Read the rest of the macro body.
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002138 if (MI->isObjectLike()) {
2139 // Object-like macros are very simple, just read their body.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002140 while (Tok.isNot(tok::eom)) {
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002141 MI->AddTokenToBody(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +00002142 // Get the next token of the macro.
2143 LexUnexpandedToken(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +00002144 }
2145
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002146 } else {
2147 // Otherwise, read the body of a function-like macro. This has to validate
2148 // the # (stringize) operator.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002149 while (Tok.isNot(tok::eom)) {
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002150 MI->AddTokenToBody(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +00002151
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002152 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
2153 // parameters in function-like macro expansions.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002154 if (Tok.isNot(tok::hash)) {
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002155 // Get the next token of the macro.
2156 LexUnexpandedToken(Tok);
2157 continue;
2158 }
2159
2160 // Get the next token of the macro.
2161 LexUnexpandedToken(Tok);
2162
2163 // Not a macro arg identifier?
2164 if (!Tok.getIdentifierInfo() ||
2165 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2166 Diag(Tok, diag::err_pp_stringize_not_parameter);
2167 delete MI;
2168
2169 // Disable __VA_ARGS__ again.
2170 Ident__VA_ARGS__->setIsPoisoned(true);
2171 return;
2172 }
2173
2174 // Things look ok, add the param name token to the macro.
2175 MI->AddTokenToBody(Tok);
2176
2177 // Get the next token of the macro.
2178 LexUnexpandedToken(Tok);
2179 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002180 }
2181
Chris Lattnerc215bd62007-07-14 22:11:41 +00002182
Reid Spencer5f016e22007-07-11 17:01:13 +00002183 // Disable __VA_ARGS__ again.
2184 Ident__VA_ARGS__->setIsPoisoned(true);
2185
2186 // Check that there is no paste (##) operator at the begining or end of the
2187 // replacement list.
2188 unsigned NumTokens = MI->getNumTokens();
2189 if (NumTokens != 0) {
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002190 if (MI->getReplacementToken(0).is(tok::hashhash)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002191 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
2192 delete MI;
2193 return;
2194 }
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002195 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002196 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
2197 delete MI;
2198 return;
2199 }
2200 }
2201
2202 // If this is the primary source file, remember that this macro hasn't been
2203 // used yet.
2204 if (isInPrimaryFile())
2205 MI->setIsUsed(false);
2206
2207 // Finally, if this identifier already had a macro defined for it, verify that
2208 // the macro bodies are identical and free the old definition.
Chris Lattnercc1a8752007-10-07 08:44:20 +00002209 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002210 if (!OtherMI->isUsed())
2211 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
2212
2213 // Macros must be identical. This means all tokes and whitespace separation
2214 // must be the same. C99 6.10.3.2.
2215 if (!MI->isIdenticalTo(*OtherMI, *this)) {
2216 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
2217 MacroNameTok.getIdentifierInfo()->getName());
2218 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
2219 }
2220 delete OtherMI;
2221 }
2222
Chris Lattnercc1a8752007-10-07 08:44:20 +00002223 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002224}
2225
2226/// HandleDefineOtherTargetDirective - Implements #define_other_target.
Chris Lattnerd2177732007-07-20 16:59:19 +00002227void Preprocessor::HandleDefineOtherTargetDirective(Token &Tok) {
2228 Token MacroNameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002229 ReadMacroName(MacroNameTok, 1);
2230
2231 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002232 if (MacroNameTok.is(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +00002233 return;
2234
2235 // Check to see if this is the last token on the #undef line.
2236 CheckEndOfDirective("#define_other_target");
2237
2238 // If there is already a macro defined by this name, turn it into a
2239 // target-specific define.
Chris Lattnercc1a8752007-10-07 08:44:20 +00002240 if (MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002241 MI->setIsTargetSpecific(true);
2242 return;
2243 }
2244
2245 // Mark the identifier as being a macro on some other target.
2246 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
2247}
2248
2249
2250/// HandleUndefDirective - Implements #undef.
2251///
Chris Lattnerd2177732007-07-20 16:59:19 +00002252void Preprocessor::HandleUndefDirective(Token &UndefTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002253 ++NumUndefined;
2254
Chris Lattnerd2177732007-07-20 16:59:19 +00002255 Token MacroNameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002256 ReadMacroName(MacroNameTok, 2);
2257
2258 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002259 if (MacroNameTok.is(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +00002260 return;
2261
2262 // Check to see if this is the last token on the #undef line.
2263 CheckEndOfDirective("#undef");
2264
2265 // Okay, we finally have a valid identifier to undef.
Chris Lattnercc1a8752007-10-07 08:44:20 +00002266 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Reid Spencer5f016e22007-07-11 17:01:13 +00002267
2268 // #undef untaints an identifier if it were marked by define_other_target.
2269 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2270
2271 // If the macro is not defined, this is a noop undef, just return.
2272 if (MI == 0) return;
2273
2274 if (!MI->isUsed())
2275 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
2276
2277 // Free macro definition.
2278 delete MI;
Chris Lattnercc1a8752007-10-07 08:44:20 +00002279 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002280}
2281
2282
2283//===----------------------------------------------------------------------===//
2284// Preprocessor Conditional Directive Handling.
2285//===----------------------------------------------------------------------===//
2286
2287/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
2288/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
2289/// if any tokens have been returned or pp-directives activated before this
2290/// #ifndef has been lexed.
2291///
Chris Lattnerd2177732007-07-20 16:59:19 +00002292void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
Reid Spencer5f016e22007-07-11 17:01:13 +00002293 bool ReadAnyTokensBeforeDirective) {
2294 ++NumIf;
Chris Lattnerd2177732007-07-20 16:59:19 +00002295 Token DirectiveTok = Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00002296
Chris Lattnerd2177732007-07-20 16:59:19 +00002297 Token MacroNameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002298 ReadMacroName(MacroNameTok);
2299
2300 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002301 if (MacroNameTok.is(tok::eom)) {
Chris Lattnerf37bb252007-09-24 05:14:57 +00002302 // Skip code until we get to #endif. This helps with recovery by not
2303 // emitting an error when the #endif is reached.
2304 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2305 /*Foundnonskip*/false, /*FoundElse*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00002306 return;
Chris Lattnerf37bb252007-09-24 05:14:57 +00002307 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002308
2309 // Check to see if this is the last token on the #if[n]def line.
2310 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
2311
2312 // If the start of a top-level #ifdef, inform MIOpt.
2313 if (!ReadAnyTokensBeforeDirective &&
2314 CurLexer->getConditionalStackDepth() == 0) {
2315 assert(isIfndef && "#ifdef shouldn't reach here");
2316 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
2317 }
2318
2319 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Chris Lattnercc1a8752007-10-07 08:44:20 +00002320 MacroInfo *MI = getMacroInfo(MII);
Reid Spencer5f016e22007-07-11 17:01:13 +00002321
2322 // If there is a macro, process it.
2323 if (MI) {
2324 // Mark it used.
2325 MI->setIsUsed(true);
2326
2327 // If this is the first use of a target-specific macro, warn about it.
2328 if (MI->isTargetSpecific()) {
2329 MI->setIsTargetSpecific(false); // Don't warn on second use.
2330 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2331 diag::port_target_macro_use);
2332 }
2333 } else {
2334 // Use of a target-specific macro for some other target? If so, warn.
2335 if (MII->isOtherTargetMacro()) {
2336 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
2337 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2338 diag::port_target_macro_use);
2339 }
2340 }
2341
2342 // Should we include the stuff contained by this directive?
2343 if (!MI == isIfndef) {
2344 // Yes, remember that we are inside a conditional, then lex the next token.
2345 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
2346 /*foundnonskip*/true, /*foundelse*/false);
2347 } else {
2348 // No, skip the contents of this block and return the first token after it.
2349 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2350 /*Foundnonskip*/false,
2351 /*FoundElse*/false);
2352 }
2353}
2354
2355/// HandleIfDirective - Implements the #if directive.
2356///
Chris Lattnerd2177732007-07-20 16:59:19 +00002357void Preprocessor::HandleIfDirective(Token &IfToken,
Reid Spencer5f016e22007-07-11 17:01:13 +00002358 bool ReadAnyTokensBeforeDirective) {
2359 ++NumIf;
2360
2361 // Parse and evaluation the conditional expression.
2362 IdentifierInfo *IfNDefMacro = 0;
2363 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2364
2365 // Should we include the stuff contained by this directive?
2366 if (ConditionalTrue) {
2367 // If this condition is equivalent to #ifndef X, and if this is the first
2368 // directive seen, handle it for the multiple-include optimization.
2369 if (!ReadAnyTokensBeforeDirective &&
2370 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2371 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2372
2373 // Yes, remember that we are inside a conditional, then lex the next token.
2374 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
2375 /*foundnonskip*/true, /*foundelse*/false);
2376 } else {
2377 // No, skip the contents of this block and return the first token after it.
2378 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
2379 /*FoundElse*/false);
2380 }
2381}
2382
2383/// HandleEndifDirective - Implements the #endif directive.
2384///
Chris Lattnerd2177732007-07-20 16:59:19 +00002385void Preprocessor::HandleEndifDirective(Token &EndifToken) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002386 ++NumEndif;
2387
2388 // Check that this is the whole directive.
2389 CheckEndOfDirective("#endif");
2390
2391 PPConditionalInfo CondInfo;
2392 if (CurLexer->popConditionalLevel(CondInfo)) {
2393 // No conditionals on the stack: this is an #endif without an #if.
2394 return Diag(EndifToken, diag::err_pp_endif_without_if);
2395 }
2396
2397 // If this the end of a top-level #endif, inform MIOpt.
2398 if (CurLexer->getConditionalStackDepth() == 0)
2399 CurLexer->MIOpt.ExitTopLevelConditional();
2400
2401 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
2402 "This code should only be reachable in the non-skipping case!");
2403}
2404
2405
Chris Lattnerd2177732007-07-20 16:59:19 +00002406void Preprocessor::HandleElseDirective(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002407 ++NumElse;
2408
2409 // #else directive in a non-skipping conditional... start skipping.
2410 CheckEndOfDirective("#else");
2411
2412 PPConditionalInfo CI;
2413 if (CurLexer->popConditionalLevel(CI))
2414 return Diag(Result, diag::pp_err_else_without_if);
2415
2416 // If this is a top-level #else, inform the MIOpt.
2417 if (CurLexer->getConditionalStackDepth() == 0)
2418 CurLexer->MIOpt.FoundTopLevelElse();
2419
2420 // If this is a #else with a #else before it, report the error.
2421 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
2422
2423 // Finally, skip the rest of the contents of this block and return the first
2424 // token after it.
2425 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2426 /*FoundElse*/true);
2427}
2428
Chris Lattnerd2177732007-07-20 16:59:19 +00002429void Preprocessor::HandleElifDirective(Token &ElifToken) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002430 ++NumElse;
2431
2432 // #elif directive in a non-skipping conditional... start skipping.
2433 // We don't care what the condition is, because we will always skip it (since
2434 // the block immediately before it was included).
2435 DiscardUntilEndOfDirective();
2436
2437 PPConditionalInfo CI;
2438 if (CurLexer->popConditionalLevel(CI))
2439 return Diag(ElifToken, diag::pp_err_elif_without_if);
2440
2441 // If this is a top-level #elif, inform the MIOpt.
2442 if (CurLexer->getConditionalStackDepth() == 0)
2443 CurLexer->MIOpt.FoundTopLevelElse();
2444
2445 // If this is a #elif with a #else before it, report the error.
2446 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
2447
2448 // Finally, skip the rest of the contents of this block and return the first
2449 // token after it.
2450 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2451 /*FoundElse*/CI.FoundElse);
2452}
2453