blob: bfd270b168bcc626cc1e9e97fcdbcc636563bb39 [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"
29#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000030#include "clang/Lex/Pragma.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000031#include "clang/Lex/ScratchBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000032#include "clang/Basic/Diagnostic.h"
33#include "clang/Basic/FileManager.h"
34#include "clang/Basic/SourceManager.h"
Chris Lattner81278c62006-10-14 19:03:49 +000035#include "clang/Basic/TargetInfo.h"
Chris Lattner7a4af3b2006-07-26 06:26:52 +000036#include "llvm/ADT/SmallVector.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000037#include <iostream>
38using namespace llvm;
39using namespace clang;
40
41//===----------------------------------------------------------------------===//
42
Chris Lattner02dffbd2006-10-14 07:50:21 +000043Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
44 TargetInfo &target,
Chris Lattner22eb9722006-06-18 05:43:12 +000045 FileManager &FM, SourceManager &SM)
Chris Lattner02dffbd2006-10-14 07:50:21 +000046 : Diags(diags), Features(opts), Target(target), FileMgr(FM), SourceMgr(SM),
Chris Lattner22eb9722006-06-18 05:43:12 +000047 SystemDirIdx(0), NoCurDirSearch(false),
Chris Lattnerc8997182006-06-22 05:52:16 +000048 CurLexer(0), CurDirLookup(0), CurMacroExpander(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000049 ScratchBuf = new ScratchBuffer(SourceMgr);
50
Chris Lattner22eb9722006-06-18 05:43:12 +000051 // Clear stats.
52 NumDirectives = NumIncluded = NumDefined = NumUndefined = NumPragma = 0;
53 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000054 NumEnteredSourceFiles = 0;
55 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
Chris Lattner510ab612006-07-20 04:47:30 +000056 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Chris Lattner3665f162006-07-04 07:26:10 +000057 MaxIncludeStackDepth = 0; NumMultiIncludeFileOptzn = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000058 NumSkipped = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000059
Chris Lattner22eb9722006-06-18 05:43:12 +000060 // Macro expansion is enabled.
61 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000062 InMacroArgs = false;
Chris Lattner0c885f52006-06-21 06:50:18 +000063
64 // There is no file-change handler yet.
65 FileChangeHandler = 0;
Chris Lattner01d66cc2006-07-03 22:16:27 +000066 IdentHandler = 0;
Chris Lattnerb8761832006-06-24 21:31:03 +000067
Chris Lattner8ff71992006-07-06 05:17:39 +000068 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
69 // This gets unpoisoned where it is allowed.
70 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
71
Chris Lattnerb8761832006-06-24 21:31:03 +000072 // Initialize the pragma handlers.
73 PragmaHandlers = new PragmaNamespace(0);
74 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000075
76 // Initialize builtin macros like __LINE__ and friends.
77 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000078}
79
80Preprocessor::~Preprocessor() {
81 // Free any active lexers.
82 delete CurLexer;
83
Chris Lattner69772b02006-07-02 20:34:39 +000084 while (!IncludeMacroStack.empty()) {
85 delete IncludeMacroStack.back().TheLexer;
86 delete IncludeMacroStack.back().TheMacroExpander;
87 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000088 }
Chris Lattnerb8761832006-06-24 21:31:03 +000089
90 // Release pragma information.
91 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +000092
93 // Delete the scratch buffer info.
94 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +000095}
96
97/// getFileInfo - Return the PerFileInfo structure for the specified
98/// FileEntry.
99Preprocessor::PerFileInfo &Preprocessor::getFileInfo(const FileEntry *FE) {
100 if (FE->getUID() >= FileInfo.size())
101 FileInfo.resize(FE->getUID()+1);
102 return FileInfo[FE->getUID()];
103}
104
105
106/// AddKeywords - Add all keywords to the symbol table.
107///
108void Preprocessor::AddKeywords() {
109 enum {
110 C90Shift = 0,
111 EXTC90 = 1 << C90Shift,
112 NOTC90 = 2 << C90Shift,
113 C99Shift = 2,
114 EXTC99 = 1 << C99Shift,
115 NOTC99 = 2 << C99Shift,
116 CPPShift = 4,
117 EXTCPP = 1 << CPPShift,
118 NOTCPP = 2 << CPPShift,
119 Mask = 3
120 };
121
122 // Add keywords and tokens for the current language.
123#define KEYWORD(NAME, FLAGS) \
Chris Lattner02f1f4f2006-07-29 03:52:46 +0000124 AddKeyword(#NAME, tok::kw_ ## NAME, \
Chris Lattner6d998552006-08-04 06:11:48 +0000125 ((FLAGS) >> C90Shift) & Mask, \
126 ((FLAGS) >> C99Shift) & Mask, \
127 ((FLAGS) >> CPPShift) & Mask);
Chris Lattner22eb9722006-06-18 05:43:12 +0000128#define ALIAS(NAME, TOK) \
129 AddKeyword(NAME, tok::kw_ ## TOK, 0, 0, 0);
130#include "clang/Basic/TokenKinds.def"
131}
132
133/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
134/// the specified LexerToken's location, translating the token's start
135/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000136void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000137 const std::string &Msg) {
Chris Lattnercb283342006-06-18 06:48:37 +0000138 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000139}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000140
141void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
142 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
143 << getSpelling(Tok) << "'";
144
145 if (!DumpFlags) return;
146 std::cerr << "\t";
147 if (Tok.isAtStartOfLine())
148 std::cerr << " [StartOfLine]";
149 if (Tok.hasLeadingSpace())
150 std::cerr << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000151 if (Tok.isExpandDisabled())
152 std::cerr << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000153 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000154 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000155 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
156 << "']";
157 }
158}
159
160void Preprocessor::DumpMacro(const MacroInfo &MI) const {
161 std::cerr << "MACRO: ";
162 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
163 DumpToken(MI.getReplacementToken(i));
164 std::cerr << " ";
165 }
166 std::cerr << "\n";
167}
168
Chris Lattner22eb9722006-06-18 05:43:12 +0000169void Preprocessor::PrintStats() {
170 std::cerr << "\n*** Preprocessor Stats:\n";
171 std::cerr << FileInfo.size() << " files tracked.\n";
172 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
173 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
174 NumOnceOnlyFiles += FileInfo[i].isImport;
175 if (MaxNumIncludes < FileInfo[i].NumIncludes)
176 MaxNumIncludes = FileInfo[i].NumIncludes;
177 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
178 }
179 std::cerr << " " << NumOnceOnlyFiles << " #import/#pragma once files.\n";
180 std::cerr << " " << NumSingleIncludedFiles << " included exactly once.\n";
181 std::cerr << " " << MaxNumIncludes << " max times a file is included.\n";
182
183 std::cerr << NumDirectives << " directives found:\n";
184 std::cerr << " " << NumDefined << " #define.\n";
185 std::cerr << " " << NumUndefined << " #undef.\n";
186 std::cerr << " " << NumIncluded << " #include/#include_next/#import.\n";
Chris Lattner3665f162006-07-04 07:26:10 +0000187 std::cerr << " " << NumMultiIncludeFileOptzn << " #includes skipped due to"
188 << " the multi-include optimization.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000189 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
190 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
191 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
192 std::cerr << " " << NumElse << " #else/#elif.\n";
193 std::cerr << " " << NumEndif << " #endif.\n";
194 std::cerr << " " << NumPragma << " #pragma.\n";
195 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
196
Chris Lattner78186052006-07-09 00:45:31 +0000197 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
198 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
Chris Lattner22eb9722006-06-18 05:43:12 +0000199 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner510ab612006-07-20 04:47:30 +0000200 std::cerr << (NumFastTokenPaste+NumTokenPaste)
201 << " token paste (##) operations performed, "
202 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000203}
204
205//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000206// Token Spelling
207//===----------------------------------------------------------------------===//
208
209
210/// getSpelling() - Return the 'spelling' of this token. The spelling of a
211/// token are the characters used to represent the token in the source file
212/// after trigraph expansion and escaped-newline folding. In particular, this
213/// wants to get the true, uncanonicalized, spelling of things like digraphs
214/// UCNs, etc.
215std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
216 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
217
218 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000219 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000220 if (!Tok.needsCleaning())
221 return std::string(TokStart, TokStart+Tok.getLength());
222
Chris Lattnerd01e2912006-06-18 16:22:51 +0000223 std::string Result;
224 Result.reserve(Tok.getLength());
225
Chris Lattneref9eae12006-07-04 22:33:12 +0000226 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000227 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
228 Ptr != End; ) {
229 unsigned CharSize;
230 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
231 Ptr += CharSize;
232 }
233 assert(Result.size() != unsigned(Tok.getLength()) &&
234 "NeedsCleaning flag set on something that didn't need cleaning!");
235 return Result;
236}
237
238/// getSpelling - This method is used to get the spelling of a token into a
239/// preallocated buffer, instead of as an std::string. The caller is required
240/// to allocate enough space for the token, which is guaranteed to be at least
241/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000242///
243/// Note that this method may do two possible things: it may either fill in
244/// the buffer specified with characters, or it may *change the input pointer*
245/// to point to a constant buffer with the data already in it (avoiding a
246/// copy). The caller is not allowed to modify the returned buffer pointer
247/// if an internal buffer is returned.
248unsigned Preprocessor::getSpelling(const LexerToken &Tok,
249 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000250 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
251
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000252 // If this token is an identifier, just return the string from the identifier
253 // table, which is very quick.
254 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
255 Buffer = II->getName();
256 return Tok.getLength();
257 }
258
259 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000260 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000261
262 // If this token contains nothing interesting, return it directly.
263 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000264 Buffer = TokStart;
265 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000266 }
267 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000268 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000269 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
270 Ptr != End; ) {
271 unsigned CharSize;
272 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
273 Ptr += CharSize;
274 }
275 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
276 "NeedsCleaning flag set on something that didn't need cleaning!");
277
278 return OutBuf-Buffer;
279}
280
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000281
282/// CreateString - Plop the specified string into a scratch buffer and return a
283/// location for it. If specified, the source location provides a source
284/// location for the token.
285SourceLocation Preprocessor::
286CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
287 if (SLoc.isValid())
288 return ScratchBuf->getToken(Buf, Len, SLoc);
289 return ScratchBuf->getToken(Buf, Len);
290}
291
292
Chris Lattnerd01e2912006-06-18 16:22:51 +0000293//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000294// Source File Location Methods.
295//===----------------------------------------------------------------------===//
296
297
298/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
299/// return null on failure. isAngled indicates whether the file reference is
300/// for system #include's or not (i.e. using <> instead of "").
301const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
Chris Lattnerc8997182006-06-22 05:52:16 +0000302 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000303 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000304 const DirectoryLookup *&CurDir) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000305 assert(CurLexer && "Cannot enter a #include inside a macro expansion!");
Chris Lattnerc8997182006-06-22 05:52:16 +0000306 CurDir = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000307
308 // If 'Filename' is absolute, check to see if it exists and no searching.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000309 // FIXME: Portability. This should be a sys::Path interface, this doesn't
310 // handle things like C:\foo.txt right, nor win32 \\network\device\blah.
Chris Lattner22eb9722006-06-18 05:43:12 +0000311 if (Filename[0] == '/') {
312 // If this was an #include_next "/absolute/file", fail.
313 if (FromDir) return 0;
314
315 // Otherwise, just return the file.
316 return FileMgr.getFile(Filename);
317 }
318
319 // Step #0, unless disabled, check to see if the file is in the #includer's
320 // directory. This search is not done for <> headers.
Chris Lattnerc8997182006-06-22 05:52:16 +0000321 if (!isAngled && !FromDir && !NoCurDirSearch) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000322 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
323 const FileEntry *CurFE = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000324 if (CurFE) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000325 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000326 // FIXME: Portability. Should be in sys::Path.
Chris Lattner22eb9722006-06-18 05:43:12 +0000327 if (const FileEntry *FE =
328 FileMgr.getFile(CurFE->getDir()->getName()+"/"+Filename)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000329 if (CurDirLookup)
330 CurDir = CurDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +0000331 else
Chris Lattnerc8997182006-06-22 05:52:16 +0000332 CurDir = 0;
333
334 // This file is a system header or C++ unfriendly if the old file is.
335 getFileInfo(FE).DirInfo = getFileInfo(CurFE).DirInfo;
Chris Lattner22eb9722006-06-18 05:43:12 +0000336 return FE;
337 }
338 }
339 }
340
341 // If this is a system #include, ignore the user #include locs.
Chris Lattnerc8997182006-06-22 05:52:16 +0000342 unsigned i = isAngled ? SystemDirIdx : 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000343
344 // If this is a #include_next request, start searching after the directory the
345 // file was found in.
346 if (FromDir)
347 i = FromDir-&SearchDirs[0];
348
349 // Check each directory in sequence to see if it contains this file.
350 for (; i != SearchDirs.size(); ++i) {
351 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000352 // FIXME: Portability. Adding file to dir should be in sys::Path.
353 std::string SearchDir = SearchDirs[i].getDir()->getName()+"/"+Filename;
354 if (const FileEntry *FE = FileMgr.getFile(SearchDir)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000355 CurDir = &SearchDirs[i];
356
357 // This file is a system header or C++ unfriendly if the dir is.
358 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
Chris Lattner22eb9722006-06-18 05:43:12 +0000359 return FE;
360 }
361 }
362
363 // Otherwise, didn't find it.
364 return 0;
365}
366
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000367/// isInPrimaryFile - Return true if we're in the top-level file, not in a
368/// #include.
369bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000370 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000371 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000372
Chris Lattner13044d92006-07-03 05:16:44 +0000373 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000374 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000375 if (IncludeMacroStack[i].TheLexer &&
376 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
377 return IncludeMacroStack[i].TheLexer->isMainFile();
378 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000379}
380
381/// getCurrentLexer - Return the current file lexer being lexed from. Note
382/// that this ignores any potentially active macro expansions and _Pragma
383/// expansions going on at the time.
384Lexer *Preprocessor::getCurrentFileLexer() const {
385 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
386
387 // Look for a stacked lexer.
388 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000389 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000390 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
391 return L;
392 }
393 return 0;
394}
395
396
Chris Lattner22eb9722006-06-18 05:43:12 +0000397/// EnterSourceFile - Add a source file to the top of the include stack and
398/// start lexing tokens from it instead of the current buffer. Return true
399/// on failure.
400void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000401 const DirectoryLookup *CurDir,
402 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000403 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000404 ++NumEnteredSourceFiles;
405
Chris Lattner69772b02006-07-02 20:34:39 +0000406 if (MaxIncludeStackDepth < IncludeMacroStack.size())
407 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000408
Chris Lattner22eb9722006-06-18 05:43:12 +0000409 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000410 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000411 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000412 EnterSourceFileWithLexer(TheLexer, CurDir);
413}
Chris Lattner22eb9722006-06-18 05:43:12 +0000414
Chris Lattner69772b02006-07-02 20:34:39 +0000415/// EnterSourceFile - Add a source file to the top of the include stack and
416/// start lexing tokens from it instead of the current buffer.
417void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
418 const DirectoryLookup *CurDir) {
419
420 // Add the current lexer to the include stack.
421 if (CurLexer || CurMacroExpander)
422 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
423 CurMacroExpander));
424
425 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000426 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000427 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000428
429 // Notify the client, if desired, that we are in a new source file.
Chris Lattner98a53122006-07-02 23:00:20 +0000430 if (FileChangeHandler && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000431 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
432
433 // Get the file entry for the current file.
434 if (const FileEntry *FE =
435 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
436 FileType = getFileInfo(FE).DirInfo;
437
Chris Lattner1840e492006-07-02 22:30:01 +0000438 FileChangeHandler(SourceLocation(CurLexer->getCurFileID(), 0),
Chris Lattner55a60952006-06-25 04:20:34 +0000439 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000440 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000441}
442
Chris Lattner69772b02006-07-02 20:34:39 +0000443
444
Chris Lattner22eb9722006-06-18 05:43:12 +0000445/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000446/// tokens from it instead of the current buffer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000447void Preprocessor::EnterMacro(LexerToken &Tok, MacroArgs *Args) {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000448 IdentifierInfo *Identifier = Tok.getIdentifierInfo();
Chris Lattner69772b02006-07-02 20:34:39 +0000449 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
450 CurMacroExpander));
451 CurLexer = 0;
452 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000453
Chris Lattneree8760b2006-07-15 07:42:55 +0000454 CurMacroExpander = new MacroExpander(Tok, Args, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000455}
456
Chris Lattner7667d0d2006-07-16 18:16:58 +0000457/// EnterTokenStream - Add a "macro" context to the top of the include stack,
458/// which will cause the lexer to start returning the specified tokens. Note
459/// that these tokens will be re-macro-expanded when/if expansion is enabled.
460/// This method assumes that the specified stream of tokens has a permanent
461/// owner somewhere, so they do not need to be copied.
Chris Lattner70216572006-07-26 03:50:40 +0000462void Preprocessor::EnterTokenStream(const LexerToken *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000463 // Save our current state.
464 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
465 CurMacroExpander));
466 CurLexer = 0;
467 CurDirLookup = 0;
468
469 // Create a macro expander to expand from the specified token stream.
Chris Lattner70216572006-07-26 03:50:40 +0000470 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000471}
472
473/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
474/// lexer stack. This should only be used in situations where the current
475/// state of the top-of-stack lexer is known.
476void Preprocessor::RemoveTopOfLexerStack() {
477 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
478 delete CurLexer;
479 delete CurMacroExpander;
480 CurLexer = IncludeMacroStack.back().TheLexer;
481 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
482 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
483 IncludeMacroStack.pop_back();
484}
485
Chris Lattner22eb9722006-06-18 05:43:12 +0000486//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000487// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000488//===----------------------------------------------------------------------===//
489
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000490/// RegisterBuiltinMacro - Register the specified identifier in the identifier
491/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000492IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000493 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000494 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000495
496 // Mark it as being a macro that is builtin.
497 MacroInfo *MI = new MacroInfo(SourceLocation());
498 MI->setIsBuiltinMacro();
499 Id->setMacroInfo(MI);
500 return Id;
501}
502
503
Chris Lattner677757a2006-06-28 05:26:32 +0000504/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
505/// identifier table.
506void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000507 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000508 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000509 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
510 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000511 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000512
513 // GCC Extensions.
514 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
515 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000516 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000517}
518
Chris Lattnerc2395832006-07-09 00:57:04 +0000519/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
520/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000521static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
522 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000523 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
524
525 // If the token isn't an identifier, it's always literally expanded.
526 if (II == 0) return true;
527
528 // If the identifier is a macro, and if that macro is enabled, it may be
529 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000530 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
531 // Fast expanding "#define X X" is ok, because X would be disabled.
532 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000533 return false;
534
535 // If this is an object-like macro invocation, it is safe to trivially expand
536 // it.
537 if (MI->isObjectLike()) return true;
538
539 // If this is a function-like macro invocation, it's safe to trivially expand
540 // as long as the identifier is not a macro argument.
541 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
542 I != E; ++I)
543 if (*I == II)
544 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000545
Chris Lattnerc2395832006-07-09 00:57:04 +0000546 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000547}
548
Chris Lattnerc2395832006-07-09 00:57:04 +0000549
Chris Lattnerafe603f2006-07-11 04:02:46 +0000550/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
551/// lexed is a '('. If so, consume the token and return true, if not, this
552/// method should have no observable side-effect on the lexed tokens.
553bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000554 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000555 unsigned Val;
556 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000557 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000558 else
559 Val = CurMacroExpander->isNextTokenLParen();
560
561 if (Val == 2) {
562 // If we ran off the end of the lexer or macro expander, walk the include
563 // stack, looking for whatever will return the next token.
564 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
565 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
566 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000567 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000568 else
569 Val = Entry.TheMacroExpander->isNextTokenLParen();
570 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000571 }
572
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000573 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
574 // have found something that isn't a '(' or we found the end of the
575 // translation unit. In either case, return false.
576 if (Val != 1)
577 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000578
579 LexerToken Tok;
580 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000581 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
582 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000583}
Chris Lattner677757a2006-06-28 05:26:32 +0000584
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000585/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
586/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000587bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000588 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000589
590 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
591 if (MI->isBuiltinMacro()) {
592 ExpandBuiltinMacro(Identifier);
593 return false;
594 }
595
Chris Lattner81278c62006-10-14 19:03:49 +0000596 // If this is the first use of a target-specific macro, warn about it.
597 if (MI->isTargetSpecific()) {
598 MI->setIsTargetSpecific(false); // Don't warn on second use.
599 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
600 diag::port_target_macro_use);
601 }
602
Chris Lattneree8760b2006-07-15 07:42:55 +0000603 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000604 /// for each macro argument, the list of tokens that were provided to the
605 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000606 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000607
608 // If this is a function-like macro, read the arguments.
609 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000610 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
611 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000612 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000613 return true;
614
Chris Lattner78186052006-07-09 00:45:31 +0000615 // Remember that we are now parsing the arguments to a macro invocation.
616 // Preprocessor directives used inside macro arguments are not portable, and
617 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000618 InMacroArgs = true;
619 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000620
621 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000622 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000623
624 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000625 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000626
627 ++NumFnMacroExpanded;
628 } else {
629 ++NumMacroExpanded;
630 }
Chris Lattner13044d92006-07-03 05:16:44 +0000631
632 // Notice that this macro has been used.
633 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000634
635 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000636
637 // If this macro expands to no tokens, don't bother to push it onto the
638 // expansion stack, only to take it right back off.
639 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000640 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000641 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000642
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000643 // Ignore this macro use, just return the next token in the current
644 // buffer.
645 bool HadLeadingSpace = Identifier.hasLeadingSpace();
646 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
647
648 Lex(Identifier);
649
650 // If the identifier isn't on some OTHER line, inherit the leading
651 // whitespace/first-on-a-line property of this token. This handles
652 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
653 // empty.
654 if (!Identifier.isAtStartOfLine()) {
Chris Lattner8c204872006-10-14 05:19:21 +0000655 if (IsAtStartOfLine) Identifier.setFlag(LexerToken::StartOfLine);
656 if (HadLeadingSpace) Identifier.setFlag(LexerToken::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000657 }
658 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000659 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000660
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000661 } else if (MI->getNumTokens() == 1 &&
662 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000663 // Otherwise, if this macro expands into a single trivially-expanded
664 // token: expand it now. This handles common cases like
665 // "#define VAL 42".
666
667 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
668 // identifier to the expanded token.
669 bool isAtStartOfLine = Identifier.isAtStartOfLine();
670 bool hasLeadingSpace = Identifier.hasLeadingSpace();
671
672 // Remember where the token is instantiated.
673 SourceLocation InstantiateLoc = Identifier.getLocation();
674
675 // Replace the result token.
676 Identifier = MI->getReplacementToken(0);
677
678 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner8c204872006-10-14 05:19:21 +0000679 Identifier.setFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
680 Identifier.setFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000681
682 // Update the tokens location to include both its logical and physical
683 // locations.
684 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000685 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000686 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000687
Chris Lattner6e4bf522006-07-27 06:59:25 +0000688 // If this is #define X X, we must mark the result as unexpandible.
689 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
690 if (NewII->getMacroInfo() == MI)
Chris Lattner8c204872006-10-14 05:19:21 +0000691 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000692
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000693 // Since this is not an identifier token, it can't be macro expanded, so
694 // we're done.
695 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000696 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000697 }
698
Chris Lattner78186052006-07-09 00:45:31 +0000699 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000700 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000701
702 // Now that the macro is at the top of the include stack, ask the
703 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000704 Lex(Identifier);
705 return false;
706}
707
Chris Lattneree8760b2006-07-15 07:42:55 +0000708/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000709/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000710/// invocation. This returns null on error.
Chris Lattneree8760b2006-07-15 07:42:55 +0000711MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(LexerToken &MacroName,
712 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000713 // The number of fixed arguments to parse.
714 unsigned NumFixedArgsLeft = MI->getNumArgs();
715 bool isVariadic = MI->isVariadic();
716
Chris Lattner78186052006-07-09 00:45:31 +0000717 // Outer loop, while there are more arguments, keep reading them.
718 LexerToken Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000719 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000720 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000721
722 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000723 // argument is separated by an EOF token. Use a SmallVector so we can avoid
724 // heap allocations in the common case.
725 SmallVector<LexerToken, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000726
727 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000728 while (Tok.getKind() == tok::comma) {
Chris Lattner78186052006-07-09 00:45:31 +0000729 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
730 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000731
Chris Lattner78186052006-07-09 00:45:31 +0000732 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000733 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
734 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000735 LexUnexpandedToken(Tok);
736
737 if (Tok.getKind() == tok::eof) {
738 Diag(MacroName, diag::err_unterm_macro_invoc);
739 // Do not lose the EOF. Return it to the client.
740 MacroName = Tok;
741 return 0;
742 } else if (Tok.getKind() == tok::r_paren) {
743 // If we found the ) token, the macro arg list is done.
744 if (NumParens-- == 0)
745 break;
746 } else if (Tok.getKind() == tok::l_paren) {
747 ++NumParens;
748 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
749 // Comma ends this argument if there are more fixed arguments expected.
750 if (NumFixedArgsLeft)
751 break;
752
Chris Lattner2ada5d32006-07-15 07:51:24 +0000753 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000754 if (!isVariadic) {
755 // Emit the diagnostic at the macro name in case there is a missing ).
756 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000757 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000758 return 0;
759 }
760 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattner457fc152006-07-29 06:30:25 +0000761 } else if (Tok.getKind() == tok::comment && !Features.KeepMacroComments) {
762 // If this is a comment token in the argument list and we're just in
763 // -C mode (not -CC mode), discard the comment.
764 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000765 }
766
767 ArgTokens.push_back(Tok);
768 }
769
Chris Lattnera12dd152006-07-11 04:09:02 +0000770 // Empty arguments are standard in C99 and supported as an extension in
771 // other modes.
772 if (ArgTokens.empty() && !Features.C99)
773 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000774
Chris Lattner36b6e812006-07-21 06:38:30 +0000775 // Add a marker EOF token to the end of the token list for this argument.
776 LexerToken EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +0000777 EOFTok.startToken();
778 EOFTok.setKind(tok::eof);
779 EOFTok.setLocation(Tok.getLocation());
780 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +0000781 ArgTokens.push_back(EOFTok);
782 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000783 --NumFixedArgsLeft;
784 };
785
786 // Okay, we either found the r_paren. Check to see if we parsed too few
787 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000788 unsigned MinArgsExpected = MI->getNumArgs();
789
Chris Lattner775d8322006-07-29 04:39:41 +0000790 // See MacroArgs instance var for description of this.
791 bool isVarargsElided = false;
792
Chris Lattner2ada5d32006-07-15 07:51:24 +0000793 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000794 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000795 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000796 // Varargs where the named vararg parameter is missing: ok as extension.
797 // #define A(x, ...)
798 // A("blah")
799 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000800
801 // Remember this occurred if this is a C99 macro invocation with at least
802 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000803 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000804 } else if (MI->getNumArgs() == 1) {
805 // #define A(x)
806 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000807 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000808
809 // Empty arguments are standard in C99 and supported as an extension in
810 // other modes.
811 if (ArgTokens.empty() && !Features.C99)
812 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000813 } else {
814 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000815 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000816 return 0;
817 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000818
819 // Add a marker EOF token to the end of the token list for this argument.
820 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +0000821 Tok.startToken();
822 Tok.setKind(tok::eof);
823 Tok.setLocation(EndLoc);
824 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +0000825 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000826 }
827
Chris Lattner775d8322006-07-29 04:39:41 +0000828 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000829}
830
Chris Lattnerc673f902006-06-30 06:10:41 +0000831/// ComputeDATE_TIME - Compute the current time, enter it into the specified
832/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
833/// the identifier tokens inserted.
834static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000835 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000836 time_t TT = time(0);
837 struct tm *TM = localtime(&TT);
838
839 static const char * const Months[] = {
840 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
841 };
842
843 char TmpBuffer[100];
844 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
845 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000846 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000847
848 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000849 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000850}
851
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000852/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
853/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000854void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000855 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000856 IdentifierInfo *II = Tok.getIdentifierInfo();
857 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000858
859 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
860 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000861 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000862 return Handle_Pragma(Tok);
863
Chris Lattner78186052006-07-09 00:45:31 +0000864 ++NumBuiltinMacroExpanded;
865
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000866 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000867
868 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +0000869 Tok.setIdentifierInfo(0);
870 Tok.clearFlag(LexerToken::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +0000871
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000872 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000873 // __LINE__ expands to a simple numeric value.
874 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
875 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000876 Tok.setKind(tok::numeric_constant);
877 Tok.setLength(Length);
878 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000879 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000880 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000881 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000882 Diag(Tok, diag::ext_pp_base_file);
883 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
884 while (NextLoc.getFileID() != 0) {
885 Loc = NextLoc;
886 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
887 }
888 }
889
Chris Lattner0766e592006-07-03 01:07:01 +0000890 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
891 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000892 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +0000893 Tok.setKind(tok::string_literal);
894 Tok.setLength(FN.size());
895 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000896 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000897 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000898 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000899 Tok.setKind(tok::string_literal);
900 Tok.setLength(strlen("\"Mmm dd yyyy\""));
901 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000902 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000903 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000904 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000905 Tok.setKind(tok::string_literal);
906 Tok.setLength(strlen("\"hh:mm:ss\""));
907 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000908 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000909 Diag(Tok, diag::ext_pp_include_level);
910
911 // Compute the include depth of this token.
912 unsigned Depth = 0;
913 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
914 for (; Loc.getFileID() != 0; ++Depth)
915 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
916
917 // __INCLUDE_LEVEL__ expands to a simple numeric value.
918 sprintf(TmpBuffer, "%u", Depth);
919 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000920 Tok.setKind(tok::numeric_constant);
921 Tok.setLength(Length);
922 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000923 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000924 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
925 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
926 Diag(Tok, diag::ext_pp_timestamp);
927
928 // Get the file that we are lexing out of. If we're currently lexing from
929 // a macro, dig into the include stack.
930 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000931 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000932
933 if (TheLexer)
934 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
935
936 // If this file is older than the file it depends on, emit a diagnostic.
937 const char *Result;
938 if (CurFile) {
939 time_t TT = CurFile->getModificationTime();
940 struct tm *TM = localtime(&TT);
941 Result = asctime(TM);
942 } else {
943 Result = "??? ??? ?? ??:??:?? ????\n";
944 }
945 TmpBuffer[0] = '"';
946 strcpy(TmpBuffer+1, Result);
947 unsigned Len = strlen(TmpBuffer);
948 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +0000949 Tok.setKind(tok::string_literal);
950 Tok.setLength(Len);
951 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000952 } else {
953 assert(0 && "Unknown identifier!");
954 }
955}
Chris Lattner677757a2006-06-28 05:26:32 +0000956
Chris Lattner13044d92006-07-03 05:16:44 +0000957namespace {
958struct UnusedIdentifierReporter : public IdentifierVisitor {
959 Preprocessor &PP;
960 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
961
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000962 void VisitIdentifier(IdentifierInfo &II) const {
963 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
964 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +0000965 }
966};
967}
968
Chris Lattner677757a2006-06-28 05:26:32 +0000969//===----------------------------------------------------------------------===//
970// Lexer Event Handling.
971//===----------------------------------------------------------------------===//
972
Chris Lattnercefc7682006-07-08 08:28:12 +0000973/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
974/// identifier information for the token and install it into the token.
975IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
976 const char *BufPtr) {
977 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
978 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
979
980 // Look up this token, see if it is a macro, or if it is a language keyword.
981 IdentifierInfo *II;
982 if (BufPtr && !Identifier.needsCleaning()) {
983 // No cleaning needed, just use the characters from the lexed buffer.
984 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
985 } else {
986 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
987 const char *TmpBuf = (char*)alloca(Identifier.getLength());
988 unsigned Size = getSpelling(Identifier, TmpBuf);
989 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
990 }
Chris Lattner8c204872006-10-14 05:19:21 +0000991 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +0000992 return II;
993}
994
995
Chris Lattner677757a2006-06-28 05:26:32 +0000996/// HandleIdentifier - This callback is invoked when the lexer reads an
997/// identifier. This callback looks up the identifier in the map and/or
998/// potentially macro expands it or turns it into a named token (like 'for').
999void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +00001000 assert(Identifier.getIdentifierInfo() &&
1001 "Can't handle identifiers without identifier info!");
1002
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001003 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +00001004
1005 // If this identifier was poisoned, and if it was not produced from a macro
1006 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +00001007 if (II.isPoisoned() && CurLexer) {
1008 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
1009 Diag(Identifier, diag::err_pp_used_poisoned_id);
1010 else
1011 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
1012 }
Chris Lattner677757a2006-06-28 05:26:32 +00001013
Chris Lattner78186052006-07-09 00:45:31 +00001014 // If this is a macro to be expanded, do it.
Chris Lattner063400e2006-10-14 19:54:15 +00001015 if (MacroInfo *MI = II.getMacroInfo()) {
Chris Lattner6e4bf522006-07-27 06:59:25 +00001016 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
1017 if (MI->isEnabled()) {
1018 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1019 return;
1020 } else {
1021 // C99 6.10.3.4p2 says that a disabled macro may never again be
1022 // expanded, even if it's in a context where it could be expanded in the
1023 // future.
Chris Lattner8c204872006-10-14 05:19:21 +00001024 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +00001025 }
1026 }
Chris Lattner063400e2006-10-14 19:54:15 +00001027 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
1028 // If this identifier is a macro on some other target, emit a diagnostic.
1029 // This diagnosic is only emitted when macro expansion is enabled, because
1030 // the macro would not have been expanded for the other target either.
1031 II.setIsOtherTargetMacro(false); // Don't warn on second use.
1032 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
1033 diag::port_target_macro_use);
1034
1035 }
Chris Lattner677757a2006-06-28 05:26:32 +00001036
1037 // Change the kind of this identifier to the appropriate token kind, e.g.
1038 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +00001039 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +00001040
1041 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001042 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +00001043}
1044
Chris Lattner22eb9722006-06-18 05:43:12 +00001045/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1046/// the current file. This either returns the EOF token or pops a level off
1047/// the include stack and keeps going.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001048bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001049 assert(!CurMacroExpander &&
1050 "Ending a file when currently in a macro!");
1051
Chris Lattner371ac8a2006-07-04 07:11:10 +00001052 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001053 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001054 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001055 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001056 // Okay, this has a controlling macro, remember in PerFileInfo.
1057 if (const FileEntry *FE =
1058 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1059 getFileInfo(FE).ControllingMacro = ControllingMacro;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001060 }
1061 }
1062
Chris Lattner22eb9722006-06-18 05:43:12 +00001063 // If this is a #include'd file, pop it off the include stack and continue
1064 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001065 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001066 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001067 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001068
1069 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +00001070 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001071 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1072
1073 // Get the file entry for the current file.
1074 if (const FileEntry *FE =
1075 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1076 FileType = getFileInfo(FE).DirInfo;
1077
Chris Lattner0c885f52006-06-21 06:50:18 +00001078 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +00001079 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001080 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001081
1082 // Client should lex another token.
1083 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001084 }
1085
Chris Lattner8c204872006-10-14 05:19:21 +00001086 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +00001087 CurLexer->BufferPtr = CurLexer->BufferEnd;
1088 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +00001089 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001090
1091 // We're done with the #included file.
1092 delete CurLexer;
1093 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001094
Chris Lattner03f83482006-07-10 06:16:26 +00001095 // This is the end of the top-level file. If the diag::pp_macro_not_used
1096 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1097 // have not been used.
1098 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored)
1099 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner2183a6e2006-07-18 06:36:12 +00001100
1101 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001102}
1103
1104/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001105/// the current macro expansion or token stream expansion.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001106bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001107 assert(CurMacroExpander && !CurLexer &&
1108 "Ending a macro when currently in a #include file!");
1109
Chris Lattner22eb9722006-06-18 05:43:12 +00001110 delete CurMacroExpander;
1111
Chris Lattner69772b02006-07-02 20:34:39 +00001112 // Handle this like a #include file being popped off the stack.
1113 CurMacroExpander = 0;
1114 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001115}
1116
1117
1118//===----------------------------------------------------------------------===//
1119// Utility Methods for Preprocessor Directive Handling.
1120//===----------------------------------------------------------------------===//
1121
1122/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1123/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001124void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001125 LexerToken Tmp;
1126 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001127 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001128 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001129}
1130
1131/// ReadMacroName - Lex and validate a macro name, which occurs after a
1132/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001133/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1134/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001135/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001136void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001137 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001138 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001139
1140 // Missing macro name?
1141 if (MacroNameTok.getKind() == tok::eom)
1142 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1143
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001144 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1145 if (II == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001146 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001147 // Fall through on error.
1148 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001149 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +00001150
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001151 } else if (isDefineUndef && II->getName()[0] == 'd' && // defined
1152 !strcmp(II->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001153 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001154 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001155 } else if (isDefineUndef && II->getMacroInfo() &&
1156 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001157 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001158 if (isDefineUndef == 1)
1159 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1160 else
1161 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001162 } else {
1163 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001164 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001165 }
1166
Chris Lattner22eb9722006-06-18 05:43:12 +00001167 // Invalid macro name, read and discard the rest of the line. Then set the
1168 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001169 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001170 return DiscardUntilEndOfDirective();
1171}
1172
1173/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1174/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001175void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001176 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001177 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001178 // There should be no tokens after the directive, but we allow them as an
1179 // extension.
1180 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001181 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1182 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001183 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001184}
1185
1186
1187
1188/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1189/// decided that the subsequent tokens are in the #if'd out portion of the
1190/// file. Lex the rest of the file, until we see an #endif. If
1191/// FoundNonSkipPortion is true, then we have already emitted code for part of
1192/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1193/// is true, then #else directives are ok, if not, then we have already seen one
1194/// so a #else directive is a duplicate. When this returns, the caller can lex
1195/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001196void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001197 bool FoundNonSkipPortion,
1198 bool FoundElse) {
1199 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001200 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001201 "Lexing a macro, not a file?");
1202
1203 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1204 FoundNonSkipPortion, FoundElse);
1205
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001206 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1207 // disabling warnings, etc.
1208 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001209 LexerToken Tok;
1210 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001211 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001212
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001213 // If this is the end of the buffer, we have an error.
1214 if (Tok.getKind() == tok::eof) {
1215 // Emit errors for each unterminated conditional on the stack, including
1216 // the current one.
1217 while (!CurLexer->ConditionalStack.empty()) {
1218 Diag(CurLexer->ConditionalStack.back().IfLoc,
1219 diag::err_pp_unterminated_conditional);
1220 CurLexer->ConditionalStack.pop_back();
1221 }
1222
1223 // Just return and let the caller lex after this #include.
1224 break;
1225 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001226
1227 // If this token is not a preprocessor directive, just skip it.
1228 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1229 continue;
1230
1231 // We just parsed a # character at the start of a line, so we're in
1232 // directive mode. Tell the lexer this so any newlines we see will be
1233 // converted into an EOM token (this terminates the macro).
1234 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001235 CurLexer->KeepCommentMode = false;
1236
Chris Lattner22eb9722006-06-18 05:43:12 +00001237
1238 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001239 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001240
1241 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1242 // something bogus), skip it.
1243 if (Tok.getKind() != tok::identifier) {
1244 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001245 // Restore comment saving mode.
1246 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001247 continue;
1248 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001249
Chris Lattner22eb9722006-06-18 05:43:12 +00001250 // If the first letter isn't i or e, it isn't intesting to us. We know that
1251 // this is safe in the face of spelling differences, because there is no way
1252 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001253 // allows us to avoid looking up the identifier info for #define/#undef and
1254 // other common directives.
1255 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1256 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001257 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1258 FirstChar != 'i' && FirstChar != 'e') {
1259 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001260 // Restore comment saving mode.
1261 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001262 continue;
1263 }
1264
Chris Lattnere60165f2006-06-22 06:36:29 +00001265 // Get the identifier name without trigraphs or embedded newlines. Note
1266 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1267 // when skipping.
1268 // TODO: could do this with zero copies in the no-clean case by using
1269 // strncmp below.
1270 char Directive[20];
1271 unsigned IdLen;
1272 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1273 IdLen = Tok.getLength();
1274 memcpy(Directive, RawCharData, IdLen);
1275 Directive[IdLen] = 0;
1276 } else {
1277 std::string DirectiveStr = getSpelling(Tok);
1278 IdLen = DirectiveStr.size();
1279 if (IdLen >= 20) {
1280 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001281 // Restore comment saving mode.
1282 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001283 continue;
1284 }
1285 memcpy(Directive, &DirectiveStr[0], IdLen);
1286 Directive[IdLen] = 0;
1287 }
1288
Chris Lattner22eb9722006-06-18 05:43:12 +00001289 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001290 if ((IdLen == 2) || // "if"
1291 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1292 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001293 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1294 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001295 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001296 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001297 /*foundnonskip*/false,
1298 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001299 }
1300 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001301 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001302 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001303 PPConditionalInfo CondInfo;
1304 CondInfo.WasSkipping = true; // Silence bogus warning.
1305 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1306 assert(!InCond && "Can't be skipping if not in a conditional!");
1307
1308 // If we popped the outermost skipping block, we're done skipping!
1309 if (!CondInfo.WasSkipping)
1310 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001311 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001312 // #else directive in a skipping conditional. If not in some other
1313 // skipping conditional, and if #else hasn't already been seen, enter it
1314 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001315 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001316 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1317
1318 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001319 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001320
1321 // Note that we've seen a #else in this conditional.
1322 CondInfo.FoundElse = true;
1323
1324 // If the conditional is at the top level, and the #if block wasn't
1325 // entered, enter the #else block now.
1326 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1327 CondInfo.FoundNonSkip = true;
1328 break;
1329 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001330 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001331 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1332
1333 bool ShouldEnter;
1334 // If this is in a skipping block or if we're already handled this #if
1335 // block, don't bother parsing the condition.
1336 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001337 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001338 ShouldEnter = false;
1339 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001340 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001341 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001342 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1343 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001344 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001345 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001346 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001347 }
1348
1349 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001350 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001351
1352 // If this condition is true, enter it!
1353 if (ShouldEnter) {
1354 CondInfo.FoundNonSkip = true;
1355 break;
1356 }
1357 }
1358 }
1359
1360 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001361 // Restore comment saving mode.
1362 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001363 }
1364
1365 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1366 // of the file, just stop skipping and return to lexing whatever came after
1367 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001368 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001369}
1370
1371//===----------------------------------------------------------------------===//
1372// Preprocessor Directive Handling.
1373//===----------------------------------------------------------------------===//
1374
1375/// HandleDirective - This callback is invoked when the lexer sees a # token
1376/// at the start of a line. This consumes the directive, modifies the
1377/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1378/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001379void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001380 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001381
1382 // We just parsed a # character at the start of a line, so we're in directive
1383 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001384 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001385 CurLexer->ParsingPreprocessorDirective = true;
1386
1387 ++NumDirectives;
1388
Chris Lattner371ac8a2006-07-04 07:11:10 +00001389 // We are about to read a token. For the multiple-include optimization FA to
1390 // work, we have to remember if we had read any tokens *before* this
1391 // pp-directive.
1392 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1393
Chris Lattner78186052006-07-09 00:45:31 +00001394 // Read the next token, the directive flavor. This isn't expanded due to
1395 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001396 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001397
Chris Lattner78186052006-07-09 00:45:31 +00001398 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1399 // #define A(x) #x
1400 // A(abc
1401 // #warning blah
1402 // def)
1403 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001404 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001405 Diag(Result, diag::ext_embedded_directive);
1406
Chris Lattner22eb9722006-06-18 05:43:12 +00001407 switch (Result.getKind()) {
1408 default: break;
1409 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001410 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001411
Chris Lattner22eb9722006-06-18 05:43:12 +00001412 case tok::numeric_constant:
1413 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001414 DiscardUntilEndOfDirective();
1415 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001416 case tok::kw_else:
1417 return HandleElseDirective(Result);
1418 case tok::kw_if:
Chris Lattnera8654ca2006-07-04 17:42:08 +00001419 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
Chris Lattner22eb9722006-06-18 05:43:12 +00001420 case tok::identifier:
Chris Lattner40931922006-06-22 06:14:04 +00001421 // Get the identifier name without trigraphs or embedded newlines.
1422 const char *Directive = Result.getIdentifierInfo()->getName();
Chris Lattner22eb9722006-06-18 05:43:12 +00001423 bool isExtension = false;
Chris Lattner40931922006-06-22 06:14:04 +00001424 switch (Result.getIdentifierInfo()->getNameLength()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001425 case 4:
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001426 if (Directive[0] == 'l' && !strcmp(Directive, "line")) {
1427 // FIXME: implement #line
1428 DiscardUntilEndOfDirective();
1429 return;
1430 }
Chris Lattner40931922006-06-22 06:14:04 +00001431 if (Directive[0] == 'e' && !strcmp(Directive, "elif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001432 return HandleElifDirective(Result);
Chris Lattner01d66cc2006-07-03 22:16:27 +00001433 if (Directive[0] == 's' && !strcmp(Directive, "sccs"))
1434 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001435 break;
1436 case 5:
Chris Lattner40931922006-06-22 06:14:04 +00001437 if (Directive[0] == 'e' && !strcmp(Directive, "endif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001438 return HandleEndifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001439 if (Directive[0] == 'i' && !strcmp(Directive, "ifdef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001440 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
Chris Lattner40931922006-06-22 06:14:04 +00001441 if (Directive[0] == 'u' && !strcmp(Directive, "undef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001442 return HandleUndefDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001443 if (Directive[0] == 'e' && !strcmp(Directive, "error"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001444 return HandleUserDiagnosticDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001445 if (Directive[0] == 'i' && !strcmp(Directive, "ident"))
Chris Lattner01d66cc2006-07-03 22:16:27 +00001446 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001447 break;
1448 case 6:
Chris Lattner40931922006-06-22 06:14:04 +00001449 if (Directive[0] == 'd' && !strcmp(Directive, "define"))
Chris Lattner81278c62006-10-14 19:03:49 +00001450 return HandleDefineDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001451 if (Directive[0] == 'i' && !strcmp(Directive, "ifndef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001452 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
Chris Lattner40931922006-06-22 06:14:04 +00001453 if (Directive[0] == 'i' && !strcmp(Directive, "import"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001454 return HandleImportDirective(Result);
Chris Lattnerb8761832006-06-24 21:31:03 +00001455 if (Directive[0] == 'p' && !strcmp(Directive, "pragma"))
Chris Lattner69772b02006-07-02 20:34:39 +00001456 return HandlePragmaDirective();
Chris Lattnerb8761832006-06-24 21:31:03 +00001457 if (Directive[0] == 'a' && !strcmp(Directive, "assert"))
1458 isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001459 break;
1460 case 7:
Chris Lattner40931922006-06-22 06:14:04 +00001461 if (Directive[0] == 'i' && !strcmp(Directive, "include"))
1462 return HandleIncludeDirective(Result); // Handle #include.
1463 if (Directive[0] == 'w' && !strcmp(Directive, "warning")) {
Chris Lattnercb283342006-06-18 06:48:37 +00001464 Diag(Result, diag::ext_pp_warning_directive);
Chris Lattner504f2eb2006-06-18 07:19:54 +00001465 return HandleUserDiagnosticDirective(Result, true);
Chris Lattnercb283342006-06-18 06:48:37 +00001466 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001467 break;
1468 case 8:
Chris Lattner40931922006-06-22 06:14:04 +00001469 if (Directive[0] == 'u' && !strcmp(Directive, "unassert")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001470 isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001471 }
1472 break;
1473 case 12:
Chris Lattner40931922006-06-22 06:14:04 +00001474 if (Directive[0] == 'i' && !strcmp(Directive, "include_next"))
1475 return HandleIncludeNextDirective(Result); // Handle #include_next.
Chris Lattner22eb9722006-06-18 05:43:12 +00001476 break;
Chris Lattner81278c62006-10-14 19:03:49 +00001477 case 13:
1478 if (Directive[0] == 'd' && !strcmp(Directive, "define_target"))
1479 return HandleDefineDirective(Result, true);
1480 break;
Chris Lattner063400e2006-10-14 19:54:15 +00001481 case 19:
1482 if (Directive[0] == 'd' && !strcmp(Directive, "define_other_target"))
1483 return HandleDefineOtherTargetDirective(Result);
1484 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00001485 }
1486 break;
1487 }
1488
1489 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001490 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001491
1492 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001493 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001494
1495 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001496}
1497
Chris Lattner01d66cc2006-07-03 22:16:27 +00001498void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001499 bool isWarning) {
1500 // Read the rest of the line raw. We do this because we don't want macros
1501 // to be expanded and we don't require that the tokens be valid preprocessing
1502 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1503 // collapse multiple consequtive white space between tokens, but this isn't
1504 // specified by the standard.
1505 std::string Message = CurLexer->ReadToEndOfLine();
1506
1507 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001508 return Diag(Tok, DiagID, Message);
1509}
1510
1511/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1512///
1513void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001514 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001515 Diag(Tok, diag::ext_pp_ident_directive);
1516
Chris Lattner371ac8a2006-07-04 07:11:10 +00001517 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001518 LexerToken StrTok;
1519 Lex(StrTok);
1520
1521 // If the token kind isn't a string, it's a malformed directive.
Chris Lattnerd3e98952006-10-06 05:22:26 +00001522 if (StrTok.getKind() != tok::string_literal &&
1523 StrTok.getKind() != tok::wide_string_literal)
Chris Lattner01d66cc2006-07-03 22:16:27 +00001524 return Diag(StrTok, diag::err_pp_malformed_ident);
1525
1526 // Verify that there is nothing after the string, other than EOM.
1527 CheckEndOfDirective("#ident");
1528
1529 if (IdentHandler)
1530 IdentHandler(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001531}
1532
Chris Lattnerb8761832006-06-24 21:31:03 +00001533//===----------------------------------------------------------------------===//
1534// Preprocessor Include Directive Handling.
1535//===----------------------------------------------------------------------===//
1536
Chris Lattner22eb9722006-06-18 05:43:12 +00001537/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1538/// file to be included from the lexer, then include it! This is a common
1539/// routine with functionality shared between #include, #include_next and
1540/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001541void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001542 const DirectoryLookup *LookupFrom,
1543 bool isImport) {
1544 ++NumIncluded;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001545
Chris Lattner22eb9722006-06-18 05:43:12 +00001546 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001547 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001548
1549 // If the token kind is EOM, the error has already been diagnosed.
1550 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001551 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001552
1553 // Verify that there is nothing after the filename, other than EOM. Use the
1554 // preprocessor to lex this in case lexing the filename entered a macro.
1555 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001556
1557 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001558 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001559 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1560
Chris Lattner269c2322006-06-25 06:23:00 +00001561 // Find out whether the filename is <x> or "x".
1562 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001563
1564 // Remove the quotes.
1565 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1566
Chris Lattner22eb9722006-06-18 05:43:12 +00001567 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001568 const DirectoryLookup *CurDir;
1569 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001570 if (File == 0)
1571 return Diag(FilenameTok, diag::err_pp_file_not_found);
1572
1573 // Get information about this file.
1574 PerFileInfo &FileInfo = getFileInfo(File);
1575
1576 // If this is a #import directive, check that we have not already imported
1577 // this header.
1578 if (isImport) {
1579 // If this has already been imported, don't import it again.
1580 FileInfo.isImport = true;
1581
1582 // Has this already been #import'ed or #include'd?
Chris Lattnercb283342006-06-18 06:48:37 +00001583 if (FileInfo.NumIncludes) return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001584 } else {
1585 // Otherwise, if this is a #include of a file that was previously #import'd
1586 // or if this is the second #include of a #pragma once file, ignore it.
1587 if (FileInfo.isImport)
Chris Lattnercb283342006-06-18 06:48:37 +00001588 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001589 }
Chris Lattner3665f162006-07-04 07:26:10 +00001590
1591 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1592 // if the macro that guards it is defined, we know the #include has no effect.
1593 if (FileInfo.ControllingMacro && FileInfo.ControllingMacro->getMacroInfo()) {
1594 ++NumMultiIncludeFileOptzn;
1595 return;
1596 }
1597
Chris Lattner22eb9722006-06-18 05:43:12 +00001598
1599 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001600 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001601 if (FileID == 0)
1602 return Diag(FilenameTok, diag::err_pp_file_not_found);
1603
1604 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001605 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001606
1607 // Increment the number of times this file has been included.
1608 ++FileInfo.NumIncludes;
Chris Lattner22eb9722006-06-18 05:43:12 +00001609}
1610
1611/// HandleIncludeNextDirective - Implements #include_next.
1612///
Chris Lattnercb283342006-06-18 06:48:37 +00001613void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1614 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001615
1616 // #include_next is like #include, except that we start searching after
1617 // the current found directory. If we can't do this, issue a
1618 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001619 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001620 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001621 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001622 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001623 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001624 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001625 } else {
1626 // Start looking up in the next directory.
1627 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001628 }
1629
1630 return HandleIncludeDirective(IncludeNextTok, Lookup);
1631}
1632
1633/// HandleImportDirective - Implements #import.
1634///
Chris Lattnercb283342006-06-18 06:48:37 +00001635void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1636 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001637
1638 return HandleIncludeDirective(ImportTok, 0, true);
1639}
1640
Chris Lattnerb8761832006-06-24 21:31:03 +00001641//===----------------------------------------------------------------------===//
1642// Preprocessor Macro Directive Handling.
1643//===----------------------------------------------------------------------===//
1644
Chris Lattnercefc7682006-07-08 08:28:12 +00001645/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1646/// definition has just been read. Lex the rest of the arguments and the
1647/// closing ), updating MI with what we learn. Return true if an error occurs
1648/// parsing the arg list.
1649bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1650 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001651 while (1) {
1652 LexUnexpandedToken(Tok);
1653 switch (Tok.getKind()) {
1654 case tok::r_paren:
1655 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001656 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001657 // Otherwise we have #define FOO(A,)
1658 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1659 return true;
1660 case tok::ellipsis: // #define X(... -> C99 varargs
1661 // Warn if use of C99 feature in non-C99 mode.
1662 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1663
1664 // Lex the token after the identifier.
1665 LexUnexpandedToken(Tok);
1666 if (Tok.getKind() != tok::r_paren) {
1667 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1668 return true;
1669 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001670 // Add the __VA_ARGS__ identifier as an argument.
1671 MI->addArgument(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001672 MI->setIsC99Varargs();
1673 return false;
1674 case tok::eom: // #define X(
1675 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1676 return true;
1677 default: // #define X(1
1678 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1679 return true;
1680 case tok::identifier:
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001681 IdentifierInfo *II = Tok.getIdentifierInfo();
1682
1683 // If this is already used as an argument, it is used multiple times (e.g.
1684 // #define X(A,A.
Chris Lattnerc6532462006-07-15 06:55:18 +00001685 if (MI->getArgumentNum(II) != -1) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001686 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1687 return true;
1688 }
1689
1690 // Add the argument to the macro info.
1691 MI->addArgument(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001692
1693 // Lex the token after the identifier.
1694 LexUnexpandedToken(Tok);
1695
1696 switch (Tok.getKind()) {
1697 default: // #define X(A B
1698 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1699 return true;
1700 case tok::r_paren: // #define X(A)
1701 return false;
1702 case tok::comma: // #define X(A,
1703 break;
1704 case tok::ellipsis: // #define X(A... -> GCC extension
1705 // Diagnose extension.
1706 Diag(Tok, diag::ext_named_variadic_macro);
1707
1708 // Lex the token after the identifier.
1709 LexUnexpandedToken(Tok);
1710 if (Tok.getKind() != tok::r_paren) {
1711 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1712 return true;
1713 }
1714
1715 MI->setIsGNUVarargs();
1716 return false;
1717 }
1718 }
1719 }
1720}
1721
Chris Lattner22eb9722006-06-18 05:43:12 +00001722/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00001723/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
1724/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00001725///
Chris Lattner81278c62006-10-14 19:03:49 +00001726void Preprocessor::HandleDefineDirective(LexerToken &DefineTok,
1727 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001728 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001729
Chris Lattner22eb9722006-06-18 05:43:12 +00001730 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001731 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001732
1733 // Error reading macro name? If so, diagnostic already issued.
1734 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001735 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001736
Chris Lattner457fc152006-07-29 06:30:25 +00001737 // If we are supposed to keep comments in #defines, reenable comment saving
1738 // mode.
1739 CurLexer->KeepCommentMode = Features.KeepMacroComments;
1740
Chris Lattner063400e2006-10-14 19:54:15 +00001741 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00001742 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00001743 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00001744
Chris Lattner063400e2006-10-14 19:54:15 +00001745 // If the identifier is an 'other target' macro, clear this bit.
1746 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1747
1748
Chris Lattner22eb9722006-06-18 05:43:12 +00001749 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001750 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001751
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001752 // If this is a function-like macro definition, parse the argument list,
1753 // marking each of the identifiers as being used as macro arguments. Also,
1754 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001755 if (Tok.getKind() == tok::eom) {
1756 // If there is no body to this macro, we have no special handling here.
1757 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001758 // This is a function-like macro definition. Read the argument list.
1759 MI->setIsFunctionLike();
1760 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001761 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001762 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001763 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001764 if (CurLexer->ParsingPreprocessorDirective)
1765 DiscardUntilEndOfDirective();
1766 return;
1767 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001768
Chris Lattner815a1f92006-07-08 20:48:04 +00001769 // Read the first token after the arg list for down below.
1770 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001771 } else if (!Tok.hasLeadingSpace()) {
1772 // C99 requires whitespace between the macro definition and the body. Emit
1773 // a diagnostic for something like "#define X+".
1774 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001775 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001776 } else {
1777 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1778 // one in some cases!
1779 }
1780 } else {
1781 // This is a normal token with leading space. Clear the leading space
1782 // marker on the first token to get proper expansion.
Chris Lattner8c204872006-10-14 05:19:21 +00001783 Tok.clearFlag(LexerToken::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001784 }
1785
Chris Lattner7e374832006-07-29 03:46:57 +00001786 // If this is a definition of a variadic C99 function-like macro, not using
1787 // the GNU named varargs extension, enabled __VA_ARGS__.
1788
1789 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1790 // This gets unpoisoned where it is allowed.
1791 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1792 if (MI->isC99Varargs())
1793 Ident__VA_ARGS__->setIsPoisoned(false);
1794
Chris Lattner22eb9722006-06-18 05:43:12 +00001795 // Read the rest of the macro body.
1796 while (Tok.getKind() != tok::eom) {
1797 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001798
1799 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
Chris Lattner69f88b82006-07-11 05:07:29 +00001800 // parameters in function-like macro expansions.
1801 if (Tok.getKind() != tok::hash || MI->isObjectLike()) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001802 // Get the next token of the macro.
1803 LexUnexpandedToken(Tok);
1804 continue;
1805 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001806
Chris Lattner815a1f92006-07-08 20:48:04 +00001807 // Get the next token of the macro.
1808 LexUnexpandedToken(Tok);
1809
1810 // Not a macro arg identifier?
Chris Lattnerc6532462006-07-15 06:55:18 +00001811 if (!Tok.getIdentifierInfo() ||
Chris Lattner95a06b32006-07-30 08:40:43 +00001812 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001813 Diag(Tok, diag::err_pp_stringize_not_parameter);
Chris Lattner815a1f92006-07-08 20:48:04 +00001814 delete MI;
Chris Lattner7e374832006-07-29 03:46:57 +00001815
1816 // Disable __VA_ARGS__ again.
1817 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattner815a1f92006-07-08 20:48:04 +00001818 return;
1819 }
1820
1821 // Things look ok, add the param name token to the macro.
1822 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001823
Chris Lattner22eb9722006-06-18 05:43:12 +00001824 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001825 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001826 }
Chris Lattner7e374832006-07-29 03:46:57 +00001827
1828 // Disable __VA_ARGS__ again.
1829 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001830
Chris Lattnerbff18d52006-07-06 04:49:18 +00001831 // Check that there is no paste (##) operator at the begining or end of the
1832 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001833 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001834 if (NumTokens != 0) {
1835 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001836 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001837 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001838 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001839 }
1840 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001841 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001842 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001843 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001844 }
1845 }
1846
Chris Lattner13044d92006-07-03 05:16:44 +00001847 // If this is the primary source file, remember that this macro hasn't been
1848 // used yet.
1849 if (isInPrimaryFile())
1850 MI->setIsUsed(false);
1851
Chris Lattner22eb9722006-06-18 05:43:12 +00001852 // Finally, if this identifier already had a macro defined for it, verify that
1853 // the macro bodies are identical and free the old definition.
1854 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001855 if (!OtherMI->isUsed())
1856 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1857
Chris Lattner22eb9722006-06-18 05:43:12 +00001858 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001859 // must be the same. C99 6.10.3.2.
1860 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001861 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1862 MacroNameTok.getIdentifierInfo()->getName());
1863 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1864 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001865 delete OtherMI;
1866 }
1867
1868 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001869}
1870
Chris Lattner063400e2006-10-14 19:54:15 +00001871/// HandleDefineOtherTargetDirective - Implements #define_other_target.
1872void Preprocessor::HandleDefineOtherTargetDirective(LexerToken &Tok) {
1873 LexerToken MacroNameTok;
1874 ReadMacroName(MacroNameTok, 1);
1875
1876 // Error reading macro name? If so, diagnostic already issued.
1877 if (MacroNameTok.getKind() == tok::eom)
1878 return;
1879
1880 // Check to see if this is the last token on the #undef line.
1881 CheckEndOfDirective("#define_other_target");
1882
1883 // If there is already a macro defined by this name, turn it into a
1884 // target-specific define.
1885 if (MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
1886 MI->setIsTargetSpecific(true);
1887 return;
1888 }
1889
1890 // Mark the identifier as being a macro on some other target.
1891 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
1892}
1893
Chris Lattner22eb9722006-06-18 05:43:12 +00001894
1895/// HandleUndefDirective - Implements #undef.
1896///
Chris Lattnercb283342006-06-18 06:48:37 +00001897void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001898 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001899
Chris Lattner22eb9722006-06-18 05:43:12 +00001900 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001901 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001902
1903 // Error reading macro name? If so, diagnostic already issued.
1904 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001905 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001906
1907 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001908 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001909
1910 // Okay, we finally have a valid identifier to undef.
1911 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1912
Chris Lattner063400e2006-10-14 19:54:15 +00001913 // #undef untaints an identifier if it were marked by define_other_target.
1914 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1915
Chris Lattner22eb9722006-06-18 05:43:12 +00001916 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001917 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001918
Chris Lattner13044d92006-07-03 05:16:44 +00001919 if (!MI->isUsed())
1920 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001921
1922 // Free macro definition.
1923 delete MI;
1924 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001925}
1926
1927
Chris Lattnerb8761832006-06-24 21:31:03 +00001928//===----------------------------------------------------------------------===//
1929// Preprocessor Conditional Directive Handling.
1930//===----------------------------------------------------------------------===//
1931
Chris Lattner22eb9722006-06-18 05:43:12 +00001932/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001933/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1934/// if any tokens have been returned or pp-directives activated before this
1935/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001936///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001937void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1938 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001939 ++NumIf;
1940 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001941
Chris Lattner22eb9722006-06-18 05:43:12 +00001942 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001943 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001944
1945 // Error reading macro name? If so, diagnostic already issued.
1946 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001947 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001948
1949 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001950 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1951
1952 // If the start of a top-level #ifdef, inform MIOpt.
1953 if (!ReadAnyTokensBeforeDirective &&
1954 CurLexer->getConditionalStackDepth() == 0) {
1955 assert(isIfndef && "#ifdef shouldn't reach here");
1956 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1957 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001958
Chris Lattner063400e2006-10-14 19:54:15 +00001959 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1960 MacroInfo *MI = MII->getMacroInfo();
Chris Lattnera78a97e2006-07-03 05:42:18 +00001961
Chris Lattner81278c62006-10-14 19:03:49 +00001962 // If there is a macro, process it.
1963 if (MI) {
1964 // Mark it used.
1965 MI->setIsUsed(true);
1966
1967 // If this is the first use of a target-specific macro, warn about it.
1968 if (MI->isTargetSpecific()) {
1969 MI->setIsTargetSpecific(false); // Don't warn on second use.
1970 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1971 diag::port_target_macro_use);
1972 }
Chris Lattner063400e2006-10-14 19:54:15 +00001973 } else {
1974 // Use of a target-specific macro for some other target? If so, warn.
1975 if (MII->isOtherTargetMacro()) {
1976 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
1977 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1978 diag::port_target_macro_use);
1979 }
Chris Lattner81278c62006-10-14 19:03:49 +00001980 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00001981
Chris Lattner22eb9722006-06-18 05:43:12 +00001982 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001983 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001984 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001985 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001986 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001987 } else {
1988 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001989 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001990 /*Foundnonskip*/false,
1991 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001992 }
1993}
1994
1995/// HandleIfDirective - Implements the #if directive.
1996///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001997void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1998 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001999 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002000
Chris Lattner371ac8a2006-07-04 07:11:10 +00002001 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00002002 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00002003 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00002004
2005 // Should we include the stuff contained by this directive?
2006 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00002007 // If this condition is equivalent to #ifndef X, and if this is the first
2008 // directive seen, handle it for the multiple-include optimization.
2009 if (!ReadAnyTokensBeforeDirective &&
2010 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2011 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2012
Chris Lattner22eb9722006-06-18 05:43:12 +00002013 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002014 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002015 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002016 } else {
2017 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002018 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00002019 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002020 }
2021}
2022
2023/// HandleEndifDirective - Implements the #endif directive.
2024///
Chris Lattnercb283342006-06-18 06:48:37 +00002025void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002026 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002027
Chris Lattner22eb9722006-06-18 05:43:12 +00002028 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00002029 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00002030
2031 PPConditionalInfo CondInfo;
2032 if (CurLexer->popConditionalLevel(CondInfo)) {
2033 // No conditionals on the stack: this is an #endif without an #if.
2034 return Diag(EndifToken, diag::err_pp_endif_without_if);
2035 }
2036
Chris Lattner371ac8a2006-07-04 07:11:10 +00002037 // If this the end of a top-level #endif, inform MIOpt.
2038 if (CurLexer->getConditionalStackDepth() == 0)
2039 CurLexer->MIOpt.ExitTopLevelConditional();
2040
Chris Lattner538d7f32006-07-20 04:31:52 +00002041 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00002042 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00002043}
2044
2045
Chris Lattnercb283342006-06-18 06:48:37 +00002046void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002047 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002048
Chris Lattner22eb9722006-06-18 05:43:12 +00002049 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00002050 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00002051
2052 PPConditionalInfo CI;
2053 if (CurLexer->popConditionalLevel(CI))
2054 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00002055
2056 // If this is a top-level #else, inform the MIOpt.
2057 if (CurLexer->getConditionalStackDepth() == 0)
2058 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00002059
2060 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002061 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002062
2063 // Finally, skip the rest of the contents of this block and return the first
2064 // token after it.
2065 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2066 /*FoundElse*/true);
2067}
2068
Chris Lattnercb283342006-06-18 06:48:37 +00002069void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002070 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002071
Chris Lattner22eb9722006-06-18 05:43:12 +00002072 // #elif directive in a non-skipping conditional... start skipping.
2073 // We don't care what the condition is, because we will always skip it (since
2074 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002075 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002076
2077 PPConditionalInfo CI;
2078 if (CurLexer->popConditionalLevel(CI))
2079 return Diag(ElifToken, diag::pp_err_elif_without_if);
2080
Chris Lattner371ac8a2006-07-04 07:11:10 +00002081 // If this is a top-level #elif, inform the MIOpt.
2082 if (CurLexer->getConditionalStackDepth() == 0)
2083 CurLexer->MIOpt.FoundTopLevelElse();
2084
Chris Lattner22eb9722006-06-18 05:43:12 +00002085 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002086 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002087
2088 // Finally, skip the rest of the contents of this block and return the first
2089 // token after it.
2090 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2091 /*FoundElse*/CI.FoundElse);
2092}
Chris Lattnerb8761832006-06-24 21:31:03 +00002093