blob: a685b0b27b8cc15abd29696022a4b62cb72150d0 [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");
Steve Naroff6d40db02007-10-31 18:42:27 +0000372
Chris Lattnered2a9eb2007-10-10 17:48:53 +0000373 // Add __builtin_va_list typedef.
374 {
375 const char *VAList = PP.getTargetInfo().getVAListDeclaration();
376 Buf.insert(Buf.end(), VAList, VAList+strlen(VAList));
377 Buf.push_back('\n');
378 }
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000379
380 // Get the target #defines.
381 PP.getTargetInfo().getTargetDefines(Buf);
382
383 // Compiler set macros.
384 DefineBuiltinMacro(Buf, "__APPLE_CC__=5250");
Steve Naroff68754c52007-11-10 18:06:36 +0000385 DefineBuiltinMacro(Buf, "__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__=1050");
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000386 DefineBuiltinMacro(Buf, "__GNUC_MINOR__=0");
387 DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
388 DefineBuiltinMacro(Buf, "__GNUC__=4");
389 DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
390 DefineBuiltinMacro(Buf, "__VERSION__=\"4.0.1 (Apple Computer, Inc. "
391 "build 5250)\"");
392
393 // Build configuration options.
394 DefineBuiltinMacro(Buf, "__DYNAMIC__=1");
395 DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");
396 DefineBuiltinMacro(Buf, "__NO_INLINE__=1");
397 DefineBuiltinMacro(Buf, "__PIC__=1");
398
399
400 if (PP.getLangOptions().CPlusPlus) {
401 DefineBuiltinMacro(Buf, "__DEPRECATED=1");
402 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
403 DefineBuiltinMacro(Buf, "__GNUG__=4");
404 DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
405 DefineBuiltinMacro(Buf, "__cplusplus=1");
406 DefineBuiltinMacro(Buf, "__private_extern__=extern");
407 }
408
409 // FIXME: Should emit a #line directive here.
410}
411
412
413/// EnterMainSourceFile - Enter the specified FileID as the main source file,
414/// which implicitly adds the builting defines etc.
415void Preprocessor::EnterMainSourceFile(unsigned MainFileID) {
416 // Enter the main file source buffer.
417 EnterSourceFile(MainFileID, 0);
418
Chris Lattner609d4132007-11-15 19:07:47 +0000419 // Tell the header info that the main file was entered. If the file is later
420 // #imported, it won't be re-entered.
421 if (const FileEntry *FE =
422 SourceMgr.getFileEntryForLoc(SourceLocation::getFileLoc(MainFileID, 0)))
423 HeaderInfo.IncrementIncludeCount(FE);
424
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000425 std::vector<char> PrologFile;
426 PrologFile.reserve(4080);
427
428 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
429 InitializePredefinedMacros(*this, PrologFile);
430
431 // Add on the predefines from the driver.
432 PrologFile.insert(PrologFile.end(), Predefines,Predefines+strlen(Predefines));
433
434 // Memory buffer must end with a null byte!
435 PrologFile.push_back(0);
436
437 // Now that we have emitted the predefined macros, #includes, etc into
438 // PrologFile, preprocess it to populate the initial preprocessor state.
439 llvm::MemoryBuffer *SB =
440 llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(),
441 "<predefines>");
442 assert(SB && "Cannot fail to create predefined source buffer");
443 unsigned FileID = SourceMgr.createFileIDForMemBuffer(SB);
444 assert(FileID && "Could not create FileID for predefines?");
445
446 // Start parsing the predefines.
447 EnterSourceFile(FileID, 0);
448}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000449
Chris Lattnerd01e2912006-06-18 16:22:51 +0000450//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000451// Source File Location Methods.
452//===----------------------------------------------------------------------===//
453
Chris Lattner22eb9722006-06-18 05:43:12 +0000454/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
455/// return null on failure. isAngled indicates whether the file reference is
456/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnerb8b94f12006-10-30 05:38:06 +0000457const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
458 const char *FilenameEnd,
Chris Lattnerc8997182006-06-22 05:52:16 +0000459 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000460 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000461 const DirectoryLookup *&CurDir) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000462 // If the header lookup mechanism may be relative to the current file, pass in
463 // info about where the current file is.
464 const FileEntry *CurFileEnt = 0;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000465 if (!FromDir) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000466 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
467 CurFileEnt = SourceMgr.getFileEntryForLoc(FileLoc);
Chris Lattner22eb9722006-06-18 05:43:12 +0000468 }
469
Chris Lattner63dd32b2006-10-20 04:42:40 +0000470 // Do a standard file entry lookup.
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000471 CurDir = CurDirLookup;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000472 const FileEntry *FE =
Chris Lattner7cdbad92006-10-30 05:33:15 +0000473 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
474 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000475 if (FE) return FE;
476
477 // Otherwise, see if this is a subframework header. If so, this is relative
478 // to one of the headers on the #include stack. Walk the list of the current
479 // headers on the #include stack and pass them to HeaderInfo.
Chris Lattner5c683b22006-10-20 05:12:14 +0000480 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000481 CurFileEnt = SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000482 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
483 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000484 return FE;
485 }
486
487 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
488 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Chris Lattner5c683b22006-10-20 05:12:14 +0000489 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000490 CurFileEnt = SourceMgr.getFileEntryForLoc(ISEntry.TheLexer->getFileLoc());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000491 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
492 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000493 return FE;
494 }
495 }
496
497 // Otherwise, we really couldn't find the file.
498 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000499}
500
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000501/// isInPrimaryFile - Return true if we're in the top-level file, not in a
502/// #include.
503bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000504 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000505 return IncludeMacroStack.empty();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000506
Chris Lattner13044d92006-07-03 05:16:44 +0000507 // If there are any stacked lexers, we're in a #include.
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000508 assert(IncludeMacroStack[0].TheLexer &&
509 !IncludeMacroStack[0].TheLexer->Is_PragmaLexer &&
510 "Top level include stack isn't our primary lexer?");
511 for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000512 if (IncludeMacroStack[i].TheLexer &&
513 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000514 return false;
515 return true;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000516}
517
518/// getCurrentLexer - Return the current file lexer being lexed from. Note
519/// that this ignores any potentially active macro expansions and _Pragma
520/// expansions going on at the time.
521Lexer *Preprocessor::getCurrentFileLexer() const {
522 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
523
524 // Look for a stacked lexer.
525 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000526 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000527 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
528 return L;
529 }
530 return 0;
531}
532
533
Chris Lattner22eb9722006-06-18 05:43:12 +0000534/// EnterSourceFile - Add a source file to the top of the include stack and
535/// start lexing tokens from it instead of the current buffer. Return true
536/// on failure.
537void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000538 const DirectoryLookup *CurDir) {
Chris Lattner69772b02006-07-02 20:34:39 +0000539 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000540 ++NumEnteredSourceFiles;
541
Chris Lattner69772b02006-07-02 20:34:39 +0000542 if (MaxIncludeStackDepth < IncludeMacroStack.size())
543 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000544
Chris Lattner77e9de52007-07-20 16:52:03 +0000545 Lexer *TheLexer = new Lexer(SourceLocation::getFileLoc(FileID, 0), *this);
Chris Lattner69772b02006-07-02 20:34:39 +0000546 EnterSourceFileWithLexer(TheLexer, CurDir);
547}
Chris Lattner22eb9722006-06-18 05:43:12 +0000548
Chris Lattner69772b02006-07-02 20:34:39 +0000549/// EnterSourceFile - Add a source file to the top of the include stack and
550/// start lexing tokens from it instead of the current buffer.
551void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
552 const DirectoryLookup *CurDir) {
553
554 // Add the current lexer to the include stack.
555 if (CurLexer || CurMacroExpander)
556 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
557 CurMacroExpander));
558
559 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000560 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000561 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000562
563 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000564 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000565 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
566
567 // Get the file entry for the current file.
568 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000569 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000570 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000571
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000572 Callbacks->FileChanged(CurLexer->getFileLoc(),
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000573 PPCallbacks::EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000574 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000575}
576
Chris Lattner69772b02006-07-02 20:34:39 +0000577
578
Chris Lattner22eb9722006-06-18 05:43:12 +0000579/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000580/// tokens from it instead of the current buffer.
Chris Lattner146762e2007-07-20 16:59:19 +0000581void Preprocessor::EnterMacro(Token &Tok, MacroArgs *Args) {
Chris Lattner69772b02006-07-02 20:34:39 +0000582 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
583 CurMacroExpander));
584 CurLexer = 0;
585 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000586
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000587 if (NumCachedMacroExpanders == 0) {
588 CurMacroExpander = new MacroExpander(Tok, Args, *this);
589 } else {
590 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
591 CurMacroExpander->Init(Tok, Args);
592 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000593}
594
Chris Lattner7667d0d2006-07-16 18:16:58 +0000595/// EnterTokenStream - Add a "macro" context to the top of the include stack,
596/// which will cause the lexer to start returning the specified tokens. Note
597/// that these tokens will be re-macro-expanded when/if expansion is enabled.
598/// This method assumes that the specified stream of tokens has a permanent
599/// owner somewhere, so they do not need to be copied.
Chris Lattner146762e2007-07-20 16:59:19 +0000600void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000601 // Save our current state.
602 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
603 CurMacroExpander));
604 CurLexer = 0;
605 CurDirLookup = 0;
606
607 // Create a macro expander to expand from the specified token stream.
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000608 if (NumCachedMacroExpanders == 0) {
609 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
610 } else {
611 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
612 CurMacroExpander->Init(Toks, NumToks);
613 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000614}
615
616/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
617/// lexer stack. This should only be used in situations where the current
618/// state of the top-of-stack lexer is known.
619void Preprocessor::RemoveTopOfLexerStack() {
620 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000621
622 if (CurMacroExpander) {
623 // Delete or cache the now-dead macro expander.
624 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
625 delete CurMacroExpander;
626 else
627 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
628 } else {
629 delete CurLexer;
630 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000631 CurLexer = IncludeMacroStack.back().TheLexer;
632 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
633 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
634 IncludeMacroStack.pop_back();
635}
636
Chris Lattner22eb9722006-06-18 05:43:12 +0000637//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000638// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000639//===----------------------------------------------------------------------===//
640
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000641/// setMacroInfo - Specify a macro for this identifier.
642///
643void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
644 if (MI == 0) {
645 if (II->hasMacroDefinition()) {
646 Macros.erase(II);
647 II->setHasMacroDefinition(false);
648 }
649 } else {
650 Macros[II] = MI;
651 II->setHasMacroDefinition(true);
652 }
653}
654
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000655/// RegisterBuiltinMacro - Register the specified identifier in the identifier
656/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000657IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000658 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000659 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000660
661 // Mark it as being a macro that is builtin.
662 MacroInfo *MI = new MacroInfo(SourceLocation());
663 MI->setIsBuiltinMacro();
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000664 setMacroInfo(Id, MI);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000665 return Id;
666}
667
668
Chris Lattner677757a2006-06-28 05:26:32 +0000669/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
670/// identifier table.
671void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000672 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000673 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000674 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
675 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000676 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000677
678 // GCC Extensions.
679 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
680 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000681 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000682}
683
Chris Lattnerc2395832006-07-09 00:57:04 +0000684/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
685/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000686static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000687 const IdentifierInfo *MacroIdent,
688 Preprocessor &PP) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000689 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
690
691 // If the token isn't an identifier, it's always literally expanded.
692 if (II == 0) return true;
693
694 // If the identifier is a macro, and if that macro is enabled, it may be
695 // expanded so it's not a trivial expansion.
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000696 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000697 // Fast expanding "#define X X" is ok, because X would be disabled.
698 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000699 return false;
700
701 // If this is an object-like macro invocation, it is safe to trivially expand
702 // it.
703 if (MI->isObjectLike()) return true;
704
705 // If this is a function-like macro invocation, it's safe to trivially expand
706 // as long as the identifier is not a macro argument.
707 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
708 I != E; ++I)
709 if (*I == II)
710 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000711
Chris Lattnerc2395832006-07-09 00:57:04 +0000712 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000713}
714
Chris Lattnerc2395832006-07-09 00:57:04 +0000715
Chris Lattnerafe603f2006-07-11 04:02:46 +0000716/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
717/// lexed is a '('. If so, consume the token and return true, if not, this
718/// method should have no observable side-effect on the lexed tokens.
719bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000720 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000721 unsigned Val;
722 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000723 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000724 else
725 Val = CurMacroExpander->isNextTokenLParen();
726
727 if (Val == 2) {
Chris Lattner5c983792007-07-19 00:07:36 +0000728 // We have run off the end. If it's a source file we don't
729 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
730 // macro stack.
731 if (CurLexer)
732 return false;
733 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000734 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
735 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000736 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000737 else
738 Val = Entry.TheMacroExpander->isNextTokenLParen();
Chris Lattner5c983792007-07-19 00:07:36 +0000739
740 if (Val != 2)
741 break;
742
743 // Ran off the end of a source file?
744 if (Entry.TheLexer)
745 return false;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000746 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000747 }
748
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000749 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
750 // have found something that isn't a '(' or we found the end of the
751 // translation unit. In either case, return false.
752 if (Val != 1)
753 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000754
Chris Lattner146762e2007-07-20 16:59:19 +0000755 Token Tok;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000756 LexUnexpandedToken(Tok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000757 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000758 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000759}
Chris Lattner677757a2006-06-28 05:26:32 +0000760
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000761/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
762/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner146762e2007-07-20 16:59:19 +0000763bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000764 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000765
766 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
767 if (MI->isBuiltinMacro()) {
768 ExpandBuiltinMacro(Identifier);
769 return false;
770 }
771
Chris Lattner81278c62006-10-14 19:03:49 +0000772 // If this is the first use of a target-specific macro, warn about it.
773 if (MI->isTargetSpecific()) {
774 MI->setIsTargetSpecific(false); // Don't warn on second use.
775 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
776 diag::port_target_macro_use);
777 }
778
Chris Lattneree8760b2006-07-15 07:42:55 +0000779 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000780 /// for each macro argument, the list of tokens that were provided to the
781 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000782 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000783
784 // If this is a function-like macro, read the arguments.
785 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000786 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner24dbee72007-07-19 16:11:58 +0000787 // name isn't a '(', this macro should not be expanded. Otherwise, consume
788 // it.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000789 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000790 return true;
791
Chris Lattner78186052006-07-09 00:45:31 +0000792 // Remember that we are now parsing the arguments to a macro invocation.
793 // Preprocessor directives used inside macro arguments are not portable, and
794 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000795 InMacroArgs = true;
796 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000797
798 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000799 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000800
801 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000802 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000803
804 ++NumFnMacroExpanded;
805 } else {
806 ++NumMacroExpanded;
807 }
Chris Lattner13044d92006-07-03 05:16:44 +0000808
809 // Notice that this macro has been used.
810 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000811
812 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000813
814 // If this macro expands to no tokens, don't bother to push it onto the
815 // expansion stack, only to take it right back off.
816 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000817 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000818 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000819
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000820 // Ignore this macro use, just return the next token in the current
821 // buffer.
822 bool HadLeadingSpace = Identifier.hasLeadingSpace();
823 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
824
825 Lex(Identifier);
826
827 // If the identifier isn't on some OTHER line, inherit the leading
828 // whitespace/first-on-a-line property of this token. This handles
829 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
830 // empty.
831 if (!Identifier.isAtStartOfLine()) {
Chris Lattner146762e2007-07-20 16:59:19 +0000832 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
833 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000834 }
835 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000836 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000837
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000838 } else if (MI->getNumTokens() == 1 &&
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000839 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
840 *this)){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000841 // Otherwise, if this macro expands into a single trivially-expanded
842 // token: expand it now. This handles common cases like
843 // "#define VAL 42".
844
845 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
846 // identifier to the expanded token.
847 bool isAtStartOfLine = Identifier.isAtStartOfLine();
848 bool hasLeadingSpace = Identifier.hasLeadingSpace();
849
850 // Remember where the token is instantiated.
851 SourceLocation InstantiateLoc = Identifier.getLocation();
852
853 // Replace the result token.
854 Identifier = MI->getReplacementToken(0);
855
856 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner146762e2007-07-20 16:59:19 +0000857 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
858 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000859
860 // Update the tokens location to include both its logical and physical
861 // locations.
862 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000863 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000864 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000865
Chris Lattner6e4bf522006-07-27 06:59:25 +0000866 // If this is #define X X, we must mark the result as unexpandible.
867 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000868 if (getMacroInfo(NewII) == MI)
Chris Lattner146762e2007-07-20 16:59:19 +0000869 Identifier.setFlag(Token::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000870
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000871 // Since this is not an identifier token, it can't be macro expanded, so
872 // we're done.
873 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000874 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000875 }
876
Chris Lattner78186052006-07-09 00:45:31 +0000877 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000878 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000879
880 // Now that the macro is at the top of the include stack, ask the
881 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000882 Lex(Identifier);
883 return false;
884}
885
Chris Lattneree8760b2006-07-15 07:42:55 +0000886/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000887/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000888/// invocation. This returns null on error.
Chris Lattner146762e2007-07-20 16:59:19 +0000889MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattneree8760b2006-07-15 07:42:55 +0000890 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000891 // The number of fixed arguments to parse.
892 unsigned NumFixedArgsLeft = MI->getNumArgs();
893 bool isVariadic = MI->isVariadic();
894
Chris Lattner78186052006-07-09 00:45:31 +0000895 // Outer loop, while there are more arguments, keep reading them.
Chris Lattner146762e2007-07-20 16:59:19 +0000896 Token Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000897 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000898 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000899
900 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000901 // argument is separated by an EOF token. Use a SmallVector so we can avoid
902 // heap allocations in the common case.
Chris Lattner146762e2007-07-20 16:59:19 +0000903 llvm::SmallVector<Token, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000904
905 unsigned NumActuals = 0;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000906 while (Tok.is(tok::comma)) {
Chris Lattner24dbee72007-07-19 16:11:58 +0000907 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
908 // that we already consumed the first one.
Chris Lattner78186052006-07-09 00:45:31 +0000909 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000910
Chris Lattner78186052006-07-09 00:45:31 +0000911 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000912 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
913 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000914 LexUnexpandedToken(Tok);
915
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000916 if (Tok.is(tok::eof)) {
Chris Lattner78186052006-07-09 00:45:31 +0000917 Diag(MacroName, diag::err_unterm_macro_invoc);
918 // Do not lose the EOF. Return it to the client.
919 MacroName = Tok;
920 return 0;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000921 } else if (Tok.is(tok::r_paren)) {
Chris Lattner78186052006-07-09 00:45:31 +0000922 // If we found the ) token, the macro arg list is done.
923 if (NumParens-- == 0)
924 break;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000925 } else if (Tok.is(tok::l_paren)) {
Chris Lattner78186052006-07-09 00:45:31 +0000926 ++NumParens;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000927 } else if (Tok.is(tok::comma) && NumParens == 0) {
Chris Lattner78186052006-07-09 00:45:31 +0000928 // Comma ends this argument if there are more fixed arguments expected.
929 if (NumFixedArgsLeft)
930 break;
931
Chris Lattner2ada5d32006-07-15 07:51:24 +0000932 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000933 if (!isVariadic) {
934 // Emit the diagnostic at the macro name in case there is a missing ).
935 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000936 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000937 return 0;
938 }
939 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000940 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
Chris Lattner457fc152006-07-29 06:30:25 +0000941 // If this is a comment token in the argument list and we're just in
942 // -C mode (not -CC mode), discard the comment.
943 continue;
Chris Lattner9fcdc522007-11-23 06:50:21 +0000944 } else if (Tok.is(tok::identifier)) {
945 // Reading macro arguments can cause macros that we are currently
946 // expanding from to be popped off the expansion stack. Doing so causes
947 // them to be reenabled for expansion. Here we record whether any
948 // identifiers we lex as macro arguments correspond to disabled macros.
949 // If so, we mark the token as noexpand. This is a subtle aspect of
950 // C99 6.10.3.4p2.
951 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
952 if (!MI->isEnabled())
953 Tok.setFlag(Token::DisableExpand);
Chris Lattner78186052006-07-09 00:45:31 +0000954 }
955
956 ArgTokens.push_back(Tok);
957 }
958
Chris Lattnera12dd152006-07-11 04:09:02 +0000959 // Empty arguments are standard in C99 and supported as an extension in
960 // other modes.
961 if (ArgTokens.empty() && !Features.C99)
962 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000963
Chris Lattner36b6e812006-07-21 06:38:30 +0000964 // Add a marker EOF token to the end of the token list for this argument.
Chris Lattner146762e2007-07-20 16:59:19 +0000965 Token EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +0000966 EOFTok.startToken();
967 EOFTok.setKind(tok::eof);
968 EOFTok.setLocation(Tok.getLocation());
969 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +0000970 ArgTokens.push_back(EOFTok);
971 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000972 --NumFixedArgsLeft;
973 };
974
975 // Okay, we either found the r_paren. Check to see if we parsed too few
976 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000977 unsigned MinArgsExpected = MI->getNumArgs();
978
Chris Lattner775d8322006-07-29 04:39:41 +0000979 // See MacroArgs instance var for description of this.
980 bool isVarargsElided = false;
981
Chris Lattner2ada5d32006-07-15 07:51:24 +0000982 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000983 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000984 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000985 // Varargs where the named vararg parameter is missing: ok as extension.
986 // #define A(x, ...)
987 // A("blah")
988 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000989
990 // Remember this occurred if this is a C99 macro invocation with at least
991 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000992 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000993 } else if (MI->getNumArgs() == 1) {
994 // #define A(x)
995 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000996 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000997
998 // Empty arguments are standard in C99 and supported as an extension in
999 // other modes.
1000 if (ArgTokens.empty() && !Features.C99)
1001 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +00001002 } else {
1003 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +00001004 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +00001005 return 0;
1006 }
Chris Lattnere7a51302006-07-29 01:25:12 +00001007
1008 // Add a marker EOF token to the end of the token list for this argument.
1009 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +00001010 Tok.startToken();
1011 Tok.setKind(tok::eof);
1012 Tok.setLocation(EndLoc);
1013 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +00001014 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +00001015 }
1016
Chris Lattner775d8322006-07-29 04:39:41 +00001017 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +00001018}
1019
Chris Lattnerc673f902006-06-30 06:10:41 +00001020/// ComputeDATE_TIME - Compute the current time, enter it into the specified
1021/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
1022/// the identifier tokens inserted.
1023static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001024 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +00001025 time_t TT = time(0);
1026 struct tm *TM = localtime(&TT);
1027
1028 static const char * const Months[] = {
1029 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
1030 };
1031
1032 char TmpBuffer[100];
1033 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
1034 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001035 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +00001036
1037 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001038 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +00001039}
1040
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001041/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1042/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner146762e2007-07-20 16:59:19 +00001043void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001044 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001045 IdentifierInfo *II = Tok.getIdentifierInfo();
1046 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +00001047
1048 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
1049 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001050 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +00001051 return Handle_Pragma(Tok);
1052
Chris Lattner78186052006-07-09 00:45:31 +00001053 ++NumBuiltinMacroExpanded;
1054
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001055 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +00001056
1057 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +00001058 Tok.setIdentifierInfo(0);
Chris Lattner146762e2007-07-20 16:59:19 +00001059 Tok.clearFlag(Token::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +00001060
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001061 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001062 // __LINE__ expands to a simple numeric value.
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001063 sprintf(TmpBuffer, "%u", SourceMgr.getLogicalLineNumber(Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001064 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +00001065 Tok.setKind(tok::numeric_constant);
1066 Tok.setLength(Length);
1067 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001068 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +00001069 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001070 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +00001071 Diag(Tok, diag::ext_pp_base_file);
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001072 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc);
1073 while (NextLoc.isValid()) {
Chris Lattnerc1283b92006-07-01 23:16:30 +00001074 Loc = NextLoc;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001075 NextLoc = SourceMgr.getIncludeLoc(Loc);
Chris Lattnerc1283b92006-07-01 23:16:30 +00001076 }
1077 }
1078
Chris Lattner0766e592006-07-03 01:07:01 +00001079 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001080 std::string FN = SourceMgr.getSourceName(SourceMgr.getLogicalLoc(Loc));
Chris Lattnerecc39e92006-07-15 05:23:31 +00001081 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +00001082 Tok.setKind(tok::string_literal);
1083 Tok.setLength(FN.size());
1084 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001085 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +00001086 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001087 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +00001088 Tok.setKind(tok::string_literal);
1089 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1090 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001091 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +00001092 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001093 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +00001094 Tok.setKind(tok::string_literal);
1095 Tok.setLength(strlen("\"hh:mm:ss\""));
1096 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001097 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +00001098 Diag(Tok, diag::ext_pp_include_level);
1099
1100 // Compute the include depth of this token.
1101 unsigned Depth = 0;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001102 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation());
1103 for (; Loc.isValid(); ++Depth)
1104 Loc = SourceMgr.getIncludeLoc(Loc);
Chris Lattnerc1283b92006-07-01 23:16:30 +00001105
1106 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1107 sprintf(TmpBuffer, "%u", Depth);
1108 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +00001109 Tok.setKind(tok::numeric_constant);
1110 Tok.setLength(Length);
1111 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001112 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +00001113 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1114 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1115 Diag(Tok, diag::ext_pp_timestamp);
1116
1117 // Get the file that we are lexing out of. If we're currently lexing from
1118 // a macro, dig into the include stack.
1119 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +00001120 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +00001121
1122 if (TheLexer)
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001123 CurFile = SourceMgr.getFileEntryForLoc(TheLexer->getFileLoc());
Chris Lattner847e0e42006-07-01 23:49:16 +00001124
1125 // If this file is older than the file it depends on, emit a diagnostic.
1126 const char *Result;
1127 if (CurFile) {
1128 time_t TT = CurFile->getModificationTime();
1129 struct tm *TM = localtime(&TT);
1130 Result = asctime(TM);
1131 } else {
1132 Result = "??? ??? ?? ??:??:?? ????\n";
1133 }
1134 TmpBuffer[0] = '"';
1135 strcpy(TmpBuffer+1, Result);
1136 unsigned Len = strlen(TmpBuffer);
1137 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +00001138 Tok.setKind(tok::string_literal);
1139 Tok.setLength(Len);
1140 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001141 } else {
1142 assert(0 && "Unknown identifier!");
1143 }
1144}
Chris Lattner677757a2006-06-28 05:26:32 +00001145
1146//===----------------------------------------------------------------------===//
1147// Lexer Event Handling.
1148//===----------------------------------------------------------------------===//
1149
Chris Lattnercefc7682006-07-08 08:28:12 +00001150/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
1151/// identifier information for the token and install it into the token.
Chris Lattner146762e2007-07-20 16:59:19 +00001152IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
Chris Lattnercefc7682006-07-08 08:28:12 +00001153 const char *BufPtr) {
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001154 assert(Identifier.is(tok::identifier) && "Not an identifier!");
Chris Lattnercefc7682006-07-08 08:28:12 +00001155 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
1156
1157 // Look up this token, see if it is a macro, or if it is a language keyword.
1158 IdentifierInfo *II;
1159 if (BufPtr && !Identifier.needsCleaning()) {
1160 // No cleaning needed, just use the characters from the lexed buffer.
1161 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
1162 } else {
1163 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Chris Lattnerf9aba2c2007-07-13 17:10:38 +00001164 llvm::SmallVector<char, 64> IdentifierBuffer;
1165 IdentifierBuffer.resize(Identifier.getLength());
1166 const char *TmpBuf = &IdentifierBuffer[0];
Chris Lattnercefc7682006-07-08 08:28:12 +00001167 unsigned Size = getSpelling(Identifier, TmpBuf);
1168 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
1169 }
Chris Lattner8c204872006-10-14 05:19:21 +00001170 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001171 return II;
1172}
1173
1174
Chris Lattner677757a2006-06-28 05:26:32 +00001175/// HandleIdentifier - This callback is invoked when the lexer reads an
1176/// identifier. This callback looks up the identifier in the map and/or
1177/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattner146762e2007-07-20 16:59:19 +00001178void Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +00001179 assert(Identifier.getIdentifierInfo() &&
1180 "Can't handle identifiers without identifier info!");
1181
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001182 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +00001183
1184 // If this identifier was poisoned, and if it was not produced from a macro
1185 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +00001186 if (II.isPoisoned() && CurLexer) {
1187 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
1188 Diag(Identifier, diag::err_pp_used_poisoned_id);
1189 else
1190 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
1191 }
Chris Lattner677757a2006-06-28 05:26:32 +00001192
Chris Lattner78186052006-07-09 00:45:31 +00001193 // If this is a macro to be expanded, do it.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001194 if (MacroInfo *MI = getMacroInfo(&II)) {
Chris Lattner6e4bf522006-07-27 06:59:25 +00001195 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
1196 if (MI->isEnabled()) {
1197 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1198 return;
1199 } else {
1200 // C99 6.10.3.4p2 says that a disabled macro may never again be
1201 // expanded, even if it's in a context where it could be expanded in the
1202 // future.
Chris Lattner146762e2007-07-20 16:59:19 +00001203 Identifier.setFlag(Token::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +00001204 }
1205 }
Chris Lattner063400e2006-10-14 19:54:15 +00001206 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
1207 // If this identifier is a macro on some other target, emit a diagnostic.
1208 // This diagnosic is only emitted when macro expansion is enabled, because
1209 // the macro would not have been expanded for the other target either.
1210 II.setIsOtherTargetMacro(false); // Don't warn on second use.
1211 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
1212 diag::port_target_macro_use);
1213
1214 }
Chris Lattner677757a2006-06-28 05:26:32 +00001215
Chris Lattner5b9f4892006-11-21 17:23:33 +00001216 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
1217 // then we act as if it is the actual operator and not the textual
1218 // representation of it.
1219 if (II.isCPlusPlusOperatorKeyword())
1220 Identifier.setIdentifierInfo(0);
1221
Chris Lattner677757a2006-06-28 05:26:32 +00001222 // Change the kind of this identifier to the appropriate token kind, e.g.
1223 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +00001224 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +00001225
1226 // If this is an extension token, diagnose its use.
Steve Naroffa8fd9732007-06-11 00:35:03 +00001227 // FIXME: tried (unsuccesfully) to shut this up when compiling with gnu99
1228 // For now, I'm just commenting it out (while I work on attributes).
Chris Lattner53621a52007-06-13 20:44:40 +00001229 if (II.isExtensionToken() && Features.C99)
1230 Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +00001231}
1232
Chris Lattner22eb9722006-06-18 05:43:12 +00001233/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1234/// the current file. This either returns the EOF token or pops a level off
1235/// the include stack and keeps going.
Chris Lattner146762e2007-07-20 16:59:19 +00001236bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001237 assert(!CurMacroExpander &&
1238 "Ending a file when currently in a macro!");
1239
Chris Lattner371ac8a2006-07-04 07:11:10 +00001240 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001241 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001242 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001243 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001244 // Okay, this has a controlling macro, remember in PerFileInfo.
1245 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001246 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001247 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001248 }
1249 }
1250
Chris Lattner22eb9722006-06-18 05:43:12 +00001251 // If this is a #include'd file, pop it off the include stack and continue
1252 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001253 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001254 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001255 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001256
1257 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001258 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001259 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1260
1261 // Get the file entry for the current file.
1262 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001263 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001264 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001265
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001266 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1267 PPCallbacks::ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001268 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001269
1270 // Client should lex another token.
1271 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001272 }
1273
Chris Lattner8c204872006-10-14 05:19:21 +00001274 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +00001275 CurLexer->BufferPtr = CurLexer->BufferEnd;
1276 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +00001277 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001278
1279 // We're done with the #included file.
1280 delete CurLexer;
1281 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001282
Chris Lattner03f83482006-07-10 06:16:26 +00001283 // This is the end of the top-level file. If the diag::pp_macro_not_used
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001284 // diagnostic is enabled, look for macros that have not been used.
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001285 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001286 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
1287 Macros.begin(), E = Macros.end(); I != E; ++I) {
1288 if (!I->second->isUsed())
1289 Diag(I->second->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001290 }
1291 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001292 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001293}
1294
1295/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001296/// the current macro expansion or token stream expansion.
Chris Lattner146762e2007-07-20 16:59:19 +00001297bool Preprocessor::HandleEndOfMacro(Token &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001298 assert(CurMacroExpander && !CurLexer &&
1299 "Ending a macro when currently in a #include file!");
1300
Chris Lattnerc02c4ab2007-07-15 00:25:26 +00001301 // Delete or cache the now-dead macro expander.
1302 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
1303 delete CurMacroExpander;
1304 else
1305 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
Chris Lattner22eb9722006-06-18 05:43:12 +00001306
Chris Lattner69772b02006-07-02 20:34:39 +00001307 // Handle this like a #include file being popped off the stack.
1308 CurMacroExpander = 0;
1309 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001310}
1311
1312
1313//===----------------------------------------------------------------------===//
1314// Utility Methods for Preprocessor Directive Handling.
1315//===----------------------------------------------------------------------===//
1316
1317/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1318/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001319void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner146762e2007-07-20 16:59:19 +00001320 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00001321 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001322 LexUnexpandedToken(Tmp);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001323 } while (Tmp.isNot(tok::eom));
Chris Lattner22eb9722006-06-18 05:43:12 +00001324}
1325
Chris Lattner652c1692006-11-21 23:47:30 +00001326/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
1327static bool isCXXNamedOperator(const std::string &Spelling) {
1328 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
1329 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
1330 Spelling == "or" || Spelling == "xor";
1331}
1332
Chris Lattner22eb9722006-06-18 05:43:12 +00001333/// ReadMacroName - Lex and validate a macro name, which occurs after a
1334/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001335/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1336/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001337/// else (e.g. #ifdef).
Chris Lattner146762e2007-07-20 16:59:19 +00001338void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001339 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001340 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001341
1342 // Missing macro name?
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001343 if (MacroNameTok.is(tok::eom))
Chris Lattner22eb9722006-06-18 05:43:12 +00001344 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1345
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001346 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1347 if (II == 0) {
Chris Lattner652c1692006-11-21 23:47:30 +00001348 std::string Spelling = getSpelling(MacroNameTok);
1349 if (isCXXNamedOperator(Spelling))
1350 // C++ 2.5p2: Alternative tokens behave the same as its primary token
1351 // except for their spellings.
1352 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
1353 else
1354 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001355 // Fall through on error.
Chris Lattner2bb8a952006-11-21 22:24:17 +00001356 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001357 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001358 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattner259716a2007-10-07 08:04:56 +00001359 } else if (isDefineUndef && II->hasMacroDefinition() &&
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001360 getMacroInfo(II)->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001361 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001362 if (isDefineUndef == 1)
1363 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1364 else
1365 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001366 } else {
1367 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001368 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001369 }
1370
Chris Lattner22eb9722006-06-18 05:43:12 +00001371 // Invalid macro name, read and discard the rest of the line. Then set the
1372 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001373 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001374 return DiscardUntilEndOfDirective();
1375}
1376
1377/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1378/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001379void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner146762e2007-07-20 16:59:19 +00001380 Token Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001381 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001382 // There should be no tokens after the directive, but we allow them as an
1383 // extension.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001384 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001385 Lex(Tmp);
1386
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001387 if (Tmp.isNot(tok::eom)) {
Chris Lattnercb283342006-06-18 06:48:37 +00001388 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1389 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001390 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001391}
1392
1393
1394
1395/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1396/// decided that the subsequent tokens are in the #if'd out portion of the
1397/// file. Lex the rest of the file, until we see an #endif. If
1398/// FoundNonSkipPortion is true, then we have already emitted code for part of
1399/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1400/// is true, then #else directives are ok, if not, then we have already seen one
1401/// so a #else directive is a duplicate. When this returns, the caller can lex
1402/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001403void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001404 bool FoundNonSkipPortion,
1405 bool FoundElse) {
1406 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001407 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001408 "Lexing a macro, not a file?");
1409
1410 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1411 FoundNonSkipPortion, FoundElse);
1412
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001413 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1414 // disabling warnings, etc.
1415 CurLexer->LexingRawMode = true;
Chris Lattner146762e2007-07-20 16:59:19 +00001416 Token Tok;
Chris Lattner22eb9722006-06-18 05:43:12 +00001417 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001418 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001419
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001420 // If this is the end of the buffer, we have an error.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001421 if (Tok.is(tok::eof)) {
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001422 // Emit errors for each unterminated conditional on the stack, including
1423 // the current one.
1424 while (!CurLexer->ConditionalStack.empty()) {
1425 Diag(CurLexer->ConditionalStack.back().IfLoc,
1426 diag::err_pp_unterminated_conditional);
1427 CurLexer->ConditionalStack.pop_back();
1428 }
1429
1430 // Just return and let the caller lex after this #include.
1431 break;
1432 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001433
1434 // If this token is not a preprocessor directive, just skip it.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001435 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
Chris Lattner22eb9722006-06-18 05:43:12 +00001436 continue;
1437
1438 // We just parsed a # character at the start of a line, so we're in
1439 // directive mode. Tell the lexer this so any newlines we see will be
1440 // converted into an EOM token (this terminates the macro).
1441 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001442 CurLexer->KeepCommentMode = false;
1443
Chris Lattner22eb9722006-06-18 05:43:12 +00001444
1445 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001446 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001447
1448 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1449 // something bogus), skip it.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001450 if (Tok.isNot(tok::identifier)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001451 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001452 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001453 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001454 continue;
1455 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001456
Chris Lattner22eb9722006-06-18 05:43:12 +00001457 // If the first letter isn't i or e, it isn't intesting to us. We know that
1458 // this is safe in the face of spelling differences, because there is no way
1459 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001460 // allows us to avoid looking up the identifier info for #define/#undef and
1461 // other common directives.
1462 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1463 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001464 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1465 FirstChar != 'i' && FirstChar != 'e') {
1466 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001467 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001468 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001469 continue;
1470 }
1471
Chris Lattnere60165f2006-06-22 06:36:29 +00001472 // Get the identifier name without trigraphs or embedded newlines. Note
1473 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1474 // when skipping.
1475 // TODO: could do this with zero copies in the no-clean case by using
1476 // strncmp below.
1477 char Directive[20];
1478 unsigned IdLen;
1479 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1480 IdLen = Tok.getLength();
1481 memcpy(Directive, RawCharData, IdLen);
1482 Directive[IdLen] = 0;
1483 } else {
1484 std::string DirectiveStr = getSpelling(Tok);
1485 IdLen = DirectiveStr.size();
1486 if (IdLen >= 20) {
1487 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001488 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001489 CurLexer->KeepCommentMode = KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001490 continue;
1491 }
1492 memcpy(Directive, &DirectiveStr[0], IdLen);
1493 Directive[IdLen] = 0;
1494 }
1495
Chris Lattner22eb9722006-06-18 05:43:12 +00001496 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001497 if ((IdLen == 2) || // "if"
1498 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1499 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001500 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1501 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001502 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001503 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001504 /*foundnonskip*/false,
1505 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001506 }
1507 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001508 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001509 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001510 PPConditionalInfo CondInfo;
1511 CondInfo.WasSkipping = true; // Silence bogus warning.
1512 bool InCond = CurLexer->popConditionalLevel(CondInfo);
Chris Lattnercf6bc662006-11-05 07:59:08 +00001513 InCond = InCond; // Silence warning in no-asserts mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00001514 assert(!InCond && "Can't be skipping if not in a conditional!");
1515
1516 // If we popped the outermost skipping block, we're done skipping!
1517 if (!CondInfo.WasSkipping)
1518 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001519 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001520 // #else directive in a skipping conditional. If not in some other
1521 // skipping conditional, and if #else hasn't already been seen, enter it
1522 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001523 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001524 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1525
1526 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001527 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001528
1529 // Note that we've seen a #else in this conditional.
1530 CondInfo.FoundElse = true;
1531
1532 // If the conditional is at the top level, and the #if block wasn't
1533 // entered, enter the #else block now.
1534 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1535 CondInfo.FoundNonSkip = true;
1536 break;
1537 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001538 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001539 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1540
1541 bool ShouldEnter;
1542 // If this is in a skipping block or if we're already handled this #if
1543 // block, don't bother parsing the condition.
1544 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001545 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001546 ShouldEnter = false;
1547 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001548 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001549 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001550 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1551 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001552 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001553 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001554 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001555 }
1556
1557 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001558 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001559
1560 // If this condition is true, enter it!
1561 if (ShouldEnter) {
1562 CondInfo.FoundNonSkip = true;
1563 break;
1564 }
1565 }
1566 }
1567
1568 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001569 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001570 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001571 }
1572
1573 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1574 // of the file, just stop skipping and return to lexing whatever came after
1575 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001576 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001577}
1578
1579//===----------------------------------------------------------------------===//
1580// Preprocessor Directive Handling.
1581//===----------------------------------------------------------------------===//
1582
1583/// HandleDirective - This callback is invoked when the lexer sees a # token
1584/// at the start of a line. This consumes the directive, modifies the
1585/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1586/// read is the correct one.
Chris Lattner146762e2007-07-20 16:59:19 +00001587void Preprocessor::HandleDirective(Token &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001588 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001589
1590 // We just parsed a # character at the start of a line, so we're in directive
1591 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001592 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001593 CurLexer->ParsingPreprocessorDirective = true;
1594
1595 ++NumDirectives;
1596
Chris Lattner371ac8a2006-07-04 07:11:10 +00001597 // We are about to read a token. For the multiple-include optimization FA to
1598 // work, we have to remember if we had read any tokens *before* this
1599 // pp-directive.
1600 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1601
Chris Lattner78186052006-07-09 00:45:31 +00001602 // Read the next token, the directive flavor. This isn't expanded due to
1603 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001604 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001605
Chris Lattner78186052006-07-09 00:45:31 +00001606 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1607 // #define A(x) #x
1608 // A(abc
1609 // #warning blah
1610 // def)
1611 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001612 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001613 Diag(Result, diag::ext_embedded_directive);
1614
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001615TryAgain:
Chris Lattner22eb9722006-06-18 05:43:12 +00001616 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001617 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001618 return; // null directive.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001619 case tok::comment:
1620 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1621 LexUnexpandedToken(Result);
1622 goto TryAgain;
Chris Lattner22eb9722006-06-18 05:43:12 +00001623
Chris Lattner22eb9722006-06-18 05:43:12 +00001624 case tok::numeric_constant:
1625 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001626 DiscardUntilEndOfDirective();
1627 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001628 default:
1629 IdentifierInfo *II = Result.getIdentifierInfo();
1630 if (II == 0) break; // Not an identifier.
1631
1632 // Ask what the preprocessor keyword ID is.
1633 switch (II->getPPKeywordID()) {
1634 default: break;
1635 // C99 6.10.1 - Conditional Inclusion.
1636 case tok::pp_if:
1637 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1638 case tok::pp_ifdef:
1639 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1640 case tok::pp_ifndef:
1641 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1642 case tok::pp_elif:
1643 return HandleElifDirective(Result);
1644 case tok::pp_else:
1645 return HandleElseDirective(Result);
1646 case tok::pp_endif:
1647 return HandleEndifDirective(Result);
1648
1649 // C99 6.10.2 - Source File Inclusion.
1650 case tok::pp_include:
1651 return HandleIncludeDirective(Result); // Handle #include.
1652
1653 // C99 6.10.3 - Macro Replacement.
1654 case tok::pp_define:
1655 return HandleDefineDirective(Result, false);
1656 case tok::pp_undef:
1657 return HandleUndefDirective(Result);
1658
1659 // C99 6.10.4 - Line Control.
1660 case tok::pp_line:
1661 // FIXME: implement #line
1662 DiscardUntilEndOfDirective();
1663 return;
1664
1665 // C99 6.10.5 - Error Directive.
1666 case tok::pp_error:
1667 return HandleUserDiagnosticDirective(Result, false);
1668
1669 // C99 6.10.6 - Pragma Directive.
1670 case tok::pp_pragma:
1671 return HandlePragmaDirective();
1672
1673 // GNU Extensions.
1674 case tok::pp_import:
1675 return HandleImportDirective(Result);
1676 case tok::pp_include_next:
1677 return HandleIncludeNextDirective(Result);
1678
1679 case tok::pp_warning:
1680 Diag(Result, diag::ext_pp_warning_directive);
1681 return HandleUserDiagnosticDirective(Result, true);
1682 case tok::pp_ident:
1683 return HandleIdentSCCSDirective(Result);
1684 case tok::pp_sccs:
1685 return HandleIdentSCCSDirective(Result);
1686 case tok::pp_assert:
1687 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001688 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001689 case tok::pp_unassert:
1690 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001691 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001692
1693 // clang extensions.
1694 case tok::pp_define_target:
1695 return HandleDefineDirective(Result, true);
1696 case tok::pp_define_other_target:
1697 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001698 }
1699 break;
1700 }
1701
1702 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001703 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001704
1705 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001706 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001707
1708 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001709}
1710
Chris Lattner146762e2007-07-20 16:59:19 +00001711void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001712 bool isWarning) {
1713 // Read the rest of the line raw. We do this because we don't want macros
1714 // to be expanded and we don't require that the tokens be valid preprocessing
1715 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1716 // collapse multiple consequtive white space between tokens, but this isn't
1717 // specified by the standard.
1718 std::string Message = CurLexer->ReadToEndOfLine();
1719
1720 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001721 return Diag(Tok, DiagID, Message);
1722}
1723
1724/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1725///
Chris Lattner146762e2007-07-20 16:59:19 +00001726void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001727 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001728 Diag(Tok, diag::ext_pp_ident_directive);
1729
Chris Lattner371ac8a2006-07-04 07:11:10 +00001730 // Read the string argument.
Chris Lattner146762e2007-07-20 16:59:19 +00001731 Token StrTok;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001732 Lex(StrTok);
1733
1734 // If the token kind isn't a string, it's a malformed directive.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001735 if (StrTok.isNot(tok::string_literal) &&
1736 StrTok.isNot(tok::wide_string_literal))
Chris Lattner01d66cc2006-07-03 22:16:27 +00001737 return Diag(StrTok, diag::err_pp_malformed_ident);
1738
1739 // Verify that there is nothing after the string, other than EOM.
1740 CheckEndOfDirective("#ident");
1741
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001742 if (Callbacks)
1743 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001744}
1745
Chris Lattnerb8761832006-06-24 21:31:03 +00001746//===----------------------------------------------------------------------===//
1747// Preprocessor Include Directive Handling.
1748//===----------------------------------------------------------------------===//
1749
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001750/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1751/// checked and spelled filename, e.g. as an operand of #include. This returns
1752/// true if the input filename was in <>'s or false if it were in ""'s. The
1753/// caller is expected to provide a buffer that is large enough to hold the
1754/// spelling of the filename, but is also expected to handle the case when
1755/// this method decides to use a different buffer.
Chris Lattner93ab9f12007-07-23 04:15:27 +00001756bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001757 const char *&BufStart,
1758 const char *&BufEnd) {
1759 // Get the text form of the filename.
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001760 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1761
1762 // Make sure the filename is <x> or "x".
1763 bool isAngled;
1764 if (BufStart[0] == '<') {
1765 if (BufEnd[-1] != '>') {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001766 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001767 BufStart = 0;
1768 return true;
1769 }
1770 isAngled = true;
1771 } else if (BufStart[0] == '"') {
1772 if (BufEnd[-1] != '"') {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001773 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001774 BufStart = 0;
1775 return true;
1776 }
1777 isAngled = false;
1778 } else {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001779 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001780 BufStart = 0;
1781 return true;
1782 }
1783
1784 // Diagnose #include "" as invalid.
1785 if (BufEnd-BufStart <= 2) {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001786 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001787 BufStart = 0;
1788 return "";
1789 }
1790
1791 // Skip the brackets.
1792 ++BufStart;
1793 --BufEnd;
1794 return isAngled;
1795}
1796
Chris Lattner43eafb42007-07-23 04:56:47 +00001797/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1798/// from a macro as multiple tokens, which need to be glued together. This
1799/// occurs for code like:
1800/// #define FOO <a/b.h>
1801/// #include FOO
1802/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1803///
1804/// This code concatenates and consumes tokens up to the '>' token. It returns
1805/// false if the > was found, otherwise it returns true if it finds and consumes
1806/// the EOM marker.
1807static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
1808 Preprocessor &PP) {
1809 Token CurTok;
1810
1811 PP.Lex(CurTok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001812 while (CurTok.isNot(tok::eom)) {
Chris Lattner43eafb42007-07-23 04:56:47 +00001813 // Append the spelling of this token to the buffer. If there was a space
1814 // before it, add it now.
1815 if (CurTok.hasLeadingSpace())
1816 FilenameBuffer.push_back(' ');
1817
1818 // Get the spelling of the token, directly into FilenameBuffer if possible.
1819 unsigned PreAppendSize = FilenameBuffer.size();
1820 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
1821
1822 const char *BufPtr = &FilenameBuffer[PreAppendSize];
1823 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
1824
1825 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1826 if (BufPtr != &FilenameBuffer[PreAppendSize])
1827 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1828
1829 // Resize FilenameBuffer to the correct size.
1830 if (CurTok.getLength() != ActualLen)
1831 FilenameBuffer.resize(PreAppendSize+ActualLen);
1832
1833 // If we found the '>' marker, return success.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001834 if (CurTok.is(tok::greater))
Chris Lattner43eafb42007-07-23 04:56:47 +00001835 return false;
1836
1837 PP.Lex(CurTok);
1838 }
1839
1840 // If we hit the eom marker, emit an error and return true so that the caller
1841 // knows the EOM has been read.
1842 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
1843 return true;
1844}
1845
Chris Lattner22eb9722006-06-18 05:43:12 +00001846/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1847/// file to be included from the lexer, then include it! This is a common
1848/// routine with functionality shared between #include, #include_next and
1849/// #import.
Chris Lattner146762e2007-07-20 16:59:19 +00001850void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001851 const DirectoryLookup *LookupFrom,
1852 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001853
Chris Lattner146762e2007-07-20 16:59:19 +00001854 Token FilenameTok;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001855 CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001856
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001857 // Reserve a buffer to get the spelling.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001858 llvm::SmallVector<char, 128> FilenameBuffer;
Chris Lattner43eafb42007-07-23 04:56:47 +00001859 const char *FilenameStart, *FilenameEnd;
1860
1861 switch (FilenameTok.getKind()) {
1862 case tok::eom:
1863 // If the token kind is EOM, the error has already been diagnosed.
1864 return;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001865
Chris Lattner43eafb42007-07-23 04:56:47 +00001866 case tok::angle_string_literal:
Chris Lattnerf97dbcb2007-07-23 22:23:52 +00001867 case tok::string_literal: {
Chris Lattner43eafb42007-07-23 04:56:47 +00001868 FilenameBuffer.resize(FilenameTok.getLength());
1869 FilenameStart = &FilenameBuffer[0];
1870 unsigned Len = getSpelling(FilenameTok, FilenameStart);
1871 FilenameEnd = FilenameStart+Len;
1872 break;
Chris Lattnerf97dbcb2007-07-23 22:23:52 +00001873 }
Chris Lattner43eafb42007-07-23 04:56:47 +00001874
1875 case tok::less:
1876 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1877 // case, glue the tokens together into FilenameBuffer and interpret those.
1878 FilenameBuffer.push_back('<');
1879 if (ConcatenateIncludeName(FilenameBuffer, *this))
1880 return; // Found <eom> but no ">"? Diagnostic already emitted.
1881 FilenameStart = &FilenameBuffer[0];
1882 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
1883 break;
1884 default:
1885 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1886 DiscardUntilEndOfDirective();
1887 return;
1888 }
1889
Chris Lattner93ab9f12007-07-23 04:15:27 +00001890 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001891 FilenameStart, FilenameEnd);
1892 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1893 // error.
Chris Lattner43eafb42007-07-23 04:56:47 +00001894 if (FilenameStart == 0) {
1895 DiscardUntilEndOfDirective();
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001896 return;
Chris Lattner43eafb42007-07-23 04:56:47 +00001897 }
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001898
Chris Lattner269c2322006-06-25 06:23:00 +00001899 // Verify that there is nothing after the filename, other than EOM. Use the
1900 // preprocessor to lex this in case lexing the filename entered a macro.
1901 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001902
1903 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001904 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001905 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1906
Chris Lattner22eb9722006-06-18 05:43:12 +00001907 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001908 const DirectoryLookup *CurDir;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001909 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
Chris Lattnerb8b94f12006-10-30 05:38:06 +00001910 isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001911 if (File == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00001912 return Diag(FilenameTok, diag::err_pp_file_not_found,
1913 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00001914
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001915 // Ask HeaderInfo if we should enter this #include file.
1916 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1917 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00001918 return;
1919 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001920
1921 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001922 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001923 if (FileID == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00001924 return Diag(FilenameTok, diag::err_pp_file_not_found,
1925 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00001926
1927 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001928 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001929}
1930
1931/// HandleIncludeNextDirective - Implements #include_next.
1932///
Chris Lattner146762e2007-07-20 16:59:19 +00001933void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
Chris Lattnercb283342006-06-18 06:48:37 +00001934 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001935
1936 // #include_next is like #include, except that we start searching after
1937 // the current found directory. If we can't do this, issue a
1938 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001939 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001940 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001941 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001942 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001943 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001944 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001945 } else {
1946 // Start looking up in the next directory.
1947 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001948 }
1949
1950 return HandleIncludeDirective(IncludeNextTok, Lookup);
1951}
1952
1953/// HandleImportDirective - Implements #import.
1954///
Chris Lattner146762e2007-07-20 16:59:19 +00001955void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnercb283342006-06-18 06:48:37 +00001956 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001957
1958 return HandleIncludeDirective(ImportTok, 0, true);
1959}
1960
Chris Lattnerb8761832006-06-24 21:31:03 +00001961//===----------------------------------------------------------------------===//
1962// Preprocessor Macro Directive Handling.
1963//===----------------------------------------------------------------------===//
1964
Chris Lattnercefc7682006-07-08 08:28:12 +00001965/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1966/// definition has just been read. Lex the rest of the arguments and the
1967/// closing ), updating MI with what we learn. Return true if an error occurs
1968/// parsing the arg list.
1969bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner564f4782007-07-14 22:46:43 +00001970 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
1971
Chris Lattner146762e2007-07-20 16:59:19 +00001972 Token Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001973 while (1) {
1974 LexUnexpandedToken(Tok);
1975 switch (Tok.getKind()) {
1976 case tok::r_paren:
1977 // Found the end of the argument list.
Chris Lattner564f4782007-07-14 22:46:43 +00001978 if (Arguments.empty()) { // #define FOO()
1979 MI->setArgumentList(Arguments.begin(), Arguments.end());
1980 return false;
1981 }
Chris Lattnercefc7682006-07-08 08:28:12 +00001982 // Otherwise we have #define FOO(A,)
1983 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1984 return true;
1985 case tok::ellipsis: // #define X(... -> C99 varargs
1986 // Warn if use of C99 feature in non-C99 mode.
1987 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1988
1989 // Lex the token after the identifier.
1990 LexUnexpandedToken(Tok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001991 if (Tok.isNot(tok::r_paren)) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001992 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1993 return true;
1994 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001995 // Add the __VA_ARGS__ identifier as an argument.
Chris Lattner564f4782007-07-14 22:46:43 +00001996 Arguments.push_back(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001997 MI->setIsC99Varargs();
Chris Lattner564f4782007-07-14 22:46:43 +00001998 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001999 return false;
2000 case tok::eom: // #define X(
2001 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2002 return true;
Chris Lattner62aa0d42006-10-20 05:08:24 +00002003 default:
2004 // Handle keywords and identifiers here to accept things like
2005 // #define Foo(for) for.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002006 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner62aa0d42006-10-20 05:08:24 +00002007 if (II == 0) {
2008 // #define X(1
2009 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
2010 return true;
2011 }
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002012
2013 // If this is already used as an argument, it is used multiple times (e.g.
2014 // #define X(A,A.
Chris Lattner564f4782007-07-14 22:46:43 +00002015 if (std::find(Arguments.begin(), Arguments.end(), II) !=
2016 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002017 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
2018 return true;
2019 }
2020
2021 // Add the argument to the macro info.
Chris Lattner564f4782007-07-14 22:46:43 +00002022 Arguments.push_back(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00002023
2024 // Lex the token after the identifier.
2025 LexUnexpandedToken(Tok);
2026
2027 switch (Tok.getKind()) {
2028 default: // #define X(A B
2029 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2030 return true;
2031 case tok::r_paren: // #define X(A)
Chris Lattner564f4782007-07-14 22:46:43 +00002032 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00002033 return false;
2034 case tok::comma: // #define X(A,
2035 break;
2036 case tok::ellipsis: // #define X(A... -> GCC extension
2037 // Diagnose extension.
2038 Diag(Tok, diag::ext_named_variadic_macro);
2039
2040 // Lex the token after the identifier.
2041 LexUnexpandedToken(Tok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002042 if (Tok.isNot(tok::r_paren)) {
Chris Lattnercefc7682006-07-08 08:28:12 +00002043 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2044 return true;
2045 }
2046
2047 MI->setIsGNUVarargs();
Chris Lattner564f4782007-07-14 22:46:43 +00002048 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00002049 return false;
2050 }
2051 }
2052 }
2053}
2054
Chris Lattner22eb9722006-06-18 05:43:12 +00002055/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00002056/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
2057/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00002058///
Chris Lattner146762e2007-07-20 16:59:19 +00002059void Preprocessor::HandleDefineDirective(Token &DefineTok,
Chris Lattner81278c62006-10-14 19:03:49 +00002060 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002061 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002062
Chris Lattner146762e2007-07-20 16:59:19 +00002063 Token MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00002064 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00002065
2066 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002067 if (MacroNameTok.is(tok::eom))
Chris Lattnercb283342006-06-18 06:48:37 +00002068 return;
Chris Lattnerf40fe992007-07-14 22:11:41 +00002069
Chris Lattner457fc152006-07-29 06:30:25 +00002070 // If we are supposed to keep comments in #defines, reenable comment saving
2071 // mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00002072 CurLexer->KeepCommentMode = KeepMacroComments;
Chris Lattner457fc152006-07-29 06:30:25 +00002073
Chris Lattner063400e2006-10-14 19:54:15 +00002074 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00002075 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00002076 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00002077
Chris Lattner063400e2006-10-14 19:54:15 +00002078 // If the identifier is an 'other target' macro, clear this bit.
2079 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2080
2081
Chris Lattner146762e2007-07-20 16:59:19 +00002082 Token Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00002083 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00002084
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002085 // If this is a function-like macro definition, parse the argument list,
2086 // marking each of the identifiers as being used as macro arguments. Also,
2087 // check other constraints on the first token of the macro body.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002088 if (Tok.is(tok::eom)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002089 // If there is no body to this macro, we have no special handling here.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002090 } else if (Tok.is(tok::l_paren) && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00002091 // This is a function-like macro definition. Read the argument list.
2092 MI->setIsFunctionLike();
2093 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002094 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00002095 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002096 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00002097 if (CurLexer->ParsingPreprocessorDirective)
2098 DiscardUntilEndOfDirective();
2099 return;
2100 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002101
Chris Lattner815a1f92006-07-08 20:48:04 +00002102 // Read the first token after the arg list for down below.
2103 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00002104 } else if (!Tok.hasLeadingSpace()) {
2105 // C99 requires whitespace between the macro definition and the body. Emit
2106 // a diagnostic for something like "#define X+".
2107 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00002108 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00002109 } else {
2110 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
2111 // one in some cases!
2112 }
2113 } else {
2114 // This is a normal token with leading space. Clear the leading space
2115 // marker on the first token to get proper expansion.
Chris Lattner146762e2007-07-20 16:59:19 +00002116 Tok.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002117 }
2118
Chris Lattner7e374832006-07-29 03:46:57 +00002119 // If this is a definition of a variadic C99 function-like macro, not using
2120 // the GNU named varargs extension, enabled __VA_ARGS__.
2121
2122 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
2123 // This gets unpoisoned where it is allowed.
2124 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
2125 if (MI->isC99Varargs())
2126 Ident__VA_ARGS__->setIsPoisoned(false);
2127
Chris Lattner22eb9722006-06-18 05:43:12 +00002128 // Read the rest of the macro body.
Chris Lattnera3834342007-07-14 21:54:03 +00002129 if (MI->isObjectLike()) {
2130 // Object-like macros are very simple, just read their body.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002131 while (Tok.isNot(tok::eom)) {
Chris Lattnera3834342007-07-14 21:54:03 +00002132 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00002133 // Get the next token of the macro.
2134 LexUnexpandedToken(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00002135 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002136
Chris Lattnera3834342007-07-14 21:54:03 +00002137 } else {
2138 // Otherwise, read the body of a function-like macro. This has to validate
2139 // the # (stringize) operator.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002140 while (Tok.isNot(tok::eom)) {
Chris Lattnera3834342007-07-14 21:54:03 +00002141 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002142
Chris Lattnera3834342007-07-14 21:54:03 +00002143 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
2144 // parameters in function-like macro expansions.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002145 if (Tok.isNot(tok::hash)) {
Chris Lattnera3834342007-07-14 21:54:03 +00002146 // Get the next token of the macro.
2147 LexUnexpandedToken(Tok);
2148 continue;
2149 }
2150
2151 // Get the next token of the macro.
2152 LexUnexpandedToken(Tok);
2153
2154 // Not a macro arg identifier?
2155 if (!Tok.getIdentifierInfo() ||
2156 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2157 Diag(Tok, diag::err_pp_stringize_not_parameter);
2158 delete MI;
2159
2160 // Disable __VA_ARGS__ again.
2161 Ident__VA_ARGS__->setIsPoisoned(true);
2162 return;
2163 }
2164
2165 // Things look ok, add the param name token to the macro.
2166 MI->AddTokenToBody(Tok);
2167
2168 // Get the next token of the macro.
2169 LexUnexpandedToken(Tok);
2170 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002171 }
Chris Lattner7e374832006-07-29 03:46:57 +00002172
Chris Lattnerf40fe992007-07-14 22:11:41 +00002173
Chris Lattner7e374832006-07-29 03:46:57 +00002174 // Disable __VA_ARGS__ again.
2175 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002176
Chris Lattnerbff18d52006-07-06 04:49:18 +00002177 // Check that there is no paste (##) operator at the begining or end of the
2178 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00002179 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00002180 if (NumTokens != 0) {
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002181 if (MI->getReplacementToken(0).is(tok::hashhash)) {
Chris Lattner815a1f92006-07-08 20:48:04 +00002182 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002183 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00002184 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00002185 }
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002186 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
Chris Lattner815a1f92006-07-08 20:48:04 +00002187 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002188 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00002189 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00002190 }
2191 }
2192
Chris Lattner13044d92006-07-03 05:16:44 +00002193 // If this is the primary source file, remember that this macro hasn't been
2194 // used yet.
2195 if (isInPrimaryFile())
2196 MI->setIsUsed(false);
2197
Chris Lattner22eb9722006-06-18 05:43:12 +00002198 // Finally, if this identifier already had a macro defined for it, verify that
2199 // the macro bodies are identical and free the old definition.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002200 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner13044d92006-07-03 05:16:44 +00002201 if (!OtherMI->isUsed())
2202 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
2203
Chris Lattner22eb9722006-06-18 05:43:12 +00002204 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00002205 // must be the same. C99 6.10.3.2.
2206 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00002207 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
2208 MacroNameTok.getIdentifierInfo()->getName());
2209 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
2210 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002211 delete OtherMI;
2212 }
2213
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002214 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00002215}
2216
Chris Lattner063400e2006-10-14 19:54:15 +00002217/// HandleDefineOtherTargetDirective - Implements #define_other_target.
Chris Lattner146762e2007-07-20 16:59:19 +00002218void Preprocessor::HandleDefineOtherTargetDirective(Token &Tok) {
2219 Token MacroNameTok;
Chris Lattner063400e2006-10-14 19:54:15 +00002220 ReadMacroName(MacroNameTok, 1);
2221
2222 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002223 if (MacroNameTok.is(tok::eom))
Chris Lattner063400e2006-10-14 19:54:15 +00002224 return;
2225
2226 // Check to see if this is the last token on the #undef line.
2227 CheckEndOfDirective("#define_other_target");
2228
2229 // If there is already a macro defined by this name, turn it into a
2230 // target-specific define.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002231 if (MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner063400e2006-10-14 19:54:15 +00002232 MI->setIsTargetSpecific(true);
2233 return;
2234 }
2235
2236 // Mark the identifier as being a macro on some other target.
2237 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
2238}
2239
Chris Lattner22eb9722006-06-18 05:43:12 +00002240
2241/// HandleUndefDirective - Implements #undef.
2242///
Chris Lattner146762e2007-07-20 16:59:19 +00002243void Preprocessor::HandleUndefDirective(Token &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002244 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002245
Chris Lattner146762e2007-07-20 16:59:19 +00002246 Token MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00002247 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00002248
2249 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002250 if (MacroNameTok.is(tok::eom))
Chris Lattnercb283342006-06-18 06:48:37 +00002251 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002252
2253 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00002254 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00002255
2256 // Okay, we finally have a valid identifier to undef.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002257 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Chris Lattner22eb9722006-06-18 05:43:12 +00002258
Chris Lattner063400e2006-10-14 19:54:15 +00002259 // #undef untaints an identifier if it were marked by define_other_target.
2260 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2261
Chris Lattner22eb9722006-06-18 05:43:12 +00002262 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00002263 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00002264
Chris Lattner13044d92006-07-03 05:16:44 +00002265 if (!MI->isUsed())
2266 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00002267
2268 // Free macro definition.
2269 delete MI;
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002270 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
Chris Lattner22eb9722006-06-18 05:43:12 +00002271}
2272
2273
Chris Lattnerb8761832006-06-24 21:31:03 +00002274//===----------------------------------------------------------------------===//
2275// Preprocessor Conditional Directive Handling.
2276//===----------------------------------------------------------------------===//
2277
Chris Lattner22eb9722006-06-18 05:43:12 +00002278/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00002279/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
2280/// if any tokens have been returned or pp-directives activated before this
2281/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00002282///
Chris Lattner146762e2007-07-20 16:59:19 +00002283void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
Chris Lattner371ac8a2006-07-04 07:11:10 +00002284 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002285 ++NumIf;
Chris Lattner146762e2007-07-20 16:59:19 +00002286 Token DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002287
Chris Lattner146762e2007-07-20 16:59:19 +00002288 Token MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00002289 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00002290
2291 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002292 if (MacroNameTok.is(tok::eom)) {
Chris Lattnerd05e44e2007-09-24 05:14:57 +00002293 // Skip code until we get to #endif. This helps with recovery by not
2294 // emitting an error when the #endif is reached.
2295 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2296 /*Foundnonskip*/false, /*FoundElse*/false);
Chris Lattnercb283342006-06-18 06:48:37 +00002297 return;
Chris Lattnerd05e44e2007-09-24 05:14:57 +00002298 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002299
2300 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00002301 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
2302
2303 // If the start of a top-level #ifdef, inform MIOpt.
2304 if (!ReadAnyTokensBeforeDirective &&
2305 CurLexer->getConditionalStackDepth() == 0) {
2306 assert(isIfndef && "#ifdef shouldn't reach here");
2307 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
2308 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002309
Chris Lattner063400e2006-10-14 19:54:15 +00002310 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002311 MacroInfo *MI = getMacroInfo(MII);
Chris Lattnera78a97e2006-07-03 05:42:18 +00002312
Chris Lattner81278c62006-10-14 19:03:49 +00002313 // If there is a macro, process it.
2314 if (MI) {
2315 // Mark it used.
2316 MI->setIsUsed(true);
2317
2318 // If this is the first use of a target-specific macro, warn about it.
2319 if (MI->isTargetSpecific()) {
2320 MI->setIsTargetSpecific(false); // Don't warn on second use.
2321 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2322 diag::port_target_macro_use);
2323 }
Chris Lattner063400e2006-10-14 19:54:15 +00002324 } else {
2325 // Use of a target-specific macro for some other target? If so, warn.
2326 if (MII->isOtherTargetMacro()) {
2327 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
2328 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2329 diag::port_target_macro_use);
2330 }
Chris Lattner81278c62006-10-14 19:03:49 +00002331 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00002332
Chris Lattner22eb9722006-06-18 05:43:12 +00002333 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00002334 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002335 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002336 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002337 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002338 } else {
2339 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002340 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00002341 /*Foundnonskip*/false,
2342 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002343 }
2344}
2345
2346/// HandleIfDirective - Implements the #if directive.
2347///
Chris Lattner146762e2007-07-20 16:59:19 +00002348void Preprocessor::HandleIfDirective(Token &IfToken,
Chris Lattnera8654ca2006-07-04 17:42:08 +00002349 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002350 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002351
Chris Lattner371ac8a2006-07-04 07:11:10 +00002352 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00002353 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00002354 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00002355
2356 // Should we include the stuff contained by this directive?
2357 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00002358 // If this condition is equivalent to #ifndef X, and if this is the first
2359 // directive seen, handle it for the multiple-include optimization.
2360 if (!ReadAnyTokensBeforeDirective &&
2361 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2362 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2363
Chris Lattner22eb9722006-06-18 05:43:12 +00002364 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002365 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002366 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002367 } else {
2368 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002369 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00002370 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002371 }
2372}
2373
2374/// HandleEndifDirective - Implements the #endif directive.
2375///
Chris Lattner146762e2007-07-20 16:59:19 +00002376void Preprocessor::HandleEndifDirective(Token &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002377 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002378
Chris Lattner22eb9722006-06-18 05:43:12 +00002379 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00002380 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00002381
2382 PPConditionalInfo CondInfo;
2383 if (CurLexer->popConditionalLevel(CondInfo)) {
2384 // No conditionals on the stack: this is an #endif without an #if.
2385 return Diag(EndifToken, diag::err_pp_endif_without_if);
2386 }
2387
Chris Lattner371ac8a2006-07-04 07:11:10 +00002388 // If this the end of a top-level #endif, inform MIOpt.
2389 if (CurLexer->getConditionalStackDepth() == 0)
2390 CurLexer->MIOpt.ExitTopLevelConditional();
2391
Chris Lattner538d7f32006-07-20 04:31:52 +00002392 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00002393 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00002394}
2395
2396
Chris Lattner146762e2007-07-20 16:59:19 +00002397void Preprocessor::HandleElseDirective(Token &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002398 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002399
Chris Lattner22eb9722006-06-18 05:43:12 +00002400 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00002401 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00002402
2403 PPConditionalInfo CI;
2404 if (CurLexer->popConditionalLevel(CI))
2405 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00002406
2407 // If this is a top-level #else, inform the MIOpt.
2408 if (CurLexer->getConditionalStackDepth() == 0)
2409 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00002410
2411 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002412 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002413
2414 // Finally, skip the rest of the contents of this block and return the first
2415 // token after it.
2416 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2417 /*FoundElse*/true);
2418}
2419
Chris Lattner146762e2007-07-20 16:59:19 +00002420void Preprocessor::HandleElifDirective(Token &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002421 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002422
Chris Lattner22eb9722006-06-18 05:43:12 +00002423 // #elif directive in a non-skipping conditional... start skipping.
2424 // We don't care what the condition is, because we will always skip it (since
2425 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002426 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002427
2428 PPConditionalInfo CI;
2429 if (CurLexer->popConditionalLevel(CI))
2430 return Diag(ElifToken, diag::pp_err_elif_without_if);
2431
Chris Lattner371ac8a2006-07-04 07:11:10 +00002432 // If this is a top-level #elif, inform the MIOpt.
2433 if (CurLexer->getConditionalStackDepth() == 0)
2434 CurLexer->MIOpt.FoundTopLevelElse();
2435
Chris Lattner22eb9722006-06-18 05:43:12 +00002436 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002437 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002438
2439 // Finally, skip the rest of the contents of this block and return the first
2440 // token after it.
2441 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2442 /*FoundElse*/CI.FoundElse);
2443}
Chris Lattnerb8761832006-06-24 21:31:03 +00002444