blob: 0d3ac521d05638efb687a58c673fcbeab69bf975 [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");
385 DefineBuiltinMacro(Buf, "__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__=1030");
386 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
419
420 std::vector<char> PrologFile;
421 PrologFile.reserve(4080);
422
423 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
424 InitializePredefinedMacros(*this, PrologFile);
425
426 // Add on the predefines from the driver.
427 PrologFile.insert(PrologFile.end(), Predefines,Predefines+strlen(Predefines));
428
429 // Memory buffer must end with a null byte!
430 PrologFile.push_back(0);
431
432 // Now that we have emitted the predefined macros, #includes, etc into
433 // PrologFile, preprocess it to populate the initial preprocessor state.
434 llvm::MemoryBuffer *SB =
435 llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(),
436 "<predefines>");
437 assert(SB && "Cannot fail to create predefined source buffer");
438 unsigned FileID = SourceMgr.createFileIDForMemBuffer(SB);
439 assert(FileID && "Could not create FileID for predefines?");
440
441 // Start parsing the predefines.
442 EnterSourceFile(FileID, 0);
443}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000444
Chris Lattnerd01e2912006-06-18 16:22:51 +0000445//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000446// Source File Location Methods.
447//===----------------------------------------------------------------------===//
448
Chris Lattner22eb9722006-06-18 05:43:12 +0000449/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
450/// return null on failure. isAngled indicates whether the file reference is
451/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnerb8b94f12006-10-30 05:38:06 +0000452const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
453 const char *FilenameEnd,
Chris Lattnerc8997182006-06-22 05:52:16 +0000454 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000455 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000456 const DirectoryLookup *&CurDir) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000457 // If the header lookup mechanism may be relative to the current file, pass in
458 // info about where the current file is.
459 const FileEntry *CurFileEnt = 0;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000460 if (!FromDir) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000461 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
462 CurFileEnt = SourceMgr.getFileEntryForLoc(FileLoc);
Chris Lattner22eb9722006-06-18 05:43:12 +0000463 }
464
Chris Lattner63dd32b2006-10-20 04:42:40 +0000465 // Do a standard file entry lookup.
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000466 CurDir = CurDirLookup;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000467 const FileEntry *FE =
Chris Lattner7cdbad92006-10-30 05:33:15 +0000468 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
469 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000470 if (FE) return FE;
471
472 // Otherwise, see if this is a subframework header. If so, this is relative
473 // to one of the headers on the #include stack. Walk the list of the current
474 // headers on the #include stack and pass them to HeaderInfo.
Chris Lattner5c683b22006-10-20 05:12:14 +0000475 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000476 CurFileEnt = SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000477 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
478 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000479 return FE;
480 }
481
482 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
483 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Chris Lattner5c683b22006-10-20 05:12:14 +0000484 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000485 CurFileEnt = SourceMgr.getFileEntryForLoc(ISEntry.TheLexer->getFileLoc());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000486 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
487 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000488 return FE;
489 }
490 }
491
492 // Otherwise, we really couldn't find the file.
493 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000494}
495
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000496/// isInPrimaryFile - Return true if we're in the top-level file, not in a
497/// #include.
498bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000499 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000500 return IncludeMacroStack.empty();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000501
Chris Lattner13044d92006-07-03 05:16:44 +0000502 // If there are any stacked lexers, we're in a #include.
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000503 assert(IncludeMacroStack[0].TheLexer &&
504 !IncludeMacroStack[0].TheLexer->Is_PragmaLexer &&
505 "Top level include stack isn't our primary lexer?");
506 for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000507 if (IncludeMacroStack[i].TheLexer &&
508 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000509 return false;
510 return true;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000511}
512
513/// getCurrentLexer - Return the current file lexer being lexed from. Note
514/// that this ignores any potentially active macro expansions and _Pragma
515/// expansions going on at the time.
516Lexer *Preprocessor::getCurrentFileLexer() const {
517 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
518
519 // Look for a stacked lexer.
520 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000521 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000522 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
523 return L;
524 }
525 return 0;
526}
527
528
Chris Lattner22eb9722006-06-18 05:43:12 +0000529/// EnterSourceFile - Add a source file to the top of the include stack and
530/// start lexing tokens from it instead of the current buffer. Return true
531/// on failure.
532void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000533 const DirectoryLookup *CurDir) {
Chris Lattner69772b02006-07-02 20:34:39 +0000534 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000535 ++NumEnteredSourceFiles;
536
Chris Lattner69772b02006-07-02 20:34:39 +0000537 if (MaxIncludeStackDepth < IncludeMacroStack.size())
538 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000539
Chris Lattner77e9de52007-07-20 16:52:03 +0000540 Lexer *TheLexer = new Lexer(SourceLocation::getFileLoc(FileID, 0), *this);
Chris Lattner69772b02006-07-02 20:34:39 +0000541 EnterSourceFileWithLexer(TheLexer, CurDir);
542}
Chris Lattner22eb9722006-06-18 05:43:12 +0000543
Chris Lattner69772b02006-07-02 20:34:39 +0000544/// EnterSourceFile - Add a source file to the top of the include stack and
545/// start lexing tokens from it instead of the current buffer.
546void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
547 const DirectoryLookup *CurDir) {
548
549 // Add the current lexer to the include stack.
550 if (CurLexer || CurMacroExpander)
551 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
552 CurMacroExpander));
553
554 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000555 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000556 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000557
558 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000559 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000560 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
561
562 // Get the file entry for the current file.
563 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000564 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000565 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000566
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000567 Callbacks->FileChanged(CurLexer->getFileLoc(),
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000568 PPCallbacks::EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000569 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000570}
571
Chris Lattner69772b02006-07-02 20:34:39 +0000572
573
Chris Lattner22eb9722006-06-18 05:43:12 +0000574/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000575/// tokens from it instead of the current buffer.
Chris Lattner146762e2007-07-20 16:59:19 +0000576void Preprocessor::EnterMacro(Token &Tok, MacroArgs *Args) {
Chris Lattner69772b02006-07-02 20:34:39 +0000577 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
578 CurMacroExpander));
579 CurLexer = 0;
580 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000581
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000582 if (NumCachedMacroExpanders == 0) {
583 CurMacroExpander = new MacroExpander(Tok, Args, *this);
584 } else {
585 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
586 CurMacroExpander->Init(Tok, Args);
587 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000588}
589
Chris Lattner7667d0d2006-07-16 18:16:58 +0000590/// EnterTokenStream - Add a "macro" context to the top of the include stack,
591/// which will cause the lexer to start returning the specified tokens. Note
592/// that these tokens will be re-macro-expanded when/if expansion is enabled.
593/// This method assumes that the specified stream of tokens has a permanent
594/// owner somewhere, so they do not need to be copied.
Chris Lattner146762e2007-07-20 16:59:19 +0000595void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000596 // Save our current state.
597 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
598 CurMacroExpander));
599 CurLexer = 0;
600 CurDirLookup = 0;
601
602 // Create a macro expander to expand from the specified token stream.
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000603 if (NumCachedMacroExpanders == 0) {
604 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
605 } else {
606 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
607 CurMacroExpander->Init(Toks, NumToks);
608 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000609}
610
611/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
612/// lexer stack. This should only be used in situations where the current
613/// state of the top-of-stack lexer is known.
614void Preprocessor::RemoveTopOfLexerStack() {
615 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000616
617 if (CurMacroExpander) {
618 // Delete or cache the now-dead macro expander.
619 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
620 delete CurMacroExpander;
621 else
622 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
623 } else {
624 delete CurLexer;
625 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000626 CurLexer = IncludeMacroStack.back().TheLexer;
627 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
628 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
629 IncludeMacroStack.pop_back();
630}
631
Chris Lattner22eb9722006-06-18 05:43:12 +0000632//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000633// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000634//===----------------------------------------------------------------------===//
635
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000636/// setMacroInfo - Specify a macro for this identifier.
637///
638void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
639 if (MI == 0) {
640 if (II->hasMacroDefinition()) {
641 Macros.erase(II);
642 II->setHasMacroDefinition(false);
643 }
644 } else {
645 Macros[II] = MI;
646 II->setHasMacroDefinition(true);
647 }
648}
649
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000650/// RegisterBuiltinMacro - Register the specified identifier in the identifier
651/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000652IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000653 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000654 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000655
656 // Mark it as being a macro that is builtin.
657 MacroInfo *MI = new MacroInfo(SourceLocation());
658 MI->setIsBuiltinMacro();
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000659 setMacroInfo(Id, MI);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000660 return Id;
661}
662
663
Chris Lattner677757a2006-06-28 05:26:32 +0000664/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
665/// identifier table.
666void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000667 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000668 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000669 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
670 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000671 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000672
673 // GCC Extensions.
674 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
675 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000676 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000677}
678
Chris Lattnerc2395832006-07-09 00:57:04 +0000679/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
680/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000681static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000682 const IdentifierInfo *MacroIdent,
683 Preprocessor &PP) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000684 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
685
686 // If the token isn't an identifier, it's always literally expanded.
687 if (II == 0) return true;
688
689 // If the identifier is a macro, and if that macro is enabled, it may be
690 // expanded so it's not a trivial expansion.
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000691 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000692 // Fast expanding "#define X X" is ok, because X would be disabled.
693 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000694 return false;
695
696 // If this is an object-like macro invocation, it is safe to trivially expand
697 // it.
698 if (MI->isObjectLike()) return true;
699
700 // If this is a function-like macro invocation, it's safe to trivially expand
701 // as long as the identifier is not a macro argument.
702 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
703 I != E; ++I)
704 if (*I == II)
705 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000706
Chris Lattnerc2395832006-07-09 00:57:04 +0000707 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000708}
709
Chris Lattnerc2395832006-07-09 00:57:04 +0000710
Chris Lattnerafe603f2006-07-11 04:02:46 +0000711/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
712/// lexed is a '('. If so, consume the token and return true, if not, this
713/// method should have no observable side-effect on the lexed tokens.
714bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000715 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000716 unsigned Val;
717 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000718 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000719 else
720 Val = CurMacroExpander->isNextTokenLParen();
721
722 if (Val == 2) {
Chris Lattner5c983792007-07-19 00:07:36 +0000723 // We have run off the end. If it's a source file we don't
724 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
725 // macro stack.
726 if (CurLexer)
727 return false;
728 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000729 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
730 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000731 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000732 else
733 Val = Entry.TheMacroExpander->isNextTokenLParen();
Chris Lattner5c983792007-07-19 00:07:36 +0000734
735 if (Val != 2)
736 break;
737
738 // Ran off the end of a source file?
739 if (Entry.TheLexer)
740 return false;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000741 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000742 }
743
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000744 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
745 // have found something that isn't a '(' or we found the end of the
746 // translation unit. In either case, return false.
747 if (Val != 1)
748 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000749
Chris Lattner146762e2007-07-20 16:59:19 +0000750 Token Tok;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000751 LexUnexpandedToken(Tok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000752 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000753 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000754}
Chris Lattner677757a2006-06-28 05:26:32 +0000755
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000756/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
757/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner146762e2007-07-20 16:59:19 +0000758bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000759 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000760
761 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
762 if (MI->isBuiltinMacro()) {
763 ExpandBuiltinMacro(Identifier);
764 return false;
765 }
766
Chris Lattner81278c62006-10-14 19:03:49 +0000767 // If this is the first use of a target-specific macro, warn about it.
768 if (MI->isTargetSpecific()) {
769 MI->setIsTargetSpecific(false); // Don't warn on second use.
770 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
771 diag::port_target_macro_use);
772 }
773
Chris Lattneree8760b2006-07-15 07:42:55 +0000774 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000775 /// for each macro argument, the list of tokens that were provided to the
776 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000777 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000778
779 // If this is a function-like macro, read the arguments.
780 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000781 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner24dbee72007-07-19 16:11:58 +0000782 // name isn't a '(', this macro should not be expanded. Otherwise, consume
783 // it.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000784 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000785 return true;
786
Chris Lattner78186052006-07-09 00:45:31 +0000787 // Remember that we are now parsing the arguments to a macro invocation.
788 // Preprocessor directives used inside macro arguments are not portable, and
789 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000790 InMacroArgs = true;
791 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000792
793 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000794 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000795
796 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000797 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000798
799 ++NumFnMacroExpanded;
800 } else {
801 ++NumMacroExpanded;
802 }
Chris Lattner13044d92006-07-03 05:16:44 +0000803
804 // Notice that this macro has been used.
805 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000806
807 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000808
809 // If this macro expands to no tokens, don't bother to push it onto the
810 // expansion stack, only to take it right back off.
811 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000812 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000813 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000814
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000815 // Ignore this macro use, just return the next token in the current
816 // buffer.
817 bool HadLeadingSpace = Identifier.hasLeadingSpace();
818 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
819
820 Lex(Identifier);
821
822 // If the identifier isn't on some OTHER line, inherit the leading
823 // whitespace/first-on-a-line property of this token. This handles
824 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
825 // empty.
826 if (!Identifier.isAtStartOfLine()) {
Chris Lattner146762e2007-07-20 16:59:19 +0000827 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
828 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000829 }
830 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000831 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000832
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000833 } else if (MI->getNumTokens() == 1 &&
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000834 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
835 *this)){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000836 // Otherwise, if this macro expands into a single trivially-expanded
837 // token: expand it now. This handles common cases like
838 // "#define VAL 42".
839
840 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
841 // identifier to the expanded token.
842 bool isAtStartOfLine = Identifier.isAtStartOfLine();
843 bool hasLeadingSpace = Identifier.hasLeadingSpace();
844
845 // Remember where the token is instantiated.
846 SourceLocation InstantiateLoc = Identifier.getLocation();
847
848 // Replace the result token.
849 Identifier = MI->getReplacementToken(0);
850
851 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner146762e2007-07-20 16:59:19 +0000852 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
853 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000854
855 // Update the tokens location to include both its logical and physical
856 // locations.
857 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000858 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000859 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000860
Chris Lattner6e4bf522006-07-27 06:59:25 +0000861 // If this is #define X X, we must mark the result as unexpandible.
862 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000863 if (getMacroInfo(NewII) == MI)
Chris Lattner146762e2007-07-20 16:59:19 +0000864 Identifier.setFlag(Token::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000865
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000866 // Since this is not an identifier token, it can't be macro expanded, so
867 // we're done.
868 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000869 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000870 }
871
Chris Lattner78186052006-07-09 00:45:31 +0000872 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000873 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000874
875 // Now that the macro is at the top of the include stack, ask the
876 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000877 Lex(Identifier);
878 return false;
879}
880
Chris Lattneree8760b2006-07-15 07:42:55 +0000881/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000882/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000883/// invocation. This returns null on error.
Chris Lattner146762e2007-07-20 16:59:19 +0000884MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattneree8760b2006-07-15 07:42:55 +0000885 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000886 // The number of fixed arguments to parse.
887 unsigned NumFixedArgsLeft = MI->getNumArgs();
888 bool isVariadic = MI->isVariadic();
889
Chris Lattner78186052006-07-09 00:45:31 +0000890 // Outer loop, while there are more arguments, keep reading them.
Chris Lattner146762e2007-07-20 16:59:19 +0000891 Token Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000892 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000893 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000894
895 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000896 // argument is separated by an EOF token. Use a SmallVector so we can avoid
897 // heap allocations in the common case.
Chris Lattner146762e2007-07-20 16:59:19 +0000898 llvm::SmallVector<Token, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000899
900 unsigned NumActuals = 0;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000901 while (Tok.is(tok::comma)) {
Chris Lattner24dbee72007-07-19 16:11:58 +0000902 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
903 // that we already consumed the first one.
Chris Lattner78186052006-07-09 00:45:31 +0000904 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000905
Chris Lattner78186052006-07-09 00:45:31 +0000906 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000907 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
908 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000909 LexUnexpandedToken(Tok);
910
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000911 if (Tok.is(tok::eof)) {
Chris Lattner78186052006-07-09 00:45:31 +0000912 Diag(MacroName, diag::err_unterm_macro_invoc);
913 // Do not lose the EOF. Return it to the client.
914 MacroName = Tok;
915 return 0;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000916 } else if (Tok.is(tok::r_paren)) {
Chris Lattner78186052006-07-09 00:45:31 +0000917 // If we found the ) token, the macro arg list is done.
918 if (NumParens-- == 0)
919 break;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000920 } else if (Tok.is(tok::l_paren)) {
Chris Lattner78186052006-07-09 00:45:31 +0000921 ++NumParens;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000922 } else if (Tok.is(tok::comma) && NumParens == 0) {
Chris Lattner78186052006-07-09 00:45:31 +0000923 // Comma ends this argument if there are more fixed arguments expected.
924 if (NumFixedArgsLeft)
925 break;
926
Chris Lattner2ada5d32006-07-15 07:51:24 +0000927 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000928 if (!isVariadic) {
929 // Emit the diagnostic at the macro name in case there is a missing ).
930 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000931 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000932 return 0;
933 }
934 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000935 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
Chris Lattner457fc152006-07-29 06:30:25 +0000936 // If this is a comment token in the argument list and we're just in
937 // -C mode (not -CC mode), discard the comment.
938 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000939 }
940
941 ArgTokens.push_back(Tok);
942 }
943
Chris Lattnera12dd152006-07-11 04:09:02 +0000944 // Empty arguments are standard in C99 and supported as an extension in
945 // other modes.
946 if (ArgTokens.empty() && !Features.C99)
947 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000948
Chris Lattner36b6e812006-07-21 06:38:30 +0000949 // Add a marker EOF token to the end of the token list for this argument.
Chris Lattner146762e2007-07-20 16:59:19 +0000950 Token EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +0000951 EOFTok.startToken();
952 EOFTok.setKind(tok::eof);
953 EOFTok.setLocation(Tok.getLocation());
954 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +0000955 ArgTokens.push_back(EOFTok);
956 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000957 --NumFixedArgsLeft;
958 };
959
960 // Okay, we either found the r_paren. Check to see if we parsed too few
961 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000962 unsigned MinArgsExpected = MI->getNumArgs();
963
Chris Lattner775d8322006-07-29 04:39:41 +0000964 // See MacroArgs instance var for description of this.
965 bool isVarargsElided = false;
966
Chris Lattner2ada5d32006-07-15 07:51:24 +0000967 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000968 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000969 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000970 // Varargs where the named vararg parameter is missing: ok as extension.
971 // #define A(x, ...)
972 // A("blah")
973 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000974
975 // Remember this occurred if this is a C99 macro invocation with at least
976 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000977 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000978 } else if (MI->getNumArgs() == 1) {
979 // #define A(x)
980 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000981 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000982
983 // Empty arguments are standard in C99 and supported as an extension in
984 // other modes.
985 if (ArgTokens.empty() && !Features.C99)
986 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000987 } else {
988 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000989 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000990 return 0;
991 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000992
993 // Add a marker EOF token to the end of the token list for this argument.
994 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +0000995 Tok.startToken();
996 Tok.setKind(tok::eof);
997 Tok.setLocation(EndLoc);
998 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +0000999 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +00001000 }
1001
Chris Lattner775d8322006-07-29 04:39:41 +00001002 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +00001003}
1004
Chris Lattnerc673f902006-06-30 06:10:41 +00001005/// ComputeDATE_TIME - Compute the current time, enter it into the specified
1006/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
1007/// the identifier tokens inserted.
1008static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001009 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +00001010 time_t TT = time(0);
1011 struct tm *TM = localtime(&TT);
1012
1013 static const char * const Months[] = {
1014 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
1015 };
1016
1017 char TmpBuffer[100];
1018 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
1019 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001020 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +00001021
1022 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001023 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +00001024}
1025
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001026/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1027/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner146762e2007-07-20 16:59:19 +00001028void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001029 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001030 IdentifierInfo *II = Tok.getIdentifierInfo();
1031 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +00001032
1033 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
1034 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001035 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +00001036 return Handle_Pragma(Tok);
1037
Chris Lattner78186052006-07-09 00:45:31 +00001038 ++NumBuiltinMacroExpanded;
1039
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001040 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +00001041
1042 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +00001043 Tok.setIdentifierInfo(0);
Chris Lattner146762e2007-07-20 16:59:19 +00001044 Tok.clearFlag(Token::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +00001045
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001046 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001047 // __LINE__ expands to a simple numeric value.
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001048 sprintf(TmpBuffer, "%u", SourceMgr.getLogicalLineNumber(Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001049 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +00001050 Tok.setKind(tok::numeric_constant);
1051 Tok.setLength(Length);
1052 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001053 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +00001054 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001055 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +00001056 Diag(Tok, diag::ext_pp_base_file);
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001057 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc);
1058 while (NextLoc.isValid()) {
Chris Lattnerc1283b92006-07-01 23:16:30 +00001059 Loc = NextLoc;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001060 NextLoc = SourceMgr.getIncludeLoc(Loc);
Chris Lattnerc1283b92006-07-01 23:16:30 +00001061 }
1062 }
1063
Chris Lattner0766e592006-07-03 01:07:01 +00001064 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001065 std::string FN = SourceMgr.getSourceName(SourceMgr.getLogicalLoc(Loc));
Chris Lattnerecc39e92006-07-15 05:23:31 +00001066 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +00001067 Tok.setKind(tok::string_literal);
1068 Tok.setLength(FN.size());
1069 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001070 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +00001071 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001072 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +00001073 Tok.setKind(tok::string_literal);
1074 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1075 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001076 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +00001077 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +00001078 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +00001079 Tok.setKind(tok::string_literal);
1080 Tok.setLength(strlen("\"hh:mm:ss\""));
1081 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001082 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +00001083 Diag(Tok, diag::ext_pp_include_level);
1084
1085 // Compute the include depth of this token.
1086 unsigned Depth = 0;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001087 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation());
1088 for (; Loc.isValid(); ++Depth)
1089 Loc = SourceMgr.getIncludeLoc(Loc);
Chris Lattnerc1283b92006-07-01 23:16:30 +00001090
1091 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1092 sprintf(TmpBuffer, "%u", Depth);
1093 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +00001094 Tok.setKind(tok::numeric_constant);
1095 Tok.setLength(Length);
1096 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001097 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +00001098 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1099 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1100 Diag(Tok, diag::ext_pp_timestamp);
1101
1102 // Get the file that we are lexing out of. If we're currently lexing from
1103 // a macro, dig into the include stack.
1104 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +00001105 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +00001106
1107 if (TheLexer)
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001108 CurFile = SourceMgr.getFileEntryForLoc(TheLexer->getFileLoc());
Chris Lattner847e0e42006-07-01 23:49:16 +00001109
1110 // If this file is older than the file it depends on, emit a diagnostic.
1111 const char *Result;
1112 if (CurFile) {
1113 time_t TT = CurFile->getModificationTime();
1114 struct tm *TM = localtime(&TT);
1115 Result = asctime(TM);
1116 } else {
1117 Result = "??? ??? ?? ??:??:?? ????\n";
1118 }
1119 TmpBuffer[0] = '"';
1120 strcpy(TmpBuffer+1, Result);
1121 unsigned Len = strlen(TmpBuffer);
1122 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +00001123 Tok.setKind(tok::string_literal);
1124 Tok.setLength(Len);
1125 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +00001126 } else {
1127 assert(0 && "Unknown identifier!");
1128 }
1129}
Chris Lattner677757a2006-06-28 05:26:32 +00001130
1131//===----------------------------------------------------------------------===//
1132// Lexer Event Handling.
1133//===----------------------------------------------------------------------===//
1134
Chris Lattnercefc7682006-07-08 08:28:12 +00001135/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
1136/// identifier information for the token and install it into the token.
Chris Lattner146762e2007-07-20 16:59:19 +00001137IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
Chris Lattnercefc7682006-07-08 08:28:12 +00001138 const char *BufPtr) {
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001139 assert(Identifier.is(tok::identifier) && "Not an identifier!");
Chris Lattnercefc7682006-07-08 08:28:12 +00001140 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
1141
1142 // Look up this token, see if it is a macro, or if it is a language keyword.
1143 IdentifierInfo *II;
1144 if (BufPtr && !Identifier.needsCleaning()) {
1145 // No cleaning needed, just use the characters from the lexed buffer.
1146 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
1147 } else {
1148 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Chris Lattnerf9aba2c2007-07-13 17:10:38 +00001149 llvm::SmallVector<char, 64> IdentifierBuffer;
1150 IdentifierBuffer.resize(Identifier.getLength());
1151 const char *TmpBuf = &IdentifierBuffer[0];
Chris Lattnercefc7682006-07-08 08:28:12 +00001152 unsigned Size = getSpelling(Identifier, TmpBuf);
1153 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
1154 }
Chris Lattner8c204872006-10-14 05:19:21 +00001155 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001156 return II;
1157}
1158
1159
Chris Lattner677757a2006-06-28 05:26:32 +00001160/// HandleIdentifier - This callback is invoked when the lexer reads an
1161/// identifier. This callback looks up the identifier in the map and/or
1162/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattner146762e2007-07-20 16:59:19 +00001163void Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +00001164 assert(Identifier.getIdentifierInfo() &&
1165 "Can't handle identifiers without identifier info!");
1166
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001167 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +00001168
1169 // If this identifier was poisoned, and if it was not produced from a macro
1170 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +00001171 if (II.isPoisoned() && CurLexer) {
1172 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
1173 Diag(Identifier, diag::err_pp_used_poisoned_id);
1174 else
1175 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
1176 }
Chris Lattner677757a2006-06-28 05:26:32 +00001177
Chris Lattner78186052006-07-09 00:45:31 +00001178 // If this is a macro to be expanded, do it.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001179 if (MacroInfo *MI = getMacroInfo(&II)) {
Chris Lattner6e4bf522006-07-27 06:59:25 +00001180 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
1181 if (MI->isEnabled()) {
1182 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1183 return;
1184 } else {
1185 // C99 6.10.3.4p2 says that a disabled macro may never again be
1186 // expanded, even if it's in a context where it could be expanded in the
1187 // future.
Chris Lattner146762e2007-07-20 16:59:19 +00001188 Identifier.setFlag(Token::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +00001189 }
1190 }
Chris Lattner063400e2006-10-14 19:54:15 +00001191 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
1192 // If this identifier is a macro on some other target, emit a diagnostic.
1193 // This diagnosic is only emitted when macro expansion is enabled, because
1194 // the macro would not have been expanded for the other target either.
1195 II.setIsOtherTargetMacro(false); // Don't warn on second use.
1196 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
1197 diag::port_target_macro_use);
1198
1199 }
Chris Lattner677757a2006-06-28 05:26:32 +00001200
Chris Lattner5b9f4892006-11-21 17:23:33 +00001201 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
1202 // then we act as if it is the actual operator and not the textual
1203 // representation of it.
1204 if (II.isCPlusPlusOperatorKeyword())
1205 Identifier.setIdentifierInfo(0);
1206
Chris Lattner677757a2006-06-28 05:26:32 +00001207 // Change the kind of this identifier to the appropriate token kind, e.g.
1208 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +00001209 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +00001210
1211 // If this is an extension token, diagnose its use.
Steve Naroffa8fd9732007-06-11 00:35:03 +00001212 // FIXME: tried (unsuccesfully) to shut this up when compiling with gnu99
1213 // For now, I'm just commenting it out (while I work on attributes).
Chris Lattner53621a52007-06-13 20:44:40 +00001214 if (II.isExtensionToken() && Features.C99)
1215 Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +00001216}
1217
Chris Lattner22eb9722006-06-18 05:43:12 +00001218/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1219/// the current file. This either returns the EOF token or pops a level off
1220/// the include stack and keeps going.
Chris Lattner146762e2007-07-20 16:59:19 +00001221bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001222 assert(!CurMacroExpander &&
1223 "Ending a file when currently in a macro!");
1224
Chris Lattner371ac8a2006-07-04 07:11:10 +00001225 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001226 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001227 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001228 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001229 // Okay, this has a controlling macro, remember in PerFileInfo.
1230 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001231 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001232 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001233 }
1234 }
1235
Chris Lattner22eb9722006-06-18 05:43:12 +00001236 // If this is a #include'd file, pop it off the include stack and continue
1237 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001238 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001239 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001240 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001241
1242 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001243 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001244 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1245
1246 // Get the file entry for the current file.
1247 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001248 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001249 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001250
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001251 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1252 PPCallbacks::ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001253 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001254
1255 // Client should lex another token.
1256 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001257 }
1258
Chris Lattner8c204872006-10-14 05:19:21 +00001259 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +00001260 CurLexer->BufferPtr = CurLexer->BufferEnd;
1261 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +00001262 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001263
1264 // We're done with the #included file.
1265 delete CurLexer;
1266 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001267
Chris Lattner03f83482006-07-10 06:16:26 +00001268 // This is the end of the top-level file. If the diag::pp_macro_not_used
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001269 // diagnostic is enabled, look for macros that have not been used.
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001270 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001271 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
1272 Macros.begin(), E = Macros.end(); I != E; ++I) {
1273 if (!I->second->isUsed())
1274 Diag(I->second->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001275 }
1276 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001277 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001278}
1279
1280/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001281/// the current macro expansion or token stream expansion.
Chris Lattner146762e2007-07-20 16:59:19 +00001282bool Preprocessor::HandleEndOfMacro(Token &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001283 assert(CurMacroExpander && !CurLexer &&
1284 "Ending a macro when currently in a #include file!");
1285
Chris Lattnerc02c4ab2007-07-15 00:25:26 +00001286 // Delete or cache the now-dead macro expander.
1287 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
1288 delete CurMacroExpander;
1289 else
1290 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
Chris Lattner22eb9722006-06-18 05:43:12 +00001291
Chris Lattner69772b02006-07-02 20:34:39 +00001292 // Handle this like a #include file being popped off the stack.
1293 CurMacroExpander = 0;
1294 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001295}
1296
1297
1298//===----------------------------------------------------------------------===//
1299// Utility Methods for Preprocessor Directive Handling.
1300//===----------------------------------------------------------------------===//
1301
1302/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1303/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001304void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner146762e2007-07-20 16:59:19 +00001305 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00001306 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001307 LexUnexpandedToken(Tmp);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001308 } while (Tmp.isNot(tok::eom));
Chris Lattner22eb9722006-06-18 05:43:12 +00001309}
1310
Chris Lattner652c1692006-11-21 23:47:30 +00001311/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
1312static bool isCXXNamedOperator(const std::string &Spelling) {
1313 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
1314 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
1315 Spelling == "or" || Spelling == "xor";
1316}
1317
Chris Lattner22eb9722006-06-18 05:43:12 +00001318/// ReadMacroName - Lex and validate a macro name, which occurs after a
1319/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001320/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1321/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001322/// else (e.g. #ifdef).
Chris Lattner146762e2007-07-20 16:59:19 +00001323void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001324 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001325 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001326
1327 // Missing macro name?
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001328 if (MacroNameTok.is(tok::eom))
Chris Lattner22eb9722006-06-18 05:43:12 +00001329 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1330
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001331 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1332 if (II == 0) {
Chris Lattner652c1692006-11-21 23:47:30 +00001333 std::string Spelling = getSpelling(MacroNameTok);
1334 if (isCXXNamedOperator(Spelling))
1335 // C++ 2.5p2: Alternative tokens behave the same as its primary token
1336 // except for their spellings.
1337 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
1338 else
1339 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001340 // Fall through on error.
Chris Lattner2bb8a952006-11-21 22:24:17 +00001341 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001342 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001343 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattner259716a2007-10-07 08:04:56 +00001344 } else if (isDefineUndef && II->hasMacroDefinition() &&
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001345 getMacroInfo(II)->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001346 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001347 if (isDefineUndef == 1)
1348 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1349 else
1350 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001351 } else {
1352 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001353 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001354 }
1355
Chris Lattner22eb9722006-06-18 05:43:12 +00001356 // Invalid macro name, read and discard the rest of the line. Then set the
1357 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001358 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001359 return DiscardUntilEndOfDirective();
1360}
1361
1362/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1363/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001364void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner146762e2007-07-20 16:59:19 +00001365 Token Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001366 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001367 // There should be no tokens after the directive, but we allow them as an
1368 // extension.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001369 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001370 Lex(Tmp);
1371
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001372 if (Tmp.isNot(tok::eom)) {
Chris Lattnercb283342006-06-18 06:48:37 +00001373 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1374 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001375 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001376}
1377
1378
1379
1380/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1381/// decided that the subsequent tokens are in the #if'd out portion of the
1382/// file. Lex the rest of the file, until we see an #endif. If
1383/// FoundNonSkipPortion is true, then we have already emitted code for part of
1384/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1385/// is true, then #else directives are ok, if not, then we have already seen one
1386/// so a #else directive is a duplicate. When this returns, the caller can lex
1387/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001388void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001389 bool FoundNonSkipPortion,
1390 bool FoundElse) {
1391 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001392 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001393 "Lexing a macro, not a file?");
1394
1395 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1396 FoundNonSkipPortion, FoundElse);
1397
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001398 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1399 // disabling warnings, etc.
1400 CurLexer->LexingRawMode = true;
Chris Lattner146762e2007-07-20 16:59:19 +00001401 Token Tok;
Chris Lattner22eb9722006-06-18 05:43:12 +00001402 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001403 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001404
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001405 // If this is the end of the buffer, we have an error.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001406 if (Tok.is(tok::eof)) {
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001407 // Emit errors for each unterminated conditional on the stack, including
1408 // the current one.
1409 while (!CurLexer->ConditionalStack.empty()) {
1410 Diag(CurLexer->ConditionalStack.back().IfLoc,
1411 diag::err_pp_unterminated_conditional);
1412 CurLexer->ConditionalStack.pop_back();
1413 }
1414
1415 // Just return and let the caller lex after this #include.
1416 break;
1417 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001418
1419 // If this token is not a preprocessor directive, just skip it.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001420 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
Chris Lattner22eb9722006-06-18 05:43:12 +00001421 continue;
1422
1423 // We just parsed a # character at the start of a line, so we're in
1424 // directive mode. Tell the lexer this so any newlines we see will be
1425 // converted into an EOM token (this terminates the macro).
1426 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001427 CurLexer->KeepCommentMode = false;
1428
Chris Lattner22eb9722006-06-18 05:43:12 +00001429
1430 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001431 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001432
1433 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1434 // something bogus), skip it.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001435 if (Tok.isNot(tok::identifier)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001436 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001437 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001438 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001439 continue;
1440 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001441
Chris Lattner22eb9722006-06-18 05:43:12 +00001442 // If the first letter isn't i or e, it isn't intesting to us. We know that
1443 // this is safe in the face of spelling differences, because there is no way
1444 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001445 // allows us to avoid looking up the identifier info for #define/#undef and
1446 // other common directives.
1447 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1448 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001449 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1450 FirstChar != 'i' && FirstChar != 'e') {
1451 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 }
1456
Chris Lattnere60165f2006-06-22 06:36:29 +00001457 // Get the identifier name without trigraphs or embedded newlines. Note
1458 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1459 // when skipping.
1460 // TODO: could do this with zero copies in the no-clean case by using
1461 // strncmp below.
1462 char Directive[20];
1463 unsigned IdLen;
1464 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1465 IdLen = Tok.getLength();
1466 memcpy(Directive, RawCharData, IdLen);
1467 Directive[IdLen] = 0;
1468 } else {
1469 std::string DirectiveStr = getSpelling(Tok);
1470 IdLen = DirectiveStr.size();
1471 if (IdLen >= 20) {
1472 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001473 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001474 CurLexer->KeepCommentMode = KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001475 continue;
1476 }
1477 memcpy(Directive, &DirectiveStr[0], IdLen);
1478 Directive[IdLen] = 0;
1479 }
1480
Chris Lattner22eb9722006-06-18 05:43:12 +00001481 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001482 if ((IdLen == 2) || // "if"
1483 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1484 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001485 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1486 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001487 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001488 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001489 /*foundnonskip*/false,
1490 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001491 }
1492 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001493 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001494 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001495 PPConditionalInfo CondInfo;
1496 CondInfo.WasSkipping = true; // Silence bogus warning.
1497 bool InCond = CurLexer->popConditionalLevel(CondInfo);
Chris Lattnercf6bc662006-11-05 07:59:08 +00001498 InCond = InCond; // Silence warning in no-asserts mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00001499 assert(!InCond && "Can't be skipping if not in a conditional!");
1500
1501 // If we popped the outermost skipping block, we're done skipping!
1502 if (!CondInfo.WasSkipping)
1503 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001504 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001505 // #else directive in a skipping conditional. If not in some other
1506 // skipping conditional, and if #else hasn't already been seen, enter it
1507 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001508 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001509 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1510
1511 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001512 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001513
1514 // Note that we've seen a #else in this conditional.
1515 CondInfo.FoundElse = true;
1516
1517 // If the conditional is at the top level, and the #if block wasn't
1518 // entered, enter the #else block now.
1519 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1520 CondInfo.FoundNonSkip = true;
1521 break;
1522 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001523 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001524 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1525
1526 bool ShouldEnter;
1527 // If this is in a skipping block or if we're already handled this #if
1528 // block, don't bother parsing the condition.
1529 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001530 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001531 ShouldEnter = false;
1532 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001533 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001534 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001535 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1536 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001537 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001538 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001539 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001540 }
1541
1542 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001543 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001544
1545 // If this condition is true, enter it!
1546 if (ShouldEnter) {
1547 CondInfo.FoundNonSkip = true;
1548 break;
1549 }
1550 }
1551 }
1552
1553 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001554 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001555 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001556 }
1557
1558 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1559 // of the file, just stop skipping and return to lexing whatever came after
1560 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001561 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001562}
1563
1564//===----------------------------------------------------------------------===//
1565// Preprocessor Directive Handling.
1566//===----------------------------------------------------------------------===//
1567
1568/// HandleDirective - This callback is invoked when the lexer sees a # token
1569/// at the start of a line. This consumes the directive, modifies the
1570/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1571/// read is the correct one.
Chris Lattner146762e2007-07-20 16:59:19 +00001572void Preprocessor::HandleDirective(Token &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001573 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001574
1575 // We just parsed a # character at the start of a line, so we're in directive
1576 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001577 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001578 CurLexer->ParsingPreprocessorDirective = true;
1579
1580 ++NumDirectives;
1581
Chris Lattner371ac8a2006-07-04 07:11:10 +00001582 // We are about to read a token. For the multiple-include optimization FA to
1583 // work, we have to remember if we had read any tokens *before* this
1584 // pp-directive.
1585 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1586
Chris Lattner78186052006-07-09 00:45:31 +00001587 // Read the next token, the directive flavor. This isn't expanded due to
1588 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001589 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001590
Chris Lattner78186052006-07-09 00:45:31 +00001591 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1592 // #define A(x) #x
1593 // A(abc
1594 // #warning blah
1595 // def)
1596 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001597 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001598 Diag(Result, diag::ext_embedded_directive);
1599
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001600TryAgain:
Chris Lattner22eb9722006-06-18 05:43:12 +00001601 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001602 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001603 return; // null directive.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001604 case tok::comment:
1605 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1606 LexUnexpandedToken(Result);
1607 goto TryAgain;
Chris Lattner22eb9722006-06-18 05:43:12 +00001608
Chris Lattner22eb9722006-06-18 05:43:12 +00001609 case tok::numeric_constant:
1610 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001611 DiscardUntilEndOfDirective();
1612 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001613 default:
1614 IdentifierInfo *II = Result.getIdentifierInfo();
1615 if (II == 0) break; // Not an identifier.
1616
1617 // Ask what the preprocessor keyword ID is.
1618 switch (II->getPPKeywordID()) {
1619 default: break;
1620 // C99 6.10.1 - Conditional Inclusion.
1621 case tok::pp_if:
1622 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1623 case tok::pp_ifdef:
1624 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1625 case tok::pp_ifndef:
1626 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1627 case tok::pp_elif:
1628 return HandleElifDirective(Result);
1629 case tok::pp_else:
1630 return HandleElseDirective(Result);
1631 case tok::pp_endif:
1632 return HandleEndifDirective(Result);
1633
1634 // C99 6.10.2 - Source File Inclusion.
1635 case tok::pp_include:
1636 return HandleIncludeDirective(Result); // Handle #include.
1637
1638 // C99 6.10.3 - Macro Replacement.
1639 case tok::pp_define:
1640 return HandleDefineDirective(Result, false);
1641 case tok::pp_undef:
1642 return HandleUndefDirective(Result);
1643
1644 // C99 6.10.4 - Line Control.
1645 case tok::pp_line:
1646 // FIXME: implement #line
1647 DiscardUntilEndOfDirective();
1648 return;
1649
1650 // C99 6.10.5 - Error Directive.
1651 case tok::pp_error:
1652 return HandleUserDiagnosticDirective(Result, false);
1653
1654 // C99 6.10.6 - Pragma Directive.
1655 case tok::pp_pragma:
1656 return HandlePragmaDirective();
1657
1658 // GNU Extensions.
1659 case tok::pp_import:
1660 return HandleImportDirective(Result);
1661 case tok::pp_include_next:
1662 return HandleIncludeNextDirective(Result);
1663
1664 case tok::pp_warning:
1665 Diag(Result, diag::ext_pp_warning_directive);
1666 return HandleUserDiagnosticDirective(Result, true);
1667 case tok::pp_ident:
1668 return HandleIdentSCCSDirective(Result);
1669 case tok::pp_sccs:
1670 return HandleIdentSCCSDirective(Result);
1671 case tok::pp_assert:
1672 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001673 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001674 case tok::pp_unassert:
1675 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001676 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001677
1678 // clang extensions.
1679 case tok::pp_define_target:
1680 return HandleDefineDirective(Result, true);
1681 case tok::pp_define_other_target:
1682 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001683 }
1684 break;
1685 }
1686
1687 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001688 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001689
1690 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001691 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001692
1693 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001694}
1695
Chris Lattner146762e2007-07-20 16:59:19 +00001696void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001697 bool isWarning) {
1698 // Read the rest of the line raw. We do this because we don't want macros
1699 // to be expanded and we don't require that the tokens be valid preprocessing
1700 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1701 // collapse multiple consequtive white space between tokens, but this isn't
1702 // specified by the standard.
1703 std::string Message = CurLexer->ReadToEndOfLine();
1704
1705 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001706 return Diag(Tok, DiagID, Message);
1707}
1708
1709/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1710///
Chris Lattner146762e2007-07-20 16:59:19 +00001711void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001712 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001713 Diag(Tok, diag::ext_pp_ident_directive);
1714
Chris Lattner371ac8a2006-07-04 07:11:10 +00001715 // Read the string argument.
Chris Lattner146762e2007-07-20 16:59:19 +00001716 Token StrTok;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001717 Lex(StrTok);
1718
1719 // If the token kind isn't a string, it's a malformed directive.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001720 if (StrTok.isNot(tok::string_literal) &&
1721 StrTok.isNot(tok::wide_string_literal))
Chris Lattner01d66cc2006-07-03 22:16:27 +00001722 return Diag(StrTok, diag::err_pp_malformed_ident);
1723
1724 // Verify that there is nothing after the string, other than EOM.
1725 CheckEndOfDirective("#ident");
1726
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001727 if (Callbacks)
1728 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001729}
1730
Chris Lattnerb8761832006-06-24 21:31:03 +00001731//===----------------------------------------------------------------------===//
1732// Preprocessor Include Directive Handling.
1733//===----------------------------------------------------------------------===//
1734
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001735/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1736/// checked and spelled filename, e.g. as an operand of #include. This returns
1737/// true if the input filename was in <>'s or false if it were in ""'s. The
1738/// caller is expected to provide a buffer that is large enough to hold the
1739/// spelling of the filename, but is also expected to handle the case when
1740/// this method decides to use a different buffer.
Chris Lattner93ab9f12007-07-23 04:15:27 +00001741bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001742 const char *&BufStart,
1743 const char *&BufEnd) {
1744 // Get the text form of the filename.
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001745 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1746
1747 // Make sure the filename is <x> or "x".
1748 bool isAngled;
1749 if (BufStart[0] == '<') {
1750 if (BufEnd[-1] != '>') {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001751 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001752 BufStart = 0;
1753 return true;
1754 }
1755 isAngled = true;
1756 } else if (BufStart[0] == '"') {
1757 if (BufEnd[-1] != '"') {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001758 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001759 BufStart = 0;
1760 return true;
1761 }
1762 isAngled = false;
1763 } else {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001764 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001765 BufStart = 0;
1766 return true;
1767 }
1768
1769 // Diagnose #include "" as invalid.
1770 if (BufEnd-BufStart <= 2) {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001771 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001772 BufStart = 0;
1773 return "";
1774 }
1775
1776 // Skip the brackets.
1777 ++BufStart;
1778 --BufEnd;
1779 return isAngled;
1780}
1781
Chris Lattner43eafb42007-07-23 04:56:47 +00001782/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1783/// from a macro as multiple tokens, which need to be glued together. This
1784/// occurs for code like:
1785/// #define FOO <a/b.h>
1786/// #include FOO
1787/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1788///
1789/// This code concatenates and consumes tokens up to the '>' token. It returns
1790/// false if the > was found, otherwise it returns true if it finds and consumes
1791/// the EOM marker.
1792static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
1793 Preprocessor &PP) {
1794 Token CurTok;
1795
1796 PP.Lex(CurTok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001797 while (CurTok.isNot(tok::eom)) {
Chris Lattner43eafb42007-07-23 04:56:47 +00001798 // Append the spelling of this token to the buffer. If there was a space
1799 // before it, add it now.
1800 if (CurTok.hasLeadingSpace())
1801 FilenameBuffer.push_back(' ');
1802
1803 // Get the spelling of the token, directly into FilenameBuffer if possible.
1804 unsigned PreAppendSize = FilenameBuffer.size();
1805 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
1806
1807 const char *BufPtr = &FilenameBuffer[PreAppendSize];
1808 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
1809
1810 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1811 if (BufPtr != &FilenameBuffer[PreAppendSize])
1812 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1813
1814 // Resize FilenameBuffer to the correct size.
1815 if (CurTok.getLength() != ActualLen)
1816 FilenameBuffer.resize(PreAppendSize+ActualLen);
1817
1818 // If we found the '>' marker, return success.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001819 if (CurTok.is(tok::greater))
Chris Lattner43eafb42007-07-23 04:56:47 +00001820 return false;
1821
1822 PP.Lex(CurTok);
1823 }
1824
1825 // If we hit the eom marker, emit an error and return true so that the caller
1826 // knows the EOM has been read.
1827 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
1828 return true;
1829}
1830
Chris Lattner22eb9722006-06-18 05:43:12 +00001831/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1832/// file to be included from the lexer, then include it! This is a common
1833/// routine with functionality shared between #include, #include_next and
1834/// #import.
Chris Lattner146762e2007-07-20 16:59:19 +00001835void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001836 const DirectoryLookup *LookupFrom,
1837 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001838
Chris Lattner146762e2007-07-20 16:59:19 +00001839 Token FilenameTok;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001840 CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001841
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001842 // Reserve a buffer to get the spelling.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001843 llvm::SmallVector<char, 128> FilenameBuffer;
Chris Lattner43eafb42007-07-23 04:56:47 +00001844 const char *FilenameStart, *FilenameEnd;
1845
1846 switch (FilenameTok.getKind()) {
1847 case tok::eom:
1848 // If the token kind is EOM, the error has already been diagnosed.
1849 return;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001850
Chris Lattner43eafb42007-07-23 04:56:47 +00001851 case tok::angle_string_literal:
Chris Lattnerf97dbcb2007-07-23 22:23:52 +00001852 case tok::string_literal: {
Chris Lattner43eafb42007-07-23 04:56:47 +00001853 FilenameBuffer.resize(FilenameTok.getLength());
1854 FilenameStart = &FilenameBuffer[0];
1855 unsigned Len = getSpelling(FilenameTok, FilenameStart);
1856 FilenameEnd = FilenameStart+Len;
1857 break;
Chris Lattnerf97dbcb2007-07-23 22:23:52 +00001858 }
Chris Lattner43eafb42007-07-23 04:56:47 +00001859
1860 case tok::less:
1861 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1862 // case, glue the tokens together into FilenameBuffer and interpret those.
1863 FilenameBuffer.push_back('<');
1864 if (ConcatenateIncludeName(FilenameBuffer, *this))
1865 return; // Found <eom> but no ">"? Diagnostic already emitted.
1866 FilenameStart = &FilenameBuffer[0];
1867 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
1868 break;
1869 default:
1870 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1871 DiscardUntilEndOfDirective();
1872 return;
1873 }
1874
Chris Lattner93ab9f12007-07-23 04:15:27 +00001875 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001876 FilenameStart, FilenameEnd);
1877 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1878 // error.
Chris Lattner43eafb42007-07-23 04:56:47 +00001879 if (FilenameStart == 0) {
1880 DiscardUntilEndOfDirective();
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001881 return;
Chris Lattner43eafb42007-07-23 04:56:47 +00001882 }
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001883
Chris Lattner269c2322006-06-25 06:23:00 +00001884 // Verify that there is nothing after the filename, other than EOM. Use the
1885 // preprocessor to lex this in case lexing the filename entered a macro.
1886 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001887
1888 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001889 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001890 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1891
Chris Lattner22eb9722006-06-18 05:43:12 +00001892 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001893 const DirectoryLookup *CurDir;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001894 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
Chris Lattnerb8b94f12006-10-30 05:38:06 +00001895 isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001896 if (File == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00001897 return Diag(FilenameTok, diag::err_pp_file_not_found,
1898 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00001899
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001900 // Ask HeaderInfo if we should enter this #include file.
1901 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1902 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00001903 return;
1904 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001905
1906 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001907 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001908 if (FileID == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00001909 return Diag(FilenameTok, diag::err_pp_file_not_found,
1910 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00001911
1912 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001913 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001914}
1915
1916/// HandleIncludeNextDirective - Implements #include_next.
1917///
Chris Lattner146762e2007-07-20 16:59:19 +00001918void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
Chris Lattnercb283342006-06-18 06:48:37 +00001919 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001920
1921 // #include_next is like #include, except that we start searching after
1922 // the current found directory. If we can't do this, issue a
1923 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001924 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001925 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001926 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001927 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001928 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001929 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001930 } else {
1931 // Start looking up in the next directory.
1932 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001933 }
1934
1935 return HandleIncludeDirective(IncludeNextTok, Lookup);
1936}
1937
1938/// HandleImportDirective - Implements #import.
1939///
Chris Lattner146762e2007-07-20 16:59:19 +00001940void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnercb283342006-06-18 06:48:37 +00001941 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001942
1943 return HandleIncludeDirective(ImportTok, 0, true);
1944}
1945
Chris Lattnerb8761832006-06-24 21:31:03 +00001946//===----------------------------------------------------------------------===//
1947// Preprocessor Macro Directive Handling.
1948//===----------------------------------------------------------------------===//
1949
Chris Lattnercefc7682006-07-08 08:28:12 +00001950/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1951/// definition has just been read. Lex the rest of the arguments and the
1952/// closing ), updating MI with what we learn. Return true if an error occurs
1953/// parsing the arg list.
1954bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner564f4782007-07-14 22:46:43 +00001955 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
1956
Chris Lattner146762e2007-07-20 16:59:19 +00001957 Token Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001958 while (1) {
1959 LexUnexpandedToken(Tok);
1960 switch (Tok.getKind()) {
1961 case tok::r_paren:
1962 // Found the end of the argument list.
Chris Lattner564f4782007-07-14 22:46:43 +00001963 if (Arguments.empty()) { // #define FOO()
1964 MI->setArgumentList(Arguments.begin(), Arguments.end());
1965 return false;
1966 }
Chris Lattnercefc7682006-07-08 08:28:12 +00001967 // Otherwise we have #define FOO(A,)
1968 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1969 return true;
1970 case tok::ellipsis: // #define X(... -> C99 varargs
1971 // Warn if use of C99 feature in non-C99 mode.
1972 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1973
1974 // Lex the token after the identifier.
1975 LexUnexpandedToken(Tok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001976 if (Tok.isNot(tok::r_paren)) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001977 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1978 return true;
1979 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001980 // Add the __VA_ARGS__ identifier as an argument.
Chris Lattner564f4782007-07-14 22:46:43 +00001981 Arguments.push_back(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001982 MI->setIsC99Varargs();
Chris Lattner564f4782007-07-14 22:46:43 +00001983 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001984 return false;
1985 case tok::eom: // #define X(
1986 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1987 return true;
Chris Lattner62aa0d42006-10-20 05:08:24 +00001988 default:
1989 // Handle keywords and identifiers here to accept things like
1990 // #define Foo(for) for.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001991 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner62aa0d42006-10-20 05:08:24 +00001992 if (II == 0) {
1993 // #define X(1
1994 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1995 return true;
1996 }
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001997
1998 // If this is already used as an argument, it is used multiple times (e.g.
1999 // #define X(A,A.
Chris Lattner564f4782007-07-14 22:46:43 +00002000 if (std::find(Arguments.begin(), Arguments.end(), II) !=
2001 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002002 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
2003 return true;
2004 }
2005
2006 // Add the argument to the macro info.
Chris Lattner564f4782007-07-14 22:46:43 +00002007 Arguments.push_back(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00002008
2009 // Lex the token after the identifier.
2010 LexUnexpandedToken(Tok);
2011
2012 switch (Tok.getKind()) {
2013 default: // #define X(A B
2014 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2015 return true;
2016 case tok::r_paren: // #define X(A)
Chris Lattner564f4782007-07-14 22:46:43 +00002017 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00002018 return false;
2019 case tok::comma: // #define X(A,
2020 break;
2021 case tok::ellipsis: // #define X(A... -> GCC extension
2022 // Diagnose extension.
2023 Diag(Tok, diag::ext_named_variadic_macro);
2024
2025 // Lex the token after the identifier.
2026 LexUnexpandedToken(Tok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002027 if (Tok.isNot(tok::r_paren)) {
Chris Lattnercefc7682006-07-08 08:28:12 +00002028 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2029 return true;
2030 }
2031
2032 MI->setIsGNUVarargs();
Chris Lattner564f4782007-07-14 22:46:43 +00002033 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00002034 return false;
2035 }
2036 }
2037 }
2038}
2039
Chris Lattner22eb9722006-06-18 05:43:12 +00002040/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00002041/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
2042/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00002043///
Chris Lattner146762e2007-07-20 16:59:19 +00002044void Preprocessor::HandleDefineDirective(Token &DefineTok,
Chris Lattner81278c62006-10-14 19:03:49 +00002045 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002046 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002047
Chris Lattner146762e2007-07-20 16:59:19 +00002048 Token MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00002049 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00002050
2051 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002052 if (MacroNameTok.is(tok::eom))
Chris Lattnercb283342006-06-18 06:48:37 +00002053 return;
Chris Lattnerf40fe992007-07-14 22:11:41 +00002054
Chris Lattner457fc152006-07-29 06:30:25 +00002055 // If we are supposed to keep comments in #defines, reenable comment saving
2056 // mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00002057 CurLexer->KeepCommentMode = KeepMacroComments;
Chris Lattner457fc152006-07-29 06:30:25 +00002058
Chris Lattner063400e2006-10-14 19:54:15 +00002059 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00002060 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00002061 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00002062
Chris Lattner063400e2006-10-14 19:54:15 +00002063 // If the identifier is an 'other target' macro, clear this bit.
2064 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2065
2066
Chris Lattner146762e2007-07-20 16:59:19 +00002067 Token Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00002068 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00002069
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002070 // If this is a function-like macro definition, parse the argument list,
2071 // marking each of the identifiers as being used as macro arguments. Also,
2072 // check other constraints on the first token of the macro body.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002073 if (Tok.is(tok::eom)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002074 // If there is no body to this macro, we have no special handling here.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002075 } else if (Tok.is(tok::l_paren) && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00002076 // This is a function-like macro definition. Read the argument list.
2077 MI->setIsFunctionLike();
2078 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002079 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00002080 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00002081 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00002082 if (CurLexer->ParsingPreprocessorDirective)
2083 DiscardUntilEndOfDirective();
2084 return;
2085 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002086
Chris Lattner815a1f92006-07-08 20:48:04 +00002087 // Read the first token after the arg list for down below.
2088 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00002089 } else if (!Tok.hasLeadingSpace()) {
2090 // C99 requires whitespace between the macro definition and the body. Emit
2091 // a diagnostic for something like "#define X+".
2092 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00002093 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00002094 } else {
2095 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
2096 // one in some cases!
2097 }
2098 } else {
2099 // This is a normal token with leading space. Clear the leading space
2100 // marker on the first token to get proper expansion.
Chris Lattner146762e2007-07-20 16:59:19 +00002101 Tok.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002102 }
2103
Chris Lattner7e374832006-07-29 03:46:57 +00002104 // If this is a definition of a variadic C99 function-like macro, not using
2105 // the GNU named varargs extension, enabled __VA_ARGS__.
2106
2107 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
2108 // This gets unpoisoned where it is allowed.
2109 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
2110 if (MI->isC99Varargs())
2111 Ident__VA_ARGS__->setIsPoisoned(false);
2112
Chris Lattner22eb9722006-06-18 05:43:12 +00002113 // Read the rest of the macro body.
Chris Lattnera3834342007-07-14 21:54:03 +00002114 if (MI->isObjectLike()) {
2115 // Object-like macros are very simple, just read their body.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002116 while (Tok.isNot(tok::eom)) {
Chris Lattnera3834342007-07-14 21:54:03 +00002117 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00002118 // Get the next token of the macro.
2119 LexUnexpandedToken(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00002120 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002121
Chris Lattnera3834342007-07-14 21:54:03 +00002122 } else {
2123 // Otherwise, read the body of a function-like macro. This has to validate
2124 // the # (stringize) operator.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002125 while (Tok.isNot(tok::eom)) {
Chris Lattnera3834342007-07-14 21:54:03 +00002126 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002127
Chris Lattnera3834342007-07-14 21:54:03 +00002128 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
2129 // parameters in function-like macro expansions.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002130 if (Tok.isNot(tok::hash)) {
Chris Lattnera3834342007-07-14 21:54:03 +00002131 // Get the next token of the macro.
2132 LexUnexpandedToken(Tok);
2133 continue;
2134 }
2135
2136 // Get the next token of the macro.
2137 LexUnexpandedToken(Tok);
2138
2139 // Not a macro arg identifier?
2140 if (!Tok.getIdentifierInfo() ||
2141 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2142 Diag(Tok, diag::err_pp_stringize_not_parameter);
2143 delete MI;
2144
2145 // Disable __VA_ARGS__ again.
2146 Ident__VA_ARGS__->setIsPoisoned(true);
2147 return;
2148 }
2149
2150 // Things look ok, add the param name token to the macro.
2151 MI->AddTokenToBody(Tok);
2152
2153 // Get the next token of the macro.
2154 LexUnexpandedToken(Tok);
2155 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002156 }
Chris Lattner7e374832006-07-29 03:46:57 +00002157
Chris Lattnerf40fe992007-07-14 22:11:41 +00002158
Chris Lattner7e374832006-07-29 03:46:57 +00002159 // Disable __VA_ARGS__ again.
2160 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002161
Chris Lattnerbff18d52006-07-06 04:49:18 +00002162 // Check that there is no paste (##) operator at the begining or end of the
2163 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00002164 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00002165 if (NumTokens != 0) {
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002166 if (MI->getReplacementToken(0).is(tok::hashhash)) {
Chris Lattner815a1f92006-07-08 20:48:04 +00002167 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002168 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00002169 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00002170 }
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002171 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
Chris Lattner815a1f92006-07-08 20:48:04 +00002172 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002173 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00002174 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00002175 }
2176 }
2177
Chris Lattner13044d92006-07-03 05:16:44 +00002178 // If this is the primary source file, remember that this macro hasn't been
2179 // used yet.
2180 if (isInPrimaryFile())
2181 MI->setIsUsed(false);
2182
Chris Lattner22eb9722006-06-18 05:43:12 +00002183 // Finally, if this identifier already had a macro defined for it, verify that
2184 // the macro bodies are identical and free the old definition.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002185 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner13044d92006-07-03 05:16:44 +00002186 if (!OtherMI->isUsed())
2187 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
2188
Chris Lattner22eb9722006-06-18 05:43:12 +00002189 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00002190 // must be the same. C99 6.10.3.2.
2191 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00002192 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
2193 MacroNameTok.getIdentifierInfo()->getName());
2194 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
2195 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002196 delete OtherMI;
2197 }
2198
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002199 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00002200}
2201
Chris Lattner063400e2006-10-14 19:54:15 +00002202/// HandleDefineOtherTargetDirective - Implements #define_other_target.
Chris Lattner146762e2007-07-20 16:59:19 +00002203void Preprocessor::HandleDefineOtherTargetDirective(Token &Tok) {
2204 Token MacroNameTok;
Chris Lattner063400e2006-10-14 19:54:15 +00002205 ReadMacroName(MacroNameTok, 1);
2206
2207 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002208 if (MacroNameTok.is(tok::eom))
Chris Lattner063400e2006-10-14 19:54:15 +00002209 return;
2210
2211 // Check to see if this is the last token on the #undef line.
2212 CheckEndOfDirective("#define_other_target");
2213
2214 // If there is already a macro defined by this name, turn it into a
2215 // target-specific define.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002216 if (MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner063400e2006-10-14 19:54:15 +00002217 MI->setIsTargetSpecific(true);
2218 return;
2219 }
2220
2221 // Mark the identifier as being a macro on some other target.
2222 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
2223}
2224
Chris Lattner22eb9722006-06-18 05:43:12 +00002225
2226/// HandleUndefDirective - Implements #undef.
2227///
Chris Lattner146762e2007-07-20 16:59:19 +00002228void Preprocessor::HandleUndefDirective(Token &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002229 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002230
Chris Lattner146762e2007-07-20 16:59:19 +00002231 Token MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00002232 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00002233
2234 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002235 if (MacroNameTok.is(tok::eom))
Chris Lattnercb283342006-06-18 06:48:37 +00002236 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002237
2238 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00002239 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00002240
2241 // Okay, we finally have a valid identifier to undef.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002242 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Chris Lattner22eb9722006-06-18 05:43:12 +00002243
Chris Lattner063400e2006-10-14 19:54:15 +00002244 // #undef untaints an identifier if it were marked by define_other_target.
2245 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2246
Chris Lattner22eb9722006-06-18 05:43:12 +00002247 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00002248 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00002249
Chris Lattner13044d92006-07-03 05:16:44 +00002250 if (!MI->isUsed())
2251 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00002252
2253 // Free macro definition.
2254 delete MI;
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002255 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
Chris Lattner22eb9722006-06-18 05:43:12 +00002256}
2257
2258
Chris Lattnerb8761832006-06-24 21:31:03 +00002259//===----------------------------------------------------------------------===//
2260// Preprocessor Conditional Directive Handling.
2261//===----------------------------------------------------------------------===//
2262
Chris Lattner22eb9722006-06-18 05:43:12 +00002263/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00002264/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
2265/// if any tokens have been returned or pp-directives activated before this
2266/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00002267///
Chris Lattner146762e2007-07-20 16:59:19 +00002268void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
Chris Lattner371ac8a2006-07-04 07:11:10 +00002269 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002270 ++NumIf;
Chris Lattner146762e2007-07-20 16:59:19 +00002271 Token DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002272
Chris Lattner146762e2007-07-20 16:59:19 +00002273 Token MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00002274 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00002275
2276 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002277 if (MacroNameTok.is(tok::eom)) {
Chris Lattnerd05e44e2007-09-24 05:14:57 +00002278 // Skip code until we get to #endif. This helps with recovery by not
2279 // emitting an error when the #endif is reached.
2280 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2281 /*Foundnonskip*/false, /*FoundElse*/false);
Chris Lattnercb283342006-06-18 06:48:37 +00002282 return;
Chris Lattnerd05e44e2007-09-24 05:14:57 +00002283 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002284
2285 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00002286 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
2287
2288 // If the start of a top-level #ifdef, inform MIOpt.
2289 if (!ReadAnyTokensBeforeDirective &&
2290 CurLexer->getConditionalStackDepth() == 0) {
2291 assert(isIfndef && "#ifdef shouldn't reach here");
2292 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
2293 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002294
Chris Lattner063400e2006-10-14 19:54:15 +00002295 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002296 MacroInfo *MI = getMacroInfo(MII);
Chris Lattnera78a97e2006-07-03 05:42:18 +00002297
Chris Lattner81278c62006-10-14 19:03:49 +00002298 // If there is a macro, process it.
2299 if (MI) {
2300 // Mark it used.
2301 MI->setIsUsed(true);
2302
2303 // If this is the first use of a target-specific macro, warn about it.
2304 if (MI->isTargetSpecific()) {
2305 MI->setIsTargetSpecific(false); // Don't warn on second use.
2306 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2307 diag::port_target_macro_use);
2308 }
Chris Lattner063400e2006-10-14 19:54:15 +00002309 } else {
2310 // Use of a target-specific macro for some other target? If so, warn.
2311 if (MII->isOtherTargetMacro()) {
2312 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
2313 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2314 diag::port_target_macro_use);
2315 }
Chris Lattner81278c62006-10-14 19:03:49 +00002316 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00002317
Chris Lattner22eb9722006-06-18 05:43:12 +00002318 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00002319 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002320 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002321 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002322 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002323 } else {
2324 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002325 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00002326 /*Foundnonskip*/false,
2327 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002328 }
2329}
2330
2331/// HandleIfDirective - Implements the #if directive.
2332///
Chris Lattner146762e2007-07-20 16:59:19 +00002333void Preprocessor::HandleIfDirective(Token &IfToken,
Chris Lattnera8654ca2006-07-04 17:42:08 +00002334 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002335 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002336
Chris Lattner371ac8a2006-07-04 07:11:10 +00002337 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00002338 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00002339 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00002340
2341 // Should we include the stuff contained by this directive?
2342 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00002343 // If this condition is equivalent to #ifndef X, and if this is the first
2344 // directive seen, handle it for the multiple-include optimization.
2345 if (!ReadAnyTokensBeforeDirective &&
2346 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2347 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2348
Chris Lattner22eb9722006-06-18 05:43:12 +00002349 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002350 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002351 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002352 } else {
2353 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002354 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00002355 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002356 }
2357}
2358
2359/// HandleEndifDirective - Implements the #endif directive.
2360///
Chris Lattner146762e2007-07-20 16:59:19 +00002361void Preprocessor::HandleEndifDirective(Token &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002362 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002363
Chris Lattner22eb9722006-06-18 05:43:12 +00002364 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00002365 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00002366
2367 PPConditionalInfo CondInfo;
2368 if (CurLexer->popConditionalLevel(CondInfo)) {
2369 // No conditionals on the stack: this is an #endif without an #if.
2370 return Diag(EndifToken, diag::err_pp_endif_without_if);
2371 }
2372
Chris Lattner371ac8a2006-07-04 07:11:10 +00002373 // If this the end of a top-level #endif, inform MIOpt.
2374 if (CurLexer->getConditionalStackDepth() == 0)
2375 CurLexer->MIOpt.ExitTopLevelConditional();
2376
Chris Lattner538d7f32006-07-20 04:31:52 +00002377 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00002378 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00002379}
2380
2381
Chris Lattner146762e2007-07-20 16:59:19 +00002382void Preprocessor::HandleElseDirective(Token &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002383 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002384
Chris Lattner22eb9722006-06-18 05:43:12 +00002385 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00002386 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00002387
2388 PPConditionalInfo CI;
2389 if (CurLexer->popConditionalLevel(CI))
2390 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00002391
2392 // If this is a top-level #else, inform the MIOpt.
2393 if (CurLexer->getConditionalStackDepth() == 0)
2394 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00002395
2396 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002397 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002398
2399 // Finally, skip the rest of the contents of this block and return the first
2400 // token after it.
2401 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2402 /*FoundElse*/true);
2403}
2404
Chris Lattner146762e2007-07-20 16:59:19 +00002405void Preprocessor::HandleElifDirective(Token &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002406 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002407
Chris Lattner22eb9722006-06-18 05:43:12 +00002408 // #elif directive in a non-skipping conditional... start skipping.
2409 // We don't care what the condition is, because we will always skip it (since
2410 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002411 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002412
2413 PPConditionalInfo CI;
2414 if (CurLexer->popConditionalLevel(CI))
2415 return Diag(ElifToken, diag::pp_err_elif_without_if);
2416
Chris Lattner371ac8a2006-07-04 07:11:10 +00002417 // If this is a top-level #elif, inform the MIOpt.
2418 if (CurLexer->getConditionalStackDepth() == 0)
2419 CurLexer->MIOpt.FoundTopLevelElse();
2420
Chris Lattner22eb9722006-06-18 05:43:12 +00002421 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002422 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002423
2424 // Finally, skip the rest of the contents of this block and return the first
2425 // token after it.
2426 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2427 /*FoundElse*/CI.FoundElse);
2428}
Chris Lattnerb8761832006-06-24 21:31:03 +00002429