blob: ba96fad92cf41c200844452a68d6ebb8f9a35b32 [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +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//
Chris Lattner22eb9722006-06-18 05:43:12 +000014// Options to support:
15// -H - Print the name of each header file used.
Chris Lattner22eb9722006-06-18 05:43:12 +000016// -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//
Chris Lattner22eb9722006-06-18 05:43:12 +000026//===----------------------------------------------------------------------===//
27
28#include "clang/Lex/Preprocessor.h"
Chris Lattner07b019a2006-10-22 07:28:56 +000029#include "clang/Lex/HeaderSearch.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000030#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000031#include "clang/Lex/PPCallbacks.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000032#include "clang/Lex/Pragma.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000033#include "clang/Lex/ScratchBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000034#include "clang/Basic/Diagnostic.h"
35#include "clang/Basic/FileManager.h"
36#include "clang/Basic/SourceManager.h"
Chris Lattner81278c62006-10-14 19:03:49 +000037#include "clang/Basic/TargetInfo.h"
Chris Lattner7a4af3b2006-07-26 06:26:52 +000038#include "llvm/ADT/SmallVector.h"
Chris Lattner8a7003c2007-07-16 06:48:38 +000039#include "llvm/Support/MemoryBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000040#include <iostream>
Chris Lattnera2633932007-09-03 18:30:32 +000041#include <ctime>
Chris Lattner22eb9722006-06-18 05:43:12 +000042using namespace clang;
43
44//===----------------------------------------------------------------------===//
45
Chris Lattner02dffbd2006-10-14 07:50:21 +000046Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
Chris Lattnerad7cdd32006-11-21 06:08:20 +000047 TargetInfo &target, SourceManager &SM,
Chris Lattner59a9ebd2006-10-18 05:34:33 +000048 HeaderSearch &Headers)
Chris Lattnerad7cdd32006-11-21 06:08:20 +000049 : Diags(diags), Features(opts), Target(target), FileMgr(Headers.getFileMgr()),
50 SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts),
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000051 CurLexer(0), CurDirLookup(0), CurMacroExpander(0), Callbacks(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000052 ScratchBuf = new ScratchBuffer(SourceMgr);
Chris Lattnerc02c4ab2007-07-15 00:25:26 +000053
Chris Lattner22eb9722006-06-18 05:43:12 +000054 // Clear stats.
Chris Lattner59a9ebd2006-10-18 05:34:33 +000055 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000056 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000057 NumEnteredSourceFiles = 0;
58 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
Chris Lattner510ab612006-07-20 04:47:30 +000059 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Chris Lattner59a9ebd2006-10-18 05:34:33 +000060 MaxIncludeStackDepth = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000061 NumSkipped = 0;
Chris Lattnerb352e3e2006-11-21 06:17:10 +000062
63 // Default to discarding comments.
64 KeepComments = false;
65 KeepMacroComments = false;
66
Chris Lattner22eb9722006-06-18 05:43:12 +000067 // Macro expansion is enabled.
68 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000069 InMacroArgs = false;
Chris Lattnerc02c4ab2007-07-15 00:25:26 +000070 NumCachedMacroExpanders = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000071
Chris Lattner8ff71992006-07-06 05:17:39 +000072 // "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 Lattner1f1b0db2007-10-09 22:10:18 +000076 Predefines = 0;
77
Chris Lattnerb8761832006-06-24 21:31:03 +000078 // Initialize the pragma handlers.
79 PragmaHandlers = new PragmaNamespace(0);
80 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000081
82 // Initialize builtin macros like __LINE__ and friends.
83 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000084}
85
86Preprocessor::~Preprocessor() {
87 // Free any active lexers.
88 delete CurLexer;
89
Chris Lattner69772b02006-07-02 20:34:39 +000090 while (!IncludeMacroStack.empty()) {
91 delete IncludeMacroStack.back().TheLexer;
92 delete IncludeMacroStack.back().TheMacroExpander;
93 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000094 }
Chris Lattnerc43ddc82007-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 }
Chris Lattnerb8761832006-06-24 21:31:03 +0000104
Chris Lattnerc02c4ab2007-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
Chris Lattnerb8761832006-06-24 21:31:03 +0000109 // Release pragma information.
110 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000111
112 // Delete the scratch buffer info.
113 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +0000114}
115
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000116PPCallbacks::~PPCallbacks() {
117}
Chris Lattner87d3bec2006-10-17 03:44:32 +0000118
Chris Lattner22eb9722006-06-18 05:43:12 +0000119/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
Chris Lattner146762e2007-07-20 16:59:19 +0000120/// the specified Token's location, translating the token's start
Chris Lattner22eb9722006-06-18 05:43:12 +0000121/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattner36982e42007-05-16 17:49:37 +0000122void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID) {
123 Diags.Report(Loc, DiagID);
124}
125
Chris Lattnercb283342006-06-18 06:48:37 +0000126void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000127 const std::string &Msg) {
Chris Lattner36982e42007-05-16 17:49:37 +0000128 Diags.Report(Loc, DiagID, &Msg, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +0000129}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000130
Chris Lattner146762e2007-07-20 16:59:19 +0000131void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +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]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000141 if (Tok.isExpandDisabled())
142 std::cerr << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000143 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000144 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000145 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
Chris Lattner22eb9722006-06-18 05:43:12 +0000159void Preprocessor::PrintStats() {
160 std::cerr << "\n*** Preprocessor Stats:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000161 std::cerr << NumDirectives << " directives found:\n";
162 std::cerr << " " << NumDefined << " #define.\n";
163 std::cerr << " " << NumUndefined << " #undef.\n";
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000164 std::cerr << " #include/#include_next/#import:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000165 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
Chris Lattner78186052006-07-09 00:45:31 +0000173 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
174 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
Chris Lattner22eb9722006-06-18 05:43:12 +0000175 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner510ab612006-07-20 04:47:30 +0000176 std::cerr << (NumFastTokenPaste+NumTokenPaste)
177 << " token paste (##) operations performed, "
178 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000179}
180
181//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000182// 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 Lattner146762e2007-07-20 16:59:19 +0000191std::string Preprocessor::getSpelling(const Token &Tok) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000192 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
193
194 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000195 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000196 if (!Tok.needsCleaning())
197 return std::string(TokStart, TokStart+Tok.getLength());
198
Chris Lattnerd01e2912006-06-18 16:22:51 +0000199 std::string Result;
200 Result.reserve(Tok.getLength());
201
Chris Lattneref9eae12006-07-04 22:33:12 +0000202 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000203 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.
Chris Lattneref9eae12006-07-04 22:33:12 +0000218///
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 Lattner146762e2007-07-20 16:59:19 +0000224unsigned Preprocessor::getSpelling(const Token &Tok,
Chris Lattneref9eae12006-07-04 22:33:12 +0000225 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000226 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
227
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000228 // 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 Lattner32e6d642007-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);
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000239 }
240
241 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000242 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000243
244 // If this token contains nothing interesting, return it directly.
245 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000246 Buffer = TokStart;
247 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000248 }
249 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000250 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000251 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
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000263
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 Lattner8a7003c2007-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 Lattnerdc5c0552007-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 Lattner8a7003c2007-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 Lattnerdc5c0552007-07-20 16:37:10 +0000289 const char *TokPtr = SourceMgr.getCharacterData(TokStart);
290 unsigned PhysOffset = 0;
Chris Lattner8a7003c2007-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 Lattnerdc5c0552007-07-20 16:37:10 +0000296 ++TokPtr, --CharNo, ++PhysOffset;
Chris Lattner8a7003c2007-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 Lattner8a7003c2007-07-16 06:48:38 +0000300 if (CharNo != 0) {
301 // Create a lexer starting at this token position.
Chris Lattner77e9de52007-07-20 16:52:03 +0000302 Lexer TheLexer(TokStart, *this, TokPtr);
Chris Lattner146762e2007-07-20 16:59:19 +0000303 Token Tok;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000304 // Skip over characters the remaining characters.
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000305 const char *TokStartPtr = TokPtr;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000306 for (; CharNo; --CharNo)
307 TheLexer.getAndAdvanceChar(TokPtr, Tok);
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000308
309 PhysOffset += TokPtr-TokStartPtr;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000310 }
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000311
312 return TokStart.getFileLocWithOffset(PhysOffset);
Chris Lattner8a7003c2007-07-16 06:48:38 +0000313}
314
315
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000316//===----------------------------------------------------------------------===//
317// Preprocessor Initialization Methods
318//===----------------------------------------------------------------------===//
319
320// Append a #define line to Buf for Macro. Macro should be of the form XXX,
321// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
322// "#define XXX Y z W". To get a #define with no value, use "XXX=".
323static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
324 const char *Command = "#define ") {
325 Buf.insert(Buf.end(), Command, Command+strlen(Command));
326 if (const char *Equal = strchr(Macro, '=')) {
327 // Turn the = into ' '.
328 Buf.insert(Buf.end(), Macro, Equal);
329 Buf.push_back(' ');
330 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
331 } else {
332 // Push "macroname 1".
333 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
334 Buf.push_back(' ');
335 Buf.push_back('1');
336 }
337 Buf.push_back('\n');
338}
339
340
341static void InitializePredefinedMacros(Preprocessor &PP,
342 std::vector<char> &Buf) {
343 // FIXME: Implement magic like cpp_init_builtins for things like __STDC__
344 // and __DATE__ etc.
345#if 0
346 /* __STDC__ has the value 1 under normal circumstances.
347 However, if (a) we are in a system header, (b) the option
348 stdc_0_in_system_headers is true (set by target config), and
349 (c) we are not in strictly conforming mode, then it has the
350 value 0. (b) and (c) are already checked in cpp_init_builtins. */
351 //case BT_STDC:
352 if (cpp_in_system_header (pfile))
353 number = 0;
354 else
355 number = 1;
356 break;
357#endif
358 // These should all be defined in the preprocessor according to the
359 // current language configuration.
360 DefineBuiltinMacro(Buf, "__STDC__=1");
361 //DefineBuiltinMacro(Buf, "__ASSEMBLER__=1");
362 if (PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus)
363 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L");
364 else if (0) // STDC94 ?
365 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L");
366
367 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1");
368 if (PP.getLangOptions().ObjC1)
369 DefineBuiltinMacro(Buf, "__OBJC__=1");
370 if (PP.getLangOptions().ObjC2)
371 DefineBuiltinMacro(Buf, "__OBJC2__=1");
372
373 // Get the target #defines.
374 PP.getTargetInfo().getTargetDefines(Buf);
375
376 // Compiler set macros.
377 DefineBuiltinMacro(Buf, "__APPLE_CC__=5250");
378 DefineBuiltinMacro(Buf, "__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__=1030");
379 DefineBuiltinMacro(Buf, "__GNUC_MINOR__=0");
380 DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
381 DefineBuiltinMacro(Buf, "__GNUC__=4");
382 DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
383 DefineBuiltinMacro(Buf, "__VERSION__=\"4.0.1 (Apple Computer, Inc. "
384 "build 5250)\"");
385
386 // Build configuration options.
387 DefineBuiltinMacro(Buf, "__DYNAMIC__=1");
388 DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");
389 DefineBuiltinMacro(Buf, "__NO_INLINE__=1");
390 DefineBuiltinMacro(Buf, "__PIC__=1");
391
392
393 if (PP.getLangOptions().CPlusPlus) {
394 DefineBuiltinMacro(Buf, "__DEPRECATED=1");
395 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
396 DefineBuiltinMacro(Buf, "__GNUG__=4");
397 DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
398 DefineBuiltinMacro(Buf, "__cplusplus=1");
399 DefineBuiltinMacro(Buf, "__private_extern__=extern");
400 }
401
402 // FIXME: Should emit a #line directive here.
403}
404
405
406/// EnterMainSourceFile - Enter the specified FileID as the main source file,
407/// which implicitly adds the builting defines etc.
408void Preprocessor::EnterMainSourceFile(unsigned MainFileID) {
409 // Enter the main file source buffer.
410 EnterSourceFile(MainFileID, 0);
411
412
413 std::vector<char> PrologFile;
414 PrologFile.reserve(4080);
415
416 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
417 InitializePredefinedMacros(*this, PrologFile);
418
419 // Add on the predefines from the driver.
420 PrologFile.insert(PrologFile.end(), Predefines,Predefines+strlen(Predefines));
421
422 // Memory buffer must end with a null byte!
423 PrologFile.push_back(0);
424
425 // Now that we have emitted the predefined macros, #includes, etc into
426 // PrologFile, preprocess it to populate the initial preprocessor state.
427 llvm::MemoryBuffer *SB =
428 llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(),
429 "<predefines>");
430 assert(SB && "Cannot fail to create predefined source buffer");
431 unsigned FileID = SourceMgr.createFileIDForMemBuffer(SB);
432 assert(FileID && "Could not create FileID for predefines?");
433
434 // Start parsing the predefines.
435 EnterSourceFile(FileID, 0);
436}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000437
Chris Lattnerd01e2912006-06-18 16:22:51 +0000438//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000439// Source File Location Methods.
440//===----------------------------------------------------------------------===//
441
Chris Lattner22eb9722006-06-18 05:43:12 +0000442/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
443/// return null on failure. isAngled indicates whether the file reference is
444/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnerb8b94f12006-10-30 05:38:06 +0000445const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
446 const char *FilenameEnd,
Chris Lattnerc8997182006-06-22 05:52:16 +0000447 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000448 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000449 const DirectoryLookup *&CurDir) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000450 // If the header lookup mechanism may be relative to the current file, pass in
451 // info about where the current file is.
452 const FileEntry *CurFileEnt = 0;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000453 if (!FromDir) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000454 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
455 CurFileEnt = SourceMgr.getFileEntryForLoc(FileLoc);
Chris Lattner22eb9722006-06-18 05:43:12 +0000456 }
457
Chris Lattner63dd32b2006-10-20 04:42:40 +0000458 // Do a standard file entry lookup.
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000459 CurDir = CurDirLookup;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000460 const FileEntry *FE =
Chris Lattner7cdbad92006-10-30 05:33:15 +0000461 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
462 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000463 if (FE) return FE;
464
465 // Otherwise, see if this is a subframework header. If so, this is relative
466 // to one of the headers on the #include stack. Walk the list of the current
467 // headers on the #include stack and pass them to HeaderInfo.
Chris Lattner5c683b22006-10-20 05:12:14 +0000468 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000469 CurFileEnt = SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000470 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
471 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000472 return FE;
473 }
474
475 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
476 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Chris Lattner5c683b22006-10-20 05:12:14 +0000477 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000478 CurFileEnt = SourceMgr.getFileEntryForLoc(ISEntry.TheLexer->getFileLoc());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000479 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
480 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000481 return FE;
482 }
483 }
484
485 // Otherwise, we really couldn't find the file.
486 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000487}
488
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000489/// isInPrimaryFile - Return true if we're in the top-level file, not in a
490/// #include.
491bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000492 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000493 return IncludeMacroStack.empty();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000494
Chris Lattner13044d92006-07-03 05:16:44 +0000495 // If there are any stacked lexers, we're in a #include.
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000496 assert(IncludeMacroStack[0].TheLexer &&
497 !IncludeMacroStack[0].TheLexer->Is_PragmaLexer &&
498 "Top level include stack isn't our primary lexer?");
499 for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000500 if (IncludeMacroStack[i].TheLexer &&
501 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000502 return false;
503 return true;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000504}
505
506/// getCurrentLexer - Return the current file lexer being lexed from. Note
507/// that this ignores any potentially active macro expansions and _Pragma
508/// expansions going on at the time.
509Lexer *Preprocessor::getCurrentFileLexer() const {
510 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
511
512 // Look for a stacked lexer.
513 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000514 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000515 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
516 return L;
517 }
518 return 0;
519}
520
521
Chris Lattner22eb9722006-06-18 05:43:12 +0000522/// EnterSourceFile - Add a source file to the top of the include stack and
523/// start lexing tokens from it instead of the current buffer. Return true
524/// on failure.
525void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000526 const DirectoryLookup *CurDir) {
Chris Lattner69772b02006-07-02 20:34:39 +0000527 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000528 ++NumEnteredSourceFiles;
529
Chris Lattner69772b02006-07-02 20:34:39 +0000530 if (MaxIncludeStackDepth < IncludeMacroStack.size())
531 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000532
Chris Lattner77e9de52007-07-20 16:52:03 +0000533 Lexer *TheLexer = new Lexer(SourceLocation::getFileLoc(FileID, 0), *this);
Chris Lattner69772b02006-07-02 20:34:39 +0000534 EnterSourceFileWithLexer(TheLexer, CurDir);
535}
Chris Lattner22eb9722006-06-18 05:43:12 +0000536
Chris Lattner69772b02006-07-02 20:34:39 +0000537/// EnterSourceFile - Add a source file to the top of the include stack and
538/// start lexing tokens from it instead of the current buffer.
539void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
540 const DirectoryLookup *CurDir) {
541
542 // Add the current lexer to the include stack.
543 if (CurLexer || CurMacroExpander)
544 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
545 CurMacroExpander));
546
547 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000548 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000549 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000550
551 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000552 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000553 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
554
555 // Get the file entry for the current file.
556 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000557 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000558 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000559
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000560 Callbacks->FileChanged(CurLexer->getFileLoc(),
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000561 PPCallbacks::EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000562 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000563}
564
Chris Lattner69772b02006-07-02 20:34:39 +0000565
566
Chris Lattner22eb9722006-06-18 05:43:12 +0000567/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000568/// tokens from it instead of the current buffer.
Chris Lattner146762e2007-07-20 16:59:19 +0000569void Preprocessor::EnterMacro(Token &Tok, MacroArgs *Args) {
Chris Lattner69772b02006-07-02 20:34:39 +0000570 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
571 CurMacroExpander));
572 CurLexer = 0;
573 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000574
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000575 if (NumCachedMacroExpanders == 0) {
576 CurMacroExpander = new MacroExpander(Tok, Args, *this);
577 } else {
578 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
579 CurMacroExpander->Init(Tok, Args);
580 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000581}
582
Chris Lattner7667d0d2006-07-16 18:16:58 +0000583/// EnterTokenStream - Add a "macro" context to the top of the include stack,
584/// which will cause the lexer to start returning the specified tokens. Note
585/// that these tokens will be re-macro-expanded when/if expansion is enabled.
586/// This method assumes that the specified stream of tokens has a permanent
587/// owner somewhere, so they do not need to be copied.
Chris Lattner146762e2007-07-20 16:59:19 +0000588void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000589 // Save our current state.
590 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
591 CurMacroExpander));
592 CurLexer = 0;
593 CurDirLookup = 0;
594
595 // Create a macro expander to expand from the specified token stream.
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000596 if (NumCachedMacroExpanders == 0) {
597 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
598 } else {
599 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
600 CurMacroExpander->Init(Toks, NumToks);
601 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000602}
603
604/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
605/// lexer stack. This should only be used in situations where the current
606/// state of the top-of-stack lexer is known.
607void Preprocessor::RemoveTopOfLexerStack() {
608 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000609
610 if (CurMacroExpander) {
611 // Delete or cache the now-dead macro expander.
612 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
613 delete CurMacroExpander;
614 else
615 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
616 } else {
617 delete CurLexer;
618 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000619 CurLexer = IncludeMacroStack.back().TheLexer;
620 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
621 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
622 IncludeMacroStack.pop_back();
623}
624
Chris Lattner22eb9722006-06-18 05:43:12 +0000625//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000626// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000627//===----------------------------------------------------------------------===//
628
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000629/// setMacroInfo - Specify a macro for this identifier.
630///
631void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
632 if (MI == 0) {
633 if (II->hasMacroDefinition()) {
634 Macros.erase(II);
635 II->setHasMacroDefinition(false);
636 }
637 } else {
638 Macros[II] = MI;
639 II->setHasMacroDefinition(true);
640 }
641}
642
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000643/// RegisterBuiltinMacro - Register the specified identifier in the identifier
644/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000645IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000646 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000647 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000648
649 // Mark it as being a macro that is builtin.
650 MacroInfo *MI = new MacroInfo(SourceLocation());
651 MI->setIsBuiltinMacro();
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000652 setMacroInfo(Id, MI);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000653 return Id;
654}
655
656
Chris Lattner677757a2006-06-28 05:26:32 +0000657/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
658/// identifier table.
659void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000660 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000661 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000662 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
663 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000664 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000665
666 // GCC Extensions.
667 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
668 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000669 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000670}
671
Chris Lattnerc2395832006-07-09 00:57:04 +0000672/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
673/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000674static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000675 const IdentifierInfo *MacroIdent,
676 Preprocessor &PP) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000677 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
678
679 // If the token isn't an identifier, it's always literally expanded.
680 if (II == 0) return true;
681
682 // If the identifier is a macro, and if that macro is enabled, it may be
683 // expanded so it's not a trivial expansion.
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000684 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000685 // Fast expanding "#define X X" is ok, because X would be disabled.
686 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000687 return false;
688
689 // If this is an object-like macro invocation, it is safe to trivially expand
690 // it.
691 if (MI->isObjectLike()) return true;
692
693 // If this is a function-like macro invocation, it's safe to trivially expand
694 // as long as the identifier is not a macro argument.
695 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
696 I != E; ++I)
697 if (*I == II)
698 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000699
Chris Lattnerc2395832006-07-09 00:57:04 +0000700 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000701}
702
Chris Lattnerc2395832006-07-09 00:57:04 +0000703
Chris Lattnerafe603f2006-07-11 04:02:46 +0000704/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
705/// lexed is a '('. If so, consume the token and return true, if not, this
706/// method should have no observable side-effect on the lexed tokens.
707bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000708 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000709 unsigned Val;
710 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000711 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000712 else
713 Val = CurMacroExpander->isNextTokenLParen();
714
715 if (Val == 2) {
Chris Lattner5c983792007-07-19 00:07:36 +0000716 // We have run off the end. If it's a source file we don't
717 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
718 // macro stack.
719 if (CurLexer)
720 return false;
721 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000722 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
723 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000724 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000725 else
726 Val = Entry.TheMacroExpander->isNextTokenLParen();
Chris Lattner5c983792007-07-19 00:07:36 +0000727
728 if (Val != 2)
729 break;
730
731 // Ran off the end of a source file?
732 if (Entry.TheLexer)
733 return false;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000734 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000735 }
736
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000737 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
738 // have found something that isn't a '(' or we found the end of the
739 // translation unit. In either case, return false.
740 if (Val != 1)
741 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000742
Chris Lattner146762e2007-07-20 16:59:19 +0000743 Token Tok;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000744 LexUnexpandedToken(Tok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000745 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000746 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000747}
Chris Lattner677757a2006-06-28 05:26:32 +0000748
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000749/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
750/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner146762e2007-07-20 16:59:19 +0000751bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000752 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000753
754 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
755 if (MI->isBuiltinMacro()) {
756 ExpandBuiltinMacro(Identifier);
757 return false;
758 }
759
Chris Lattner81278c62006-10-14 19:03:49 +0000760 // If this is the first use of a target-specific macro, warn about it.
761 if (MI->isTargetSpecific()) {
762 MI->setIsTargetSpecific(false); // Don't warn on second use.
763 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
764 diag::port_target_macro_use);
765 }
766
Chris Lattneree8760b2006-07-15 07:42:55 +0000767 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000768 /// for each macro argument, the list of tokens that were provided to the
769 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000770 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000771
772 // If this is a function-like macro, read the arguments.
773 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000774 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner24dbee72007-07-19 16:11:58 +0000775 // name isn't a '(', this macro should not be expanded. Otherwise, consume
776 // it.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000777 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000778 return true;
779
Chris Lattner78186052006-07-09 00:45:31 +0000780 // Remember that we are now parsing the arguments to a macro invocation.
781 // Preprocessor directives used inside macro arguments are not portable, and
782 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000783 InMacroArgs = true;
784 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000785
786 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000787 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000788
789 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000790 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000791
792 ++NumFnMacroExpanded;
793 } else {
794 ++NumMacroExpanded;
795 }
Chris Lattner13044d92006-07-03 05:16:44 +0000796
797 // Notice that this macro has been used.
798 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000799
800 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000801
802 // If this macro expands to no tokens, don't bother to push it onto the
803 // expansion stack, only to take it right back off.
804 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000805 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000806 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000807
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000808 // Ignore this macro use, just return the next token in the current
809 // buffer.
810 bool HadLeadingSpace = Identifier.hasLeadingSpace();
811 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
812
813 Lex(Identifier);
814
815 // If the identifier isn't on some OTHER line, inherit the leading
816 // whitespace/first-on-a-line property of this token. This handles
817 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
818 // empty.
819 if (!Identifier.isAtStartOfLine()) {
Chris Lattner146762e2007-07-20 16:59:19 +0000820 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
821 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000822 }
823 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000824 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000825
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000826 } else if (MI->getNumTokens() == 1 &&
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000827 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
828 *this)){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000829 // Otherwise, if this macro expands into a single trivially-expanded
830 // token: expand it now. This handles common cases like
831 // "#define VAL 42".
832
833 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
834 // identifier to the expanded token.
835 bool isAtStartOfLine = Identifier.isAtStartOfLine();
836 bool hasLeadingSpace = Identifier.hasLeadingSpace();
837
838 // Remember where the token is instantiated.
839 SourceLocation InstantiateLoc = Identifier.getLocation();
840
841 // Replace the result token.
842 Identifier = MI->getReplacementToken(0);
843
844 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner146762e2007-07-20 16:59:19 +0000845 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
846 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000847
848 // Update the tokens location to include both its logical and physical
849 // locations.
850 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000851 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000852 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000853
Chris Lattner6e4bf522006-07-27 06:59:25 +0000854 // If this is #define X X, we must mark the result as unexpandible.
855 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000856 if (getMacroInfo(NewII) == MI)
Chris Lattner146762e2007-07-20 16:59:19 +0000857 Identifier.setFlag(Token::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000858
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000859 // Since this is not an identifier token, it can't be macro expanded, so
860 // we're done.
861 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000862 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000863 }
864
Chris Lattner78186052006-07-09 00:45:31 +0000865 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000866 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000867
868 // Now that the macro is at the top of the include stack, ask the
869 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000870 Lex(Identifier);
871 return false;
872}
873
Chris Lattneree8760b2006-07-15 07:42:55 +0000874/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000875/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000876/// invocation. This returns null on error.
Chris Lattner146762e2007-07-20 16:59:19 +0000877MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattneree8760b2006-07-15 07:42:55 +0000878 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000879 // The number of fixed arguments to parse.
880 unsigned NumFixedArgsLeft = MI->getNumArgs();
881 bool isVariadic = MI->isVariadic();
882
Chris Lattner78186052006-07-09 00:45:31 +0000883 // Outer loop, while there are more arguments, keep reading them.
Chris Lattner146762e2007-07-20 16:59:19 +0000884 Token Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000885 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000886 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000887
888 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000889 // argument is separated by an EOF token. Use a SmallVector so we can avoid
890 // heap allocations in the common case.
Chris Lattner146762e2007-07-20 16:59:19 +0000891 llvm::SmallVector<Token, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000892
893 unsigned NumActuals = 0;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000894 while (Tok.is(tok::comma)) {
Chris Lattner24dbee72007-07-19 16:11:58 +0000895 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
896 // that we already consumed the first one.
Chris Lattner78186052006-07-09 00:45:31 +0000897 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000898
Chris Lattner78186052006-07-09 00:45:31 +0000899 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000900 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
901 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000902 LexUnexpandedToken(Tok);
903
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000904 if (Tok.is(tok::eof)) {
Chris Lattner78186052006-07-09 00:45:31 +0000905 Diag(MacroName, diag::err_unterm_macro_invoc);
906 // Do not lose the EOF. Return it to the client.
907 MacroName = Tok;
908 return 0;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000909 } else if (Tok.is(tok::r_paren)) {
Chris Lattner78186052006-07-09 00:45:31 +0000910 // If we found the ) token, the macro arg list is done.
911 if (NumParens-- == 0)
912 break;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000913 } else if (Tok.is(tok::l_paren)) {
Chris Lattner78186052006-07-09 00:45:31 +0000914 ++NumParens;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000915 } else if (Tok.is(tok::comma) && NumParens == 0) {
Chris Lattner78186052006-07-09 00:45:31 +0000916 // Comma ends this argument if there are more fixed arguments expected.
917 if (NumFixedArgsLeft)
918 break;
919
Chris Lattner2ada5d32006-07-15 07:51:24 +0000920 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000921 if (!isVariadic) {
922 // Emit the diagnostic at the macro name in case there is a missing ).
923 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000924 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000925 return 0;
926 }
927 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000928 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
Chris Lattner457fc152006-07-29 06:30:25 +0000929 // If this is a comment token in the argument list and we're just in
930 // -C mode (not -CC mode), discard the comment.
931 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000932 }
933
934 ArgTokens.push_back(Tok);
935 }
936
Chris Lattnera12dd152006-07-11 04:09:02 +0000937 // Empty arguments are standard in C99 and supported as an extension in
938 // other modes.
939 if (ArgTokens.empty() && !Features.C99)
940 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000941
Chris Lattner36b6e812006-07-21 06:38:30 +0000942 // Add a marker EOF token to the end of the token list for this argument.
Chris Lattner146762e2007-07-20 16:59:19 +0000943 Token EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +0000944 EOFTok.startToken();
945 EOFTok.setKind(tok::eof);
946 EOFTok.setLocation(Tok.getLocation());
947 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +0000948 ArgTokens.push_back(EOFTok);
949 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000950 --NumFixedArgsLeft;
951 };
952
953 // Okay, we either found the r_paren. Check to see if we parsed too few
954 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000955 unsigned MinArgsExpected = MI->getNumArgs();
956
Chris Lattner775d8322006-07-29 04:39:41 +0000957 // See MacroArgs instance var for description of this.
958 bool isVarargsElided = false;
959
Chris Lattner2ada5d32006-07-15 07:51:24 +0000960 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000961 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000962 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000963 // Varargs where the named vararg parameter is missing: ok as extension.
964 // #define A(x, ...)
965 // A("blah")
966 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000967
968 // Remember this occurred if this is a C99 macro invocation with at least
969 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000970 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000971 } else if (MI->getNumArgs() == 1) {
972 // #define A(x)
973 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000974 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000975
976 // Empty arguments are standard in C99 and supported as an extension in
977 // other modes.
978 if (ArgTokens.empty() && !Features.C99)
979 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000980 } else {
981 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000982 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000983 return 0;
984 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000985
986 // Add a marker EOF token to the end of the token list for this argument.
987 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +0000988 Tok.startToken();
989 Tok.setKind(tok::eof);
990 Tok.setLocation(EndLoc);
991 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +0000992 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000993 }
994
Chris Lattner775d8322006-07-29 04:39:41 +0000995 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000996}
997
Chris Lattnerc673f902006-06-30 06:10:41 +0000998/// ComputeDATE_TIME - Compute the current time, enter it into the specified
999/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
1000/// the identifier tokens inserted.
1001static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001002 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +00001003 time_t TT = time(0);
1004 struct tm *TM = localtime(&TT);
1005
1006 static const char * const Months[] = {
1007 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
1008 };
1009
1010 char TmpBuffer[100];
1011 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
1012 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001013 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +00001014
1015 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001016 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +00001017}
1018
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001019/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1020/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner146762e2007-07-20 16:59:19 +00001021void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001022 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001023 IdentifierInfo *II = Tok.getIdentifierInfo();
1024 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +00001025
1026 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
1027 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001028 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +00001029 return Handle_Pragma(Tok);
1030
Chris Lattner78186052006-07-09 00:45:31 +00001031 ++NumBuiltinMacroExpanded;
1032
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001033 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +00001034
1035 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +00001036 Tok.setIdentifierInfo(0);
Chris Lattner146762e2007-07-20 16:59:19 +00001037 Tok.clearFlag(Token::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +00001038
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001039 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001040 // __LINE__ expands to a simple numeric value.
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001041 sprintf(TmpBuffer, "%u", SourceMgr.getLogicalLineNumber(Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001042 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +00001043 Tok.setKind(tok::numeric_constant);
1044 Tok.setLength(Length);
1045 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001046 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +00001047 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001048 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +00001049 Diag(Tok, diag::ext_pp_base_file);
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001050 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc);
1051 while (NextLoc.isValid()) {
Chris Lattnerc1283b92006-07-01 23:16:30 +00001052 Loc = NextLoc;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001053 NextLoc = SourceMgr.getIncludeLoc(Loc);
Chris Lattnerc1283b92006-07-01 23:16:30 +00001054 }
1055 }
1056
Chris Lattner0766e592006-07-03 01:07:01 +00001057 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001058 std::string FN = SourceMgr.getSourceName(SourceMgr.getLogicalLoc(Loc));
Chris Lattnerecc39e92006-07-15 05:23:31 +00001059 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +00001060 Tok.setKind(tok::string_literal);
1061 Tok.setLength(FN.size());
1062 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001063 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +00001064 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001065 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +00001066 Tok.setKind(tok::string_literal);
1067 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1068 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001069 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +00001070 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001071 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +00001072 Tok.setKind(tok::string_literal);
1073 Tok.setLength(strlen("\"hh:mm:ss\""));
1074 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001075 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +00001076 Diag(Tok, diag::ext_pp_include_level);
1077
1078 // Compute the include depth of this token.
1079 unsigned Depth = 0;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001080 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation());
1081 for (; Loc.isValid(); ++Depth)
1082 Loc = SourceMgr.getIncludeLoc(Loc);
Chris Lattnerc1283b92006-07-01 23:16:30 +00001083
1084 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1085 sprintf(TmpBuffer, "%u", Depth);
1086 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +00001087 Tok.setKind(tok::numeric_constant);
1088 Tok.setLength(Length);
1089 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001090 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +00001091 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1092 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1093 Diag(Tok, diag::ext_pp_timestamp);
1094
1095 // Get the file that we are lexing out of. If we're currently lexing from
1096 // a macro, dig into the include stack.
1097 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +00001098 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +00001099
1100 if (TheLexer)
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001101 CurFile = SourceMgr.getFileEntryForLoc(TheLexer->getFileLoc());
Chris Lattner847e0e42006-07-01 23:49:16 +00001102
1103 // If this file is older than the file it depends on, emit a diagnostic.
1104 const char *Result;
1105 if (CurFile) {
1106 time_t TT = CurFile->getModificationTime();
1107 struct tm *TM = localtime(&TT);
1108 Result = asctime(TM);
1109 } else {
1110 Result = "??? ??? ?? ??:??:?? ????\n";
1111 }
1112 TmpBuffer[0] = '"';
1113 strcpy(TmpBuffer+1, Result);
1114 unsigned Len = strlen(TmpBuffer);
1115 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +00001116 Tok.setKind(tok::string_literal);
1117 Tok.setLength(Len);
1118 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001119 } else {
1120 assert(0 && "Unknown identifier!");
1121 }
1122}
Chris Lattner677757a2006-06-28 05:26:32 +00001123
1124//===----------------------------------------------------------------------===//
1125// Lexer Event Handling.
1126//===----------------------------------------------------------------------===//
1127
Chris Lattnercefc7682006-07-08 08:28:12 +00001128/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
1129/// identifier information for the token and install it into the token.
Chris Lattner146762e2007-07-20 16:59:19 +00001130IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
Chris Lattnercefc7682006-07-08 08:28:12 +00001131 const char *BufPtr) {
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001132 assert(Identifier.is(tok::identifier) && "Not an identifier!");
Chris Lattnercefc7682006-07-08 08:28:12 +00001133 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
1134
1135 // Look up this token, see if it is a macro, or if it is a language keyword.
1136 IdentifierInfo *II;
1137 if (BufPtr && !Identifier.needsCleaning()) {
1138 // No cleaning needed, just use the characters from the lexed buffer.
1139 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
1140 } else {
1141 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Chris Lattnerf9aba2c2007-07-13 17:10:38 +00001142 llvm::SmallVector<char, 64> IdentifierBuffer;
1143 IdentifierBuffer.resize(Identifier.getLength());
1144 const char *TmpBuf = &IdentifierBuffer[0];
Chris Lattnercefc7682006-07-08 08:28:12 +00001145 unsigned Size = getSpelling(Identifier, TmpBuf);
1146 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
1147 }
Chris Lattner8c204872006-10-14 05:19:21 +00001148 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001149 return II;
1150}
1151
1152
Chris Lattner677757a2006-06-28 05:26:32 +00001153/// HandleIdentifier - This callback is invoked when the lexer reads an
1154/// identifier. This callback looks up the identifier in the map and/or
1155/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattner146762e2007-07-20 16:59:19 +00001156void Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +00001157 assert(Identifier.getIdentifierInfo() &&
1158 "Can't handle identifiers without identifier info!");
1159
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001160 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +00001161
1162 // If this identifier was poisoned, and if it was not produced from a macro
1163 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +00001164 if (II.isPoisoned() && CurLexer) {
1165 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
1166 Diag(Identifier, diag::err_pp_used_poisoned_id);
1167 else
1168 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
1169 }
Chris Lattner677757a2006-06-28 05:26:32 +00001170
Chris Lattner78186052006-07-09 00:45:31 +00001171 // If this is a macro to be expanded, do it.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001172 if (MacroInfo *MI = getMacroInfo(&II)) {
Chris Lattner6e4bf522006-07-27 06:59:25 +00001173 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
1174 if (MI->isEnabled()) {
1175 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1176 return;
1177 } else {
1178 // C99 6.10.3.4p2 says that a disabled macro may never again be
1179 // expanded, even if it's in a context where it could be expanded in the
1180 // future.
Chris Lattner146762e2007-07-20 16:59:19 +00001181 Identifier.setFlag(Token::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +00001182 }
1183 }
Chris Lattner063400e2006-10-14 19:54:15 +00001184 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
1185 // If this identifier is a macro on some other target, emit a diagnostic.
1186 // This diagnosic is only emitted when macro expansion is enabled, because
1187 // the macro would not have been expanded for the other target either.
1188 II.setIsOtherTargetMacro(false); // Don't warn on second use.
1189 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
1190 diag::port_target_macro_use);
1191
1192 }
Chris Lattner677757a2006-06-28 05:26:32 +00001193
Chris Lattner5b9f4892006-11-21 17:23:33 +00001194 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
1195 // then we act as if it is the actual operator and not the textual
1196 // representation of it.
1197 if (II.isCPlusPlusOperatorKeyword())
1198 Identifier.setIdentifierInfo(0);
1199
Chris Lattner677757a2006-06-28 05:26:32 +00001200 // Change the kind of this identifier to the appropriate token kind, e.g.
1201 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +00001202 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +00001203
1204 // If this is an extension token, diagnose its use.
Steve Naroffa8fd9732007-06-11 00:35:03 +00001205 // FIXME: tried (unsuccesfully) to shut this up when compiling with gnu99
1206 // For now, I'm just commenting it out (while I work on attributes).
Chris Lattner53621a52007-06-13 20:44:40 +00001207 if (II.isExtensionToken() && Features.C99)
1208 Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +00001209}
1210
Chris Lattner22eb9722006-06-18 05:43:12 +00001211/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1212/// the current file. This either returns the EOF token or pops a level off
1213/// the include stack and keeps going.
Chris Lattner146762e2007-07-20 16:59:19 +00001214bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001215 assert(!CurMacroExpander &&
1216 "Ending a file when currently in a macro!");
1217
Chris Lattner371ac8a2006-07-04 07:11:10 +00001218 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001219 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001220 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001221 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001222 // Okay, this has a controlling macro, remember in PerFileInfo.
1223 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001224 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001225 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001226 }
1227 }
1228
Chris Lattner22eb9722006-06-18 05:43:12 +00001229 // If this is a #include'd file, pop it off the include stack and continue
1230 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001231 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001232 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001233 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001234
1235 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001236 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001237 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1238
1239 // Get the file entry for the current file.
1240 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001241 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001242 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001243
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001244 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1245 PPCallbacks::ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001246 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001247
1248 // Client should lex another token.
1249 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001250 }
1251
Chris Lattner8c204872006-10-14 05:19:21 +00001252 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +00001253 CurLexer->BufferPtr = CurLexer->BufferEnd;
1254 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +00001255 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001256
1257 // We're done with the #included file.
1258 delete CurLexer;
1259 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001260
Chris Lattner03f83482006-07-10 06:16:26 +00001261 // This is the end of the top-level file. If the diag::pp_macro_not_used
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001262 // diagnostic is enabled, look for macros that have not been used.
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001263 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001264 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
1265 Macros.begin(), E = Macros.end(); I != E; ++I) {
1266 if (!I->second->isUsed())
1267 Diag(I->second->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001268 }
1269 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001270 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001271}
1272
1273/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001274/// the current macro expansion or token stream expansion.
Chris Lattner146762e2007-07-20 16:59:19 +00001275bool Preprocessor::HandleEndOfMacro(Token &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001276 assert(CurMacroExpander && !CurLexer &&
1277 "Ending a macro when currently in a #include file!");
1278
Chris Lattnerc02c4ab2007-07-15 00:25:26 +00001279 // Delete or cache the now-dead macro expander.
1280 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
1281 delete CurMacroExpander;
1282 else
1283 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
Chris Lattner22eb9722006-06-18 05:43:12 +00001284
Chris Lattner69772b02006-07-02 20:34:39 +00001285 // Handle this like a #include file being popped off the stack.
1286 CurMacroExpander = 0;
1287 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001288}
1289
1290
1291//===----------------------------------------------------------------------===//
1292// Utility Methods for Preprocessor Directive Handling.
1293//===----------------------------------------------------------------------===//
1294
1295/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1296/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001297void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner146762e2007-07-20 16:59:19 +00001298 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00001299 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001300 LexUnexpandedToken(Tmp);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001301 } while (Tmp.isNot(tok::eom));
Chris Lattner22eb9722006-06-18 05:43:12 +00001302}
1303
Chris Lattner652c1692006-11-21 23:47:30 +00001304/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
1305static bool isCXXNamedOperator(const std::string &Spelling) {
1306 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
1307 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
1308 Spelling == "or" || Spelling == "xor";
1309}
1310
Chris Lattner22eb9722006-06-18 05:43:12 +00001311/// ReadMacroName - Lex and validate a macro name, which occurs after a
1312/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001313/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1314/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001315/// else (e.g. #ifdef).
Chris Lattner146762e2007-07-20 16:59:19 +00001316void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001317 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001318 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001319
1320 // Missing macro name?
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001321 if (MacroNameTok.is(tok::eom))
Chris Lattner22eb9722006-06-18 05:43:12 +00001322 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1323
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001324 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1325 if (II == 0) {
Chris Lattner652c1692006-11-21 23:47:30 +00001326 std::string Spelling = getSpelling(MacroNameTok);
1327 if (isCXXNamedOperator(Spelling))
1328 // C++ 2.5p2: Alternative tokens behave the same as its primary token
1329 // except for their spellings.
1330 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
1331 else
1332 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001333 // Fall through on error.
Chris Lattner2bb8a952006-11-21 22:24:17 +00001334 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001335 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001336 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattner259716a2007-10-07 08:04:56 +00001337 } else if (isDefineUndef && II->hasMacroDefinition() &&
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001338 getMacroInfo(II)->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001339 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001340 if (isDefineUndef == 1)
1341 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1342 else
1343 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001344 } else {
1345 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001346 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001347 }
1348
Chris Lattner22eb9722006-06-18 05:43:12 +00001349 // Invalid macro name, read and discard the rest of the line. Then set the
1350 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001351 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001352 return DiscardUntilEndOfDirective();
1353}
1354
1355/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1356/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001357void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner146762e2007-07-20 16:59:19 +00001358 Token Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001359 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001360 // There should be no tokens after the directive, but we allow them as an
1361 // extension.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001362 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001363 Lex(Tmp);
1364
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001365 if (Tmp.isNot(tok::eom)) {
Chris Lattnercb283342006-06-18 06:48:37 +00001366 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1367 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001368 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001369}
1370
1371
1372
1373/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1374/// decided that the subsequent tokens are in the #if'd out portion of the
1375/// file. Lex the rest of the file, until we see an #endif. If
1376/// FoundNonSkipPortion is true, then we have already emitted code for part of
1377/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1378/// is true, then #else directives are ok, if not, then we have already seen one
1379/// so a #else directive is a duplicate. When this returns, the caller can lex
1380/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001381void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001382 bool FoundNonSkipPortion,
1383 bool FoundElse) {
1384 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001385 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001386 "Lexing a macro, not a file?");
1387
1388 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1389 FoundNonSkipPortion, FoundElse);
1390
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001391 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1392 // disabling warnings, etc.
1393 CurLexer->LexingRawMode = true;
Chris Lattner146762e2007-07-20 16:59:19 +00001394 Token Tok;
Chris Lattner22eb9722006-06-18 05:43:12 +00001395 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001396 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001397
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001398 // If this is the end of the buffer, we have an error.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001399 if (Tok.is(tok::eof)) {
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001400 // Emit errors for each unterminated conditional on the stack, including
1401 // the current one.
1402 while (!CurLexer->ConditionalStack.empty()) {
1403 Diag(CurLexer->ConditionalStack.back().IfLoc,
1404 diag::err_pp_unterminated_conditional);
1405 CurLexer->ConditionalStack.pop_back();
1406 }
1407
1408 // Just return and let the caller lex after this #include.
1409 break;
1410 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001411
1412 // If this token is not a preprocessor directive, just skip it.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001413 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
Chris Lattner22eb9722006-06-18 05:43:12 +00001414 continue;
1415
1416 // We just parsed a # character at the start of a line, so we're in
1417 // directive mode. Tell the lexer this so any newlines we see will be
1418 // converted into an EOM token (this terminates the macro).
1419 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001420 CurLexer->KeepCommentMode = false;
1421
Chris Lattner22eb9722006-06-18 05:43:12 +00001422
1423 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001424 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001425
1426 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1427 // something bogus), skip it.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001428 if (Tok.isNot(tok::identifier)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001429 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001430 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001431 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001432 continue;
1433 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001434
Chris Lattner22eb9722006-06-18 05:43:12 +00001435 // If the first letter isn't i or e, it isn't intesting to us. We know that
1436 // this is safe in the face of spelling differences, because there is no way
1437 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001438 // allows us to avoid looking up the identifier info for #define/#undef and
1439 // other common directives.
1440 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1441 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001442 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1443 FirstChar != 'i' && FirstChar != 'e') {
1444 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001445 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001446 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001447 continue;
1448 }
1449
Chris Lattnere60165f2006-06-22 06:36:29 +00001450 // Get the identifier name without trigraphs or embedded newlines. Note
1451 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1452 // when skipping.
1453 // TODO: could do this with zero copies in the no-clean case by using
1454 // strncmp below.
1455 char Directive[20];
1456 unsigned IdLen;
1457 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1458 IdLen = Tok.getLength();
1459 memcpy(Directive, RawCharData, IdLen);
1460 Directive[IdLen] = 0;
1461 } else {
1462 std::string DirectiveStr = getSpelling(Tok);
1463 IdLen = DirectiveStr.size();
1464 if (IdLen >= 20) {
1465 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001466 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001467 CurLexer->KeepCommentMode = KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001468 continue;
1469 }
1470 memcpy(Directive, &DirectiveStr[0], IdLen);
1471 Directive[IdLen] = 0;
1472 }
1473
Chris Lattner22eb9722006-06-18 05:43:12 +00001474 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001475 if ((IdLen == 2) || // "if"
1476 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1477 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001478 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1479 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001480 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001481 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001482 /*foundnonskip*/false,
1483 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001484 }
1485 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001486 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001487 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001488 PPConditionalInfo CondInfo;
1489 CondInfo.WasSkipping = true; // Silence bogus warning.
1490 bool InCond = CurLexer->popConditionalLevel(CondInfo);
Chris Lattnercf6bc662006-11-05 07:59:08 +00001491 InCond = InCond; // Silence warning in no-asserts mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00001492 assert(!InCond && "Can't be skipping if not in a conditional!");
1493
1494 // If we popped the outermost skipping block, we're done skipping!
1495 if (!CondInfo.WasSkipping)
1496 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001497 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001498 // #else directive in a skipping conditional. If not in some other
1499 // skipping conditional, and if #else hasn't already been seen, enter it
1500 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001501 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001502 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1503
1504 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001505 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001506
1507 // Note that we've seen a #else in this conditional.
1508 CondInfo.FoundElse = true;
1509
1510 // If the conditional is at the top level, and the #if block wasn't
1511 // entered, enter the #else block now.
1512 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1513 CondInfo.FoundNonSkip = true;
1514 break;
1515 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001516 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001517 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1518
1519 bool ShouldEnter;
1520 // If this is in a skipping block or if we're already handled this #if
1521 // block, don't bother parsing the condition.
1522 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001523 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001524 ShouldEnter = false;
1525 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001526 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001527 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001528 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1529 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001530 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001531 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001532 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001533 }
1534
1535 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001536 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001537
1538 // If this condition is true, enter it!
1539 if (ShouldEnter) {
1540 CondInfo.FoundNonSkip = true;
1541 break;
1542 }
1543 }
1544 }
1545
1546 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001547 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001548 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001549 }
1550
1551 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1552 // of the file, just stop skipping and return to lexing whatever came after
1553 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001554 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001555}
1556
1557//===----------------------------------------------------------------------===//
1558// Preprocessor Directive Handling.
1559//===----------------------------------------------------------------------===//
1560
1561/// HandleDirective - This callback is invoked when the lexer sees a # token
1562/// at the start of a line. This consumes the directive, modifies the
1563/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1564/// read is the correct one.
Chris Lattner146762e2007-07-20 16:59:19 +00001565void Preprocessor::HandleDirective(Token &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001566 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001567
1568 // We just parsed a # character at the start of a line, so we're in directive
1569 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001570 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001571 CurLexer->ParsingPreprocessorDirective = true;
1572
1573 ++NumDirectives;
1574
Chris Lattner371ac8a2006-07-04 07:11:10 +00001575 // We are about to read a token. For the multiple-include optimization FA to
1576 // work, we have to remember if we had read any tokens *before* this
1577 // pp-directive.
1578 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1579
Chris Lattner78186052006-07-09 00:45:31 +00001580 // Read the next token, the directive flavor. This isn't expanded due to
1581 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001582 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001583
Chris Lattner78186052006-07-09 00:45:31 +00001584 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1585 // #define A(x) #x
1586 // A(abc
1587 // #warning blah
1588 // def)
1589 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001590 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001591 Diag(Result, diag::ext_embedded_directive);
1592
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001593TryAgain:
Chris Lattner22eb9722006-06-18 05:43:12 +00001594 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001595 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001596 return; // null directive.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001597 case tok::comment:
1598 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1599 LexUnexpandedToken(Result);
1600 goto TryAgain;
Chris Lattner22eb9722006-06-18 05:43:12 +00001601
Chris Lattner22eb9722006-06-18 05:43:12 +00001602 case tok::numeric_constant:
1603 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001604 DiscardUntilEndOfDirective();
1605 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001606 default:
1607 IdentifierInfo *II = Result.getIdentifierInfo();
1608 if (II == 0) break; // Not an identifier.
1609
1610 // Ask what the preprocessor keyword ID is.
1611 switch (II->getPPKeywordID()) {
1612 default: break;
1613 // C99 6.10.1 - Conditional Inclusion.
1614 case tok::pp_if:
1615 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1616 case tok::pp_ifdef:
1617 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1618 case tok::pp_ifndef:
1619 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1620 case tok::pp_elif:
1621 return HandleElifDirective(Result);
1622 case tok::pp_else:
1623 return HandleElseDirective(Result);
1624 case tok::pp_endif:
1625 return HandleEndifDirective(Result);
1626
1627 // C99 6.10.2 - Source File Inclusion.
1628 case tok::pp_include:
1629 return HandleIncludeDirective(Result); // Handle #include.
1630
1631 // C99 6.10.3 - Macro Replacement.
1632 case tok::pp_define:
1633 return HandleDefineDirective(Result, false);
1634 case tok::pp_undef:
1635 return HandleUndefDirective(Result);
1636
1637 // C99 6.10.4 - Line Control.
1638 case tok::pp_line:
1639 // FIXME: implement #line
1640 DiscardUntilEndOfDirective();
1641 return;
1642
1643 // C99 6.10.5 - Error Directive.
1644 case tok::pp_error:
1645 return HandleUserDiagnosticDirective(Result, false);
1646
1647 // C99 6.10.6 - Pragma Directive.
1648 case tok::pp_pragma:
1649 return HandlePragmaDirective();
1650
1651 // GNU Extensions.
1652 case tok::pp_import:
1653 return HandleImportDirective(Result);
1654 case tok::pp_include_next:
1655 return HandleIncludeNextDirective(Result);
1656
1657 case tok::pp_warning:
1658 Diag(Result, diag::ext_pp_warning_directive);
1659 return HandleUserDiagnosticDirective(Result, true);
1660 case tok::pp_ident:
1661 return HandleIdentSCCSDirective(Result);
1662 case tok::pp_sccs:
1663 return HandleIdentSCCSDirective(Result);
1664 case tok::pp_assert:
1665 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001666 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001667 case tok::pp_unassert:
1668 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001669 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001670
1671 // clang extensions.
1672 case tok::pp_define_target:
1673 return HandleDefineDirective(Result, true);
1674 case tok::pp_define_other_target:
1675 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001676 }
1677 break;
1678 }
1679
1680 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001681 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001682
1683 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001684 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001685
1686 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001687}
1688
Chris Lattner146762e2007-07-20 16:59:19 +00001689void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001690 bool isWarning) {
1691 // Read the rest of the line raw. We do this because we don't want macros
1692 // to be expanded and we don't require that the tokens be valid preprocessing
1693 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1694 // collapse multiple consequtive white space between tokens, but this isn't
1695 // specified by the standard.
1696 std::string Message = CurLexer->ReadToEndOfLine();
1697
1698 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001699 return Diag(Tok, DiagID, Message);
1700}
1701
1702/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1703///
Chris Lattner146762e2007-07-20 16:59:19 +00001704void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001705 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001706 Diag(Tok, diag::ext_pp_ident_directive);
1707
Chris Lattner371ac8a2006-07-04 07:11:10 +00001708 // Read the string argument.
Chris Lattner146762e2007-07-20 16:59:19 +00001709 Token StrTok;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001710 Lex(StrTok);
1711
1712 // If the token kind isn't a string, it's a malformed directive.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001713 if (StrTok.isNot(tok::string_literal) &&
1714 StrTok.isNot(tok::wide_string_literal))
Chris Lattner01d66cc2006-07-03 22:16:27 +00001715 return Diag(StrTok, diag::err_pp_malformed_ident);
1716
1717 // Verify that there is nothing after the string, other than EOM.
1718 CheckEndOfDirective("#ident");
1719
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001720 if (Callbacks)
1721 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001722}
1723
Chris Lattnerb8761832006-06-24 21:31:03 +00001724//===----------------------------------------------------------------------===//
1725// Preprocessor Include Directive Handling.
1726//===----------------------------------------------------------------------===//
1727
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001728/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1729/// checked and spelled filename, e.g. as an operand of #include. This returns
1730/// true if the input filename was in <>'s or false if it were in ""'s. The
1731/// caller is expected to provide a buffer that is large enough to hold the
1732/// spelling of the filename, but is also expected to handle the case when
1733/// this method decides to use a different buffer.
Chris Lattner93ab9f12007-07-23 04:15:27 +00001734bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001735 const char *&BufStart,
1736 const char *&BufEnd) {
1737 // Get the text form of the filename.
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001738 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1739
1740 // Make sure the filename is <x> or "x".
1741 bool isAngled;
1742 if (BufStart[0] == '<') {
1743 if (BufEnd[-1] != '>') {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001744 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001745 BufStart = 0;
1746 return true;
1747 }
1748 isAngled = true;
1749 } else if (BufStart[0] == '"') {
1750 if (BufEnd[-1] != '"') {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001751 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001752 BufStart = 0;
1753 return true;
1754 }
1755 isAngled = false;
1756 } else {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001757 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001758 BufStart = 0;
1759 return true;
1760 }
1761
1762 // Diagnose #include "" as invalid.
1763 if (BufEnd-BufStart <= 2) {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001764 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001765 BufStart = 0;
1766 return "";
1767 }
1768
1769 // Skip the brackets.
1770 ++BufStart;
1771 --BufEnd;
1772 return isAngled;
1773}
1774
Chris Lattner43eafb42007-07-23 04:56:47 +00001775/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1776/// from a macro as multiple tokens, which need to be glued together. This
1777/// occurs for code like:
1778/// #define FOO <a/b.h>
1779/// #include FOO
1780/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1781///
1782/// This code concatenates and consumes tokens up to the '>' token. It returns
1783/// false if the > was found, otherwise it returns true if it finds and consumes
1784/// the EOM marker.
1785static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
1786 Preprocessor &PP) {
1787 Token CurTok;
1788
1789 PP.Lex(CurTok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001790 while (CurTok.isNot(tok::eom)) {
Chris Lattner43eafb42007-07-23 04:56:47 +00001791 // Append the spelling of this token to the buffer. If there was a space
1792 // before it, add it now.
1793 if (CurTok.hasLeadingSpace())
1794 FilenameBuffer.push_back(' ');
1795
1796 // Get the spelling of the token, directly into FilenameBuffer if possible.
1797 unsigned PreAppendSize = FilenameBuffer.size();
1798 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
1799
1800 const char *BufPtr = &FilenameBuffer[PreAppendSize];
1801 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
1802
1803 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1804 if (BufPtr != &FilenameBuffer[PreAppendSize])
1805 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1806
1807 // Resize FilenameBuffer to the correct size.
1808 if (CurTok.getLength() != ActualLen)
1809 FilenameBuffer.resize(PreAppendSize+ActualLen);
1810
1811 // If we found the '>' marker, return success.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001812 if (CurTok.is(tok::greater))
Chris Lattner43eafb42007-07-23 04:56:47 +00001813 return false;
1814
1815 PP.Lex(CurTok);
1816 }
1817
1818 // If we hit the eom marker, emit an error and return true so that the caller
1819 // knows the EOM has been read.
1820 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
1821 return true;
1822}
1823
Chris Lattner22eb9722006-06-18 05:43:12 +00001824/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1825/// file to be included from the lexer, then include it! This is a common
1826/// routine with functionality shared between #include, #include_next and
1827/// #import.
Chris Lattner146762e2007-07-20 16:59:19 +00001828void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001829 const DirectoryLookup *LookupFrom,
1830 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001831
Chris Lattner146762e2007-07-20 16:59:19 +00001832 Token FilenameTok;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001833 CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001834
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001835 // Reserve a buffer to get the spelling.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001836 llvm::SmallVector<char, 128> FilenameBuffer;
Chris Lattner43eafb42007-07-23 04:56:47 +00001837 const char *FilenameStart, *FilenameEnd;
1838
1839 switch (FilenameTok.getKind()) {
1840 case tok::eom:
1841 // If the token kind is EOM, the error has already been diagnosed.
1842 return;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001843
Chris Lattner43eafb42007-07-23 04:56:47 +00001844 case tok::angle_string_literal:
Chris Lattnerf97dbcb2007-07-23 22:23:52 +00001845 case tok::string_literal: {
Chris Lattner43eafb42007-07-23 04:56:47 +00001846 FilenameBuffer.resize(FilenameTok.getLength());
1847 FilenameStart = &FilenameBuffer[0];
1848 unsigned Len = getSpelling(FilenameTok, FilenameStart);
1849 FilenameEnd = FilenameStart+Len;
1850 break;
Chris Lattnerf97dbcb2007-07-23 22:23:52 +00001851 }
Chris Lattner43eafb42007-07-23 04:56:47 +00001852
1853 case tok::less:
1854 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1855 // case, glue the tokens together into FilenameBuffer and interpret those.
1856 FilenameBuffer.push_back('<');
1857 if (ConcatenateIncludeName(FilenameBuffer, *this))
1858 return; // Found <eom> but no ">"? Diagnostic already emitted.
1859 FilenameStart = &FilenameBuffer[0];
1860 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
1861 break;
1862 default:
1863 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1864 DiscardUntilEndOfDirective();
1865 return;
1866 }
1867
Chris Lattner93ab9f12007-07-23 04:15:27 +00001868 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001869 FilenameStart, FilenameEnd);
1870 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1871 // error.
Chris Lattner43eafb42007-07-23 04:56:47 +00001872 if (FilenameStart == 0) {
1873 DiscardUntilEndOfDirective();
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001874 return;
Chris Lattner43eafb42007-07-23 04:56:47 +00001875 }
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001876
Chris Lattner269c2322006-06-25 06:23:00 +00001877 // Verify that there is nothing after the filename, other than EOM. Use the
1878 // preprocessor to lex this in case lexing the filename entered a macro.
1879 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001880
1881 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001882 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001883 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1884
Chris Lattner22eb9722006-06-18 05:43:12 +00001885 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001886 const DirectoryLookup *CurDir;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001887 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
Chris Lattnerb8b94f12006-10-30 05:38:06 +00001888 isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001889 if (File == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00001890 return Diag(FilenameTok, diag::err_pp_file_not_found,
1891 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00001892
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001893 // Ask HeaderInfo if we should enter this #include file.
1894 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1895 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00001896 return;
1897 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001898
1899 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001900 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001901 if (FileID == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00001902 return Diag(FilenameTok, diag::err_pp_file_not_found,
1903 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00001904
1905 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001906 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001907}
1908
1909/// HandleIncludeNextDirective - Implements #include_next.
1910///
Chris Lattner146762e2007-07-20 16:59:19 +00001911void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
Chris Lattnercb283342006-06-18 06:48:37 +00001912 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001913
1914 // #include_next is like #include, except that we start searching after
1915 // the current found directory. If we can't do this, issue a
1916 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001917 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001918 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001919 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001920 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001921 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001922 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001923 } else {
1924 // Start looking up in the next directory.
1925 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001926 }
1927
1928 return HandleIncludeDirective(IncludeNextTok, Lookup);
1929}
1930
1931/// HandleImportDirective - Implements #import.
1932///
Chris Lattner146762e2007-07-20 16:59:19 +00001933void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnercb283342006-06-18 06:48:37 +00001934 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001935
1936 return HandleIncludeDirective(ImportTok, 0, true);
1937}
1938
Chris Lattnerb8761832006-06-24 21:31:03 +00001939//===----------------------------------------------------------------------===//
1940// Preprocessor Macro Directive Handling.
1941//===----------------------------------------------------------------------===//
1942
Chris Lattnercefc7682006-07-08 08:28:12 +00001943/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1944/// definition has just been read. Lex the rest of the arguments and the
1945/// closing ), updating MI with what we learn. Return true if an error occurs
1946/// parsing the arg list.
1947bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner564f4782007-07-14 22:46:43 +00001948 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
1949
Chris Lattner146762e2007-07-20 16:59:19 +00001950 Token Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001951 while (1) {
1952 LexUnexpandedToken(Tok);
1953 switch (Tok.getKind()) {
1954 case tok::r_paren:
1955 // Found the end of the argument list.
Chris Lattner564f4782007-07-14 22:46:43 +00001956 if (Arguments.empty()) { // #define FOO()
1957 MI->setArgumentList(Arguments.begin(), Arguments.end());
1958 return false;
1959 }
Chris Lattnercefc7682006-07-08 08:28:12 +00001960 // Otherwise we have #define FOO(A,)
1961 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1962 return true;
1963 case tok::ellipsis: // #define X(... -> C99 varargs
1964 // Warn if use of C99 feature in non-C99 mode.
1965 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1966
1967 // Lex the token after the identifier.
1968 LexUnexpandedToken(Tok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001969 if (Tok.isNot(tok::r_paren)) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001970 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1971 return true;
1972 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001973 // Add the __VA_ARGS__ identifier as an argument.
Chris Lattner564f4782007-07-14 22:46:43 +00001974 Arguments.push_back(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001975 MI->setIsC99Varargs();
Chris Lattner564f4782007-07-14 22:46:43 +00001976 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001977 return false;
1978 case tok::eom: // #define X(
1979 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1980 return true;
Chris Lattner62aa0d42006-10-20 05:08:24 +00001981 default:
1982 // Handle keywords and identifiers here to accept things like
1983 // #define Foo(for) for.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001984 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner62aa0d42006-10-20 05:08:24 +00001985 if (II == 0) {
1986 // #define X(1
1987 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1988 return true;
1989 }
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001990
1991 // If this is already used as an argument, it is used multiple times (e.g.
1992 // #define X(A,A.
Chris Lattner564f4782007-07-14 22:46:43 +00001993 if (std::find(Arguments.begin(), Arguments.end(), II) !=
1994 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001995 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1996 return true;
1997 }
1998
1999 // Add the argument to the macro info.
Chris Lattner564f4782007-07-14 22:46:43 +00002000 Arguments.push_back(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00002001
2002 // Lex the token after the identifier.
2003 LexUnexpandedToken(Tok);
2004
2005 switch (Tok.getKind()) {
2006 default: // #define X(A B
2007 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2008 return true;
2009 case tok::r_paren: // #define X(A)
Chris Lattner564f4782007-07-14 22:46:43 +00002010 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00002011 return false;
2012 case tok::comma: // #define X(A,
2013 break;
2014 case tok::ellipsis: // #define X(A... -> GCC extension
2015 // Diagnose extension.
2016 Diag(Tok, diag::ext_named_variadic_macro);
2017
2018 // Lex the token after the identifier.
2019 LexUnexpandedToken(Tok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002020 if (Tok.isNot(tok::r_paren)) {
Chris Lattnercefc7682006-07-08 08:28:12 +00002021 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2022 return true;
2023 }
2024
2025 MI->setIsGNUVarargs();
Chris Lattner564f4782007-07-14 22:46:43 +00002026 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00002027 return false;
2028 }
2029 }
2030 }
2031}
2032
Chris Lattner22eb9722006-06-18 05:43:12 +00002033/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00002034/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
2035/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00002036///
Chris Lattner146762e2007-07-20 16:59:19 +00002037void Preprocessor::HandleDefineDirective(Token &DefineTok,
Chris Lattner81278c62006-10-14 19:03:49 +00002038 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002039 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002040
Chris Lattner146762e2007-07-20 16:59:19 +00002041 Token MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00002042 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00002043
2044 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002045 if (MacroNameTok.is(tok::eom))
Chris Lattnercb283342006-06-18 06:48:37 +00002046 return;
Chris Lattnerf40fe992007-07-14 22:11:41 +00002047
Chris Lattner457fc152006-07-29 06:30:25 +00002048 // If we are supposed to keep comments in #defines, reenable comment saving
2049 // mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00002050 CurLexer->KeepCommentMode = KeepMacroComments;
Chris Lattner457fc152006-07-29 06:30:25 +00002051
Chris Lattner063400e2006-10-14 19:54:15 +00002052 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00002053 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00002054 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00002055
Chris Lattner063400e2006-10-14 19:54:15 +00002056 // If the identifier is an 'other target' macro, clear this bit.
2057 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2058
2059
Chris Lattner146762e2007-07-20 16:59:19 +00002060 Token Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00002061 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00002062
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002063 // If this is a function-like macro definition, parse the argument list,
2064 // marking each of the identifiers as being used as macro arguments. Also,
2065 // check other constraints on the first token of the macro body.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002066 if (Tok.is(tok::eom)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002067 // If there is no body to this macro, we have no special handling here.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002068 } else if (Tok.is(tok::l_paren) && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00002069 // This is a function-like macro definition. Read the argument list.
2070 MI->setIsFunctionLike();
2071 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002072 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00002073 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002074 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00002075 if (CurLexer->ParsingPreprocessorDirective)
2076 DiscardUntilEndOfDirective();
2077 return;
2078 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002079
Chris Lattner815a1f92006-07-08 20:48:04 +00002080 // Read the first token after the arg list for down below.
2081 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00002082 } else if (!Tok.hasLeadingSpace()) {
2083 // C99 requires whitespace between the macro definition and the body. Emit
2084 // a diagnostic for something like "#define X+".
2085 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00002086 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00002087 } else {
2088 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
2089 // one in some cases!
2090 }
2091 } else {
2092 // This is a normal token with leading space. Clear the leading space
2093 // marker on the first token to get proper expansion.
Chris Lattner146762e2007-07-20 16:59:19 +00002094 Tok.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002095 }
2096
Chris Lattner7e374832006-07-29 03:46:57 +00002097 // If this is a definition of a variadic C99 function-like macro, not using
2098 // the GNU named varargs extension, enabled __VA_ARGS__.
2099
2100 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
2101 // This gets unpoisoned where it is allowed.
2102 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
2103 if (MI->isC99Varargs())
2104 Ident__VA_ARGS__->setIsPoisoned(false);
2105
Chris Lattner22eb9722006-06-18 05:43:12 +00002106 // Read the rest of the macro body.
Chris Lattnera3834342007-07-14 21:54:03 +00002107 if (MI->isObjectLike()) {
2108 // Object-like macros are very simple, just read their body.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002109 while (Tok.isNot(tok::eom)) {
Chris Lattnera3834342007-07-14 21:54:03 +00002110 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00002111 // Get the next token of the macro.
2112 LexUnexpandedToken(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00002113 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002114
Chris Lattnera3834342007-07-14 21:54:03 +00002115 } else {
2116 // Otherwise, read the body of a function-like macro. This has to validate
2117 // the # (stringize) operator.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002118 while (Tok.isNot(tok::eom)) {
Chris Lattnera3834342007-07-14 21:54:03 +00002119 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002120
Chris Lattnera3834342007-07-14 21:54:03 +00002121 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
2122 // parameters in function-like macro expansions.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002123 if (Tok.isNot(tok::hash)) {
Chris Lattnera3834342007-07-14 21:54:03 +00002124 // Get the next token of the macro.
2125 LexUnexpandedToken(Tok);
2126 continue;
2127 }
2128
2129 // Get the next token of the macro.
2130 LexUnexpandedToken(Tok);
2131
2132 // Not a macro arg identifier?
2133 if (!Tok.getIdentifierInfo() ||
2134 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2135 Diag(Tok, diag::err_pp_stringize_not_parameter);
2136 delete MI;
2137
2138 // Disable __VA_ARGS__ again.
2139 Ident__VA_ARGS__->setIsPoisoned(true);
2140 return;
2141 }
2142
2143 // Things look ok, add the param name token to the macro.
2144 MI->AddTokenToBody(Tok);
2145
2146 // Get the next token of the macro.
2147 LexUnexpandedToken(Tok);
2148 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002149 }
Chris Lattner7e374832006-07-29 03:46:57 +00002150
Chris Lattnerf40fe992007-07-14 22:11:41 +00002151
Chris Lattner7e374832006-07-29 03:46:57 +00002152 // Disable __VA_ARGS__ again.
2153 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002154
Chris Lattnerbff18d52006-07-06 04:49:18 +00002155 // Check that there is no paste (##) operator at the begining or end of the
2156 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00002157 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00002158 if (NumTokens != 0) {
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002159 if (MI->getReplacementToken(0).is(tok::hashhash)) {
Chris Lattner815a1f92006-07-08 20:48:04 +00002160 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002161 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00002162 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00002163 }
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002164 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
Chris Lattner815a1f92006-07-08 20:48:04 +00002165 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002166 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00002167 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00002168 }
2169 }
2170
Chris Lattner13044d92006-07-03 05:16:44 +00002171 // If this is the primary source file, remember that this macro hasn't been
2172 // used yet.
2173 if (isInPrimaryFile())
2174 MI->setIsUsed(false);
2175
Chris Lattner22eb9722006-06-18 05:43:12 +00002176 // Finally, if this identifier already had a macro defined for it, verify that
2177 // the macro bodies are identical and free the old definition.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002178 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner13044d92006-07-03 05:16:44 +00002179 if (!OtherMI->isUsed())
2180 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
2181
Chris Lattner22eb9722006-06-18 05:43:12 +00002182 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00002183 // must be the same. C99 6.10.3.2.
2184 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00002185 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
2186 MacroNameTok.getIdentifierInfo()->getName());
2187 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
2188 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002189 delete OtherMI;
2190 }
2191
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002192 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00002193}
2194
Chris Lattner063400e2006-10-14 19:54:15 +00002195/// HandleDefineOtherTargetDirective - Implements #define_other_target.
Chris Lattner146762e2007-07-20 16:59:19 +00002196void Preprocessor::HandleDefineOtherTargetDirective(Token &Tok) {
2197 Token MacroNameTok;
Chris Lattner063400e2006-10-14 19:54:15 +00002198 ReadMacroName(MacroNameTok, 1);
2199
2200 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002201 if (MacroNameTok.is(tok::eom))
Chris Lattner063400e2006-10-14 19:54:15 +00002202 return;
2203
2204 // Check to see if this is the last token on the #undef line.
2205 CheckEndOfDirective("#define_other_target");
2206
2207 // If there is already a macro defined by this name, turn it into a
2208 // target-specific define.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002209 if (MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner063400e2006-10-14 19:54:15 +00002210 MI->setIsTargetSpecific(true);
2211 return;
2212 }
2213
2214 // Mark the identifier as being a macro on some other target.
2215 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
2216}
2217
Chris Lattner22eb9722006-06-18 05:43:12 +00002218
2219/// HandleUndefDirective - Implements #undef.
2220///
Chris Lattner146762e2007-07-20 16:59:19 +00002221void Preprocessor::HandleUndefDirective(Token &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002222 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002223
Chris Lattner146762e2007-07-20 16:59:19 +00002224 Token MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00002225 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00002226
2227 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002228 if (MacroNameTok.is(tok::eom))
Chris Lattnercb283342006-06-18 06:48:37 +00002229 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002230
2231 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00002232 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00002233
2234 // Okay, we finally have a valid identifier to undef.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002235 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Chris Lattner22eb9722006-06-18 05:43:12 +00002236
Chris Lattner063400e2006-10-14 19:54:15 +00002237 // #undef untaints an identifier if it were marked by define_other_target.
2238 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2239
Chris Lattner22eb9722006-06-18 05:43:12 +00002240 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00002241 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00002242
Chris Lattner13044d92006-07-03 05:16:44 +00002243 if (!MI->isUsed())
2244 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00002245
2246 // Free macro definition.
2247 delete MI;
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002248 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
Chris Lattner22eb9722006-06-18 05:43:12 +00002249}
2250
2251
Chris Lattnerb8761832006-06-24 21:31:03 +00002252//===----------------------------------------------------------------------===//
2253// Preprocessor Conditional Directive Handling.
2254//===----------------------------------------------------------------------===//
2255
Chris Lattner22eb9722006-06-18 05:43:12 +00002256/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00002257/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
2258/// if any tokens have been returned or pp-directives activated before this
2259/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00002260///
Chris Lattner146762e2007-07-20 16:59:19 +00002261void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
Chris Lattner371ac8a2006-07-04 07:11:10 +00002262 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002263 ++NumIf;
Chris Lattner146762e2007-07-20 16:59:19 +00002264 Token DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002265
Chris Lattner146762e2007-07-20 16:59:19 +00002266 Token MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00002267 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00002268
2269 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002270 if (MacroNameTok.is(tok::eom)) {
Chris Lattnerd05e44e2007-09-24 05:14:57 +00002271 // Skip code until we get to #endif. This helps with recovery by not
2272 // emitting an error when the #endif is reached.
2273 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2274 /*Foundnonskip*/false, /*FoundElse*/false);
Chris Lattnercb283342006-06-18 06:48:37 +00002275 return;
Chris Lattnerd05e44e2007-09-24 05:14:57 +00002276 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002277
2278 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00002279 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
2280
2281 // If the start of a top-level #ifdef, inform MIOpt.
2282 if (!ReadAnyTokensBeforeDirective &&
2283 CurLexer->getConditionalStackDepth() == 0) {
2284 assert(isIfndef && "#ifdef shouldn't reach here");
2285 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
2286 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002287
Chris Lattner063400e2006-10-14 19:54:15 +00002288 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002289 MacroInfo *MI = getMacroInfo(MII);
Chris Lattnera78a97e2006-07-03 05:42:18 +00002290
Chris Lattner81278c62006-10-14 19:03:49 +00002291 // If there is a macro, process it.
2292 if (MI) {
2293 // Mark it used.
2294 MI->setIsUsed(true);
2295
2296 // If this is the first use of a target-specific macro, warn about it.
2297 if (MI->isTargetSpecific()) {
2298 MI->setIsTargetSpecific(false); // Don't warn on second use.
2299 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2300 diag::port_target_macro_use);
2301 }
Chris Lattner063400e2006-10-14 19:54:15 +00002302 } else {
2303 // Use of a target-specific macro for some other target? If so, warn.
2304 if (MII->isOtherTargetMacro()) {
2305 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
2306 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2307 diag::port_target_macro_use);
2308 }
Chris Lattner81278c62006-10-14 19:03:49 +00002309 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00002310
Chris Lattner22eb9722006-06-18 05:43:12 +00002311 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00002312 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002313 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002314 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002315 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002316 } else {
2317 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002318 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00002319 /*Foundnonskip*/false,
2320 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002321 }
2322}
2323
2324/// HandleIfDirective - Implements the #if directive.
2325///
Chris Lattner146762e2007-07-20 16:59:19 +00002326void Preprocessor::HandleIfDirective(Token &IfToken,
Chris Lattnera8654ca2006-07-04 17:42:08 +00002327 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002328 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002329
Chris Lattner371ac8a2006-07-04 07:11:10 +00002330 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00002331 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00002332 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00002333
2334 // Should we include the stuff contained by this directive?
2335 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00002336 // If this condition is equivalent to #ifndef X, and if this is the first
2337 // directive seen, handle it for the multiple-include optimization.
2338 if (!ReadAnyTokensBeforeDirective &&
2339 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2340 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2341
Chris Lattner22eb9722006-06-18 05:43:12 +00002342 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002343 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002344 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002345 } else {
2346 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002347 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00002348 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002349 }
2350}
2351
2352/// HandleEndifDirective - Implements the #endif directive.
2353///
Chris Lattner146762e2007-07-20 16:59:19 +00002354void Preprocessor::HandleEndifDirective(Token &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002355 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002356
Chris Lattner22eb9722006-06-18 05:43:12 +00002357 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00002358 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00002359
2360 PPConditionalInfo CondInfo;
2361 if (CurLexer->popConditionalLevel(CondInfo)) {
2362 // No conditionals on the stack: this is an #endif without an #if.
2363 return Diag(EndifToken, diag::err_pp_endif_without_if);
2364 }
2365
Chris Lattner371ac8a2006-07-04 07:11:10 +00002366 // If this the end of a top-level #endif, inform MIOpt.
2367 if (CurLexer->getConditionalStackDepth() == 0)
2368 CurLexer->MIOpt.ExitTopLevelConditional();
2369
Chris Lattner538d7f32006-07-20 04:31:52 +00002370 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00002371 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00002372}
2373
2374
Chris Lattner146762e2007-07-20 16:59:19 +00002375void Preprocessor::HandleElseDirective(Token &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002376 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002377
Chris Lattner22eb9722006-06-18 05:43:12 +00002378 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00002379 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00002380
2381 PPConditionalInfo CI;
2382 if (CurLexer->popConditionalLevel(CI))
2383 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00002384
2385 // If this is a top-level #else, inform the MIOpt.
2386 if (CurLexer->getConditionalStackDepth() == 0)
2387 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00002388
2389 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002390 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002391
2392 // Finally, skip the rest of the contents of this block and return the first
2393 // token after it.
2394 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2395 /*FoundElse*/true);
2396}
2397
Chris Lattner146762e2007-07-20 16:59:19 +00002398void Preprocessor::HandleElifDirective(Token &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002399 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002400
Chris Lattner22eb9722006-06-18 05:43:12 +00002401 // #elif directive in a non-skipping conditional... start skipping.
2402 // We don't care what the condition is, because we will always skip it (since
2403 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002404 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002405
2406 PPConditionalInfo CI;
2407 if (CurLexer->popConditionalLevel(CI))
2408 return Diag(ElifToken, diag::pp_err_elif_without_if);
2409
Chris Lattner371ac8a2006-07-04 07:11:10 +00002410 // If this is a top-level #elif, inform the MIOpt.
2411 if (CurLexer->getConditionalStackDepth() == 0)
2412 CurLexer->MIOpt.FoundTopLevelElse();
2413
Chris Lattner22eb9722006-06-18 05:43:12 +00002414 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002415 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002416
2417 // Finally, skip the rest of the contents of this block and return the first
2418 // token after it.
2419 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2420 /*FoundElse*/CI.FoundElse);
2421}
Chris Lattnerb8761832006-06-24 21:31:03 +00002422