blob: 25ddb03d48a782202ef88671533ea23521db99e5 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Preprocessor interface.
11//
12//===----------------------------------------------------------------------===//
13//
14// Options to support:
15// -H - Print the name of each header file used.
16// -d[MDNI] - Dump various things.
17// -fworking-directory - #line's with preprocessor's working dir.
18// -fpreprocessed
19// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
20// -W*
21// -w
22//
23// Messages to emit:
24// "Multiple include guards may be useful for:\n"
25//
26//===----------------------------------------------------------------------===//
27
28#include "clang/Lex/Preprocessor.h"
29#include "clang/Lex/HeaderSearch.h"
30#include "clang/Lex/MacroInfo.h"
31#include "clang/Lex/PPCallbacks.h"
32#include "clang/Lex/Pragma.h"
33#include "clang/Lex/ScratchBuffer.h"
34#include "clang/Basic/Diagnostic.h"
35#include "clang/Basic/FileManager.h"
36#include "clang/Basic/SourceManager.h"
37#include "clang/Basic/TargetInfo.h"
38#include "llvm/ADT/SmallVector.h"
39#include "llvm/Support/MemoryBuffer.h"
40#include <iostream>
41using namespace clang;
42
43//===----------------------------------------------------------------------===//
44
45Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
46 TargetInfo &target, SourceManager &SM,
47 HeaderSearch &Headers)
48 : Diags(diags), Features(opts), Target(target), FileMgr(Headers.getFileMgr()),
49 SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts),
50 CurLexer(0), CurDirLookup(0), CurMacroExpander(0), Callbacks(0) {
51 ScratchBuf = new ScratchBuffer(SourceMgr);
52
53 // Clear stats.
54 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
55 NumIf = NumElse = NumEndif = 0;
56 NumEnteredSourceFiles = 0;
57 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
58 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
59 MaxIncludeStackDepth = 0;
60 NumSkipped = 0;
61
62 // Default to discarding comments.
63 KeepComments = false;
64 KeepMacroComments = false;
65
66 // Macro expansion is enabled.
67 DisableMacroExpansion = false;
68 InMacroArgs = false;
69 NumCachedMacroExpanders = 0;
70
71 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
72 // This gets unpoisoned where it is allowed.
73 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
74
75 // Initialize the pragma handlers.
76 PragmaHandlers = new PragmaNamespace(0);
77 RegisterBuiltinPragmas();
78
79 // Initialize builtin macros like __LINE__ and friends.
80 RegisterBuiltinMacros();
81}
82
83Preprocessor::~Preprocessor() {
84 // Free any active lexers.
85 delete CurLexer;
86
87 while (!IncludeMacroStack.empty()) {
88 delete IncludeMacroStack.back().TheLexer;
89 delete IncludeMacroStack.back().TheMacroExpander;
90 IncludeMacroStack.pop_back();
91 }
92
93 // Free any cached macro expanders.
94 for (unsigned i = 0, e = NumCachedMacroExpanders; i != e; ++i)
95 delete MacroExpanderCache[i];
96
97 // Release pragma information.
98 delete PragmaHandlers;
99
100 // Delete the scratch buffer info.
101 delete ScratchBuf;
102}
103
104PPCallbacks::~PPCallbacks() {
105}
106
107/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
108/// the specified Token's location, translating the token's start
109/// position in the current buffer into a SourcePosition object for rendering.
110void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID) {
111 Diags.Report(Loc, DiagID);
112}
113
114void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
115 const std::string &Msg) {
116 Diags.Report(Loc, DiagID, &Msg, 1);
117}
118
119void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
120 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
121 << getSpelling(Tok) << "'";
122
123 if (!DumpFlags) return;
124 std::cerr << "\t";
125 if (Tok.isAtStartOfLine())
126 std::cerr << " [StartOfLine]";
127 if (Tok.hasLeadingSpace())
128 std::cerr << " [LeadingSpace]";
129 if (Tok.isExpandDisabled())
130 std::cerr << " [ExpandDisabled]";
131 if (Tok.needsCleaning()) {
132 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
133 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
134 << "']";
135 }
136}
137
138void Preprocessor::DumpMacro(const MacroInfo &MI) const {
139 std::cerr << "MACRO: ";
140 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
141 DumpToken(MI.getReplacementToken(i));
142 std::cerr << " ";
143 }
144 std::cerr << "\n";
145}
146
147void Preprocessor::PrintStats() {
148 std::cerr << "\n*** Preprocessor Stats:\n";
149 std::cerr << NumDirectives << " directives found:\n";
150 std::cerr << " " << NumDefined << " #define.\n";
151 std::cerr << " " << NumUndefined << " #undef.\n";
152 std::cerr << " #include/#include_next/#import:\n";
153 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
154 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
155 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
156 std::cerr << " " << NumElse << " #else/#elif.\n";
157 std::cerr << " " << NumEndif << " #endif.\n";
158 std::cerr << " " << NumPragma << " #pragma.\n";
159 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
160
161 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
162 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
163 << NumFastMacroExpanded << " on the fast path.\n";
164 std::cerr << (NumFastTokenPaste+NumTokenPaste)
165 << " token paste (##) operations performed, "
166 << NumFastTokenPaste << " on the fast path.\n";
167}
168
169//===----------------------------------------------------------------------===//
170// Token Spelling
171//===----------------------------------------------------------------------===//
172
173
174/// getSpelling() - Return the 'spelling' of this token. The spelling of a
175/// token are the characters used to represent the token in the source file
176/// after trigraph expansion and escaped-newline folding. In particular, this
177/// wants to get the true, uncanonicalized, spelling of things like digraphs
178/// UCNs, etc.
179std::string Preprocessor::getSpelling(const Token &Tok) const {
180 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
181
182 // If this token contains nothing interesting, return it directly.
183 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
184 if (!Tok.needsCleaning())
185 return std::string(TokStart, TokStart+Tok.getLength());
186
187 std::string Result;
188 Result.reserve(Tok.getLength());
189
190 // Otherwise, hard case, relex the characters into the string.
191 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
192 Ptr != End; ) {
193 unsigned CharSize;
194 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
195 Ptr += CharSize;
196 }
197 assert(Result.size() != unsigned(Tok.getLength()) &&
198 "NeedsCleaning flag set on something that didn't need cleaning!");
199 return Result;
200}
201
202/// getSpelling - This method is used to get the spelling of a token into a
203/// preallocated buffer, instead of as an std::string. The caller is required
204/// to allocate enough space for the token, which is guaranteed to be at least
205/// Tok.getLength() bytes long. The actual length of the token is returned.
206///
207/// Note that this method may do two possible things: it may either fill in
208/// the buffer specified with characters, or it may *change the input pointer*
209/// to point to a constant buffer with the data already in it (avoiding a
210/// copy). The caller is not allowed to modify the returned buffer pointer
211/// if an internal buffer is returned.
212unsigned Preprocessor::getSpelling(const Token &Tok,
213 const char *&Buffer) const {
214 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
215
216 // If this token is an identifier, just return the string from the identifier
217 // table, which is very quick.
218 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
219 Buffer = II->getName();
220
221 // Return the length of the token. If the token needed cleaning, don't
222 // include the size of the newlines or trigraphs in it.
223 if (!Tok.needsCleaning())
224 return Tok.getLength();
225 else
226 return strlen(Buffer);
227 }
228
229 // Otherwise, compute the start of the token in the input lexer buffer.
230 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
231
232 // If this token contains nothing interesting, return it directly.
233 if (!Tok.needsCleaning()) {
234 Buffer = TokStart;
235 return Tok.getLength();
236 }
237 // Otherwise, hard case, relex the characters into the string.
238 char *OutBuf = const_cast<char*>(Buffer);
239 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
240 Ptr != End; ) {
241 unsigned CharSize;
242 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
243 Ptr += CharSize;
244 }
245 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
246 "NeedsCleaning flag set on something that didn't need cleaning!");
247
248 return OutBuf-Buffer;
249}
250
251
252/// CreateString - Plop the specified string into a scratch buffer and return a
253/// location for it. If specified, the source location provides a source
254/// location for the token.
255SourceLocation Preprocessor::
256CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
257 if (SLoc.isValid())
258 return ScratchBuf->getToken(Buf, Len, SLoc);
259 return ScratchBuf->getToken(Buf, Len);
260}
261
262
263/// AdvanceToTokenCharacter - Given a location that specifies the start of a
264/// token, return a new location that specifies a character within the token.
265SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart,
266 unsigned CharNo) {
267 // If they request the first char of the token, we're trivially done. If this
268 // is a macro expansion, it doesn't make sense to point to a character within
269 // the instantiation point (the name). We could point to the source
270 // character, but without also pointing to instantiation info, this is
271 // confusing.
272 if (CharNo == 0 || TokStart.isMacroID()) return TokStart;
273
274 // Figure out how many physical characters away the specified logical
275 // character is. This needs to take into consideration newlines and
276 // trigraphs.
277 const char *TokPtr = SourceMgr.getCharacterData(TokStart);
278 unsigned PhysOffset = 0;
279
280 // The usual case is that tokens don't contain anything interesting. Skip
281 // over the uninteresting characters. If a token only consists of simple
282 // chars, this method is extremely fast.
283 while (CharNo && Lexer::isObviouslySimpleCharacter(*TokPtr))
284 ++TokPtr, --CharNo, ++PhysOffset;
285
286 // If we have a character that may be a trigraph or escaped newline, create a
287 // lexer to parse it correctly.
288 if (CharNo != 0) {
289 // Create a lexer starting at this token position.
290 Lexer TheLexer(TokStart, *this, TokPtr);
291 Token Tok;
292 // Skip over characters the remaining characters.
293 const char *TokStartPtr = TokPtr;
294 for (; CharNo; --CharNo)
295 TheLexer.getAndAdvanceChar(TokPtr, Tok);
296
297 PhysOffset += TokPtr-TokStartPtr;
298 }
299
300 return TokStart.getFileLocWithOffset(PhysOffset);
301}
302
303
304
305//===----------------------------------------------------------------------===//
306// Source File Location Methods.
307//===----------------------------------------------------------------------===//
308
309/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
310/// return null on failure. isAngled indicates whether the file reference is
311/// for system #include's or not (i.e. using <> instead of "").
312const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
313 const char *FilenameEnd,
314 bool isAngled,
315 const DirectoryLookup *FromDir,
316 const DirectoryLookup *&CurDir) {
317 // If the header lookup mechanism may be relative to the current file, pass in
318 // info about where the current file is.
319 const FileEntry *CurFileEnt = 0;
320 if (!FromDir) {
321 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
322 CurFileEnt = SourceMgr.getFileEntryForLoc(FileLoc);
323 }
324
325 // Do a standard file entry lookup.
326 CurDir = CurDirLookup;
327 const FileEntry *FE =
328 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
329 isAngled, FromDir, CurDir, CurFileEnt);
330 if (FE) return FE;
331
332 // Otherwise, see if this is a subframework header. If so, this is relative
333 // to one of the headers on the #include stack. Walk the list of the current
334 // headers on the #include stack and pass them to HeaderInfo.
335 if (CurLexer && !CurLexer->Is_PragmaLexer) {
336 CurFileEnt = SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc());
337 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
338 CurFileEnt)))
339 return FE;
340 }
341
342 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
343 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
344 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
345 CurFileEnt = SourceMgr.getFileEntryForLoc(ISEntry.TheLexer->getFileLoc());
346 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
347 CurFileEnt)))
348 return FE;
349 }
350 }
351
352 // Otherwise, we really couldn't find the file.
353 return 0;
354}
355
356/// isInPrimaryFile - Return true if we're in the top-level file, not in a
357/// #include.
358bool Preprocessor::isInPrimaryFile() const {
359 if (CurLexer && !CurLexer->Is_PragmaLexer)
360 return CurLexer->isMainFile();
361
362 // If there are any stacked lexers, we're in a #include.
363 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
364 if (IncludeMacroStack[i].TheLexer &&
365 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
366 return IncludeMacroStack[i].TheLexer->isMainFile();
367 return false;
368}
369
370/// getCurrentLexer - Return the current file lexer being lexed from. Note
371/// that this ignores any potentially active macro expansions and _Pragma
372/// expansions going on at the time.
373Lexer *Preprocessor::getCurrentFileLexer() const {
374 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
375
376 // Look for a stacked lexer.
377 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
378 Lexer *L = IncludeMacroStack[i-1].TheLexer;
379 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
380 return L;
381 }
382 return 0;
383}
384
385
386/// EnterSourceFile - Add a source file to the top of the include stack and
387/// start lexing tokens from it instead of the current buffer. Return true
388/// on failure.
389void Preprocessor::EnterSourceFile(unsigned FileID,
390 const DirectoryLookup *CurDir,
391 bool isMainFile) {
392 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
393 ++NumEnteredSourceFiles;
394
395 if (MaxIncludeStackDepth < IncludeMacroStack.size())
396 MaxIncludeStackDepth = IncludeMacroStack.size();
397
398 Lexer *TheLexer = new Lexer(SourceLocation::getFileLoc(FileID, 0), *this);
399 if (isMainFile) TheLexer->setIsMainFile();
400 EnterSourceFileWithLexer(TheLexer, CurDir);
401}
402
403/// EnterSourceFile - Add a source file to the top of the include stack and
404/// start lexing tokens from it instead of the current buffer.
405void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
406 const DirectoryLookup *CurDir) {
407
408 // Add the current lexer to the include stack.
409 if (CurLexer || CurMacroExpander)
410 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
411 CurMacroExpander));
412
413 CurLexer = TheLexer;
414 CurDirLookup = CurDir;
415 CurMacroExpander = 0;
416
417 // Notify the client, if desired, that we are in a new source file.
418 if (Callbacks && !CurLexer->Is_PragmaLexer) {
419 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
420
421 // Get the file entry for the current file.
422 if (const FileEntry *FE =
423 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
424 FileType = HeaderInfo.getFileDirFlavor(FE);
425
426 Callbacks->FileChanged(CurLexer->getFileLoc(),
427 PPCallbacks::EnterFile, FileType);
428 }
429}
430
431
432
433/// EnterMacro - Add a Macro to the top of the include stack and start lexing
434/// tokens from it instead of the current buffer.
435void Preprocessor::EnterMacro(Token &Tok, MacroArgs *Args) {
436 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
437 CurMacroExpander));
438 CurLexer = 0;
439 CurDirLookup = 0;
440
441 if (NumCachedMacroExpanders == 0) {
442 CurMacroExpander = new MacroExpander(Tok, Args, *this);
443 } else {
444 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
445 CurMacroExpander->Init(Tok, Args);
446 }
447}
448
449/// EnterTokenStream - Add a "macro" context to the top of the include stack,
450/// which will cause the lexer to start returning the specified tokens. Note
451/// that these tokens will be re-macro-expanded when/if expansion is enabled.
452/// This method assumes that the specified stream of tokens has a permanent
453/// owner somewhere, so they do not need to be copied.
454void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks) {
455 // Save our current state.
456 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
457 CurMacroExpander));
458 CurLexer = 0;
459 CurDirLookup = 0;
460
461 // Create a macro expander to expand from the specified token stream.
462 if (NumCachedMacroExpanders == 0) {
463 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
464 } else {
465 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
466 CurMacroExpander->Init(Toks, NumToks);
467 }
468}
469
470/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
471/// lexer stack. This should only be used in situations where the current
472/// state of the top-of-stack lexer is known.
473void Preprocessor::RemoveTopOfLexerStack() {
474 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
475
476 if (CurMacroExpander) {
477 // Delete or cache the now-dead macro expander.
478 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
479 delete CurMacroExpander;
480 else
481 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
482 } else {
483 delete CurLexer;
484 }
485 CurLexer = IncludeMacroStack.back().TheLexer;
486 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
487 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
488 IncludeMacroStack.pop_back();
489}
490
491//===----------------------------------------------------------------------===//
492// Macro Expansion Handling.
493//===----------------------------------------------------------------------===//
494
495/// RegisterBuiltinMacro - Register the specified identifier in the identifier
496/// table and mark it as a builtin macro to be expanded.
497IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
498 // Get the identifier.
499 IdentifierInfo *Id = getIdentifierInfo(Name);
500
501 // Mark it as being a macro that is builtin.
502 MacroInfo *MI = new MacroInfo(SourceLocation());
503 MI->setIsBuiltinMacro();
504 Id->setMacroInfo(MI);
505 return Id;
506}
507
508
509/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
510/// identifier table.
511void Preprocessor::RegisterBuiltinMacros() {
512 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
513 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
514 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
515 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
516 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
517
518 // GCC Extensions.
519 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
520 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
521 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
522}
523
524/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
525/// in its expansion, currently expands to that token literally.
526static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
527 const IdentifierInfo *MacroIdent) {
528 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
529
530 // If the token isn't an identifier, it's always literally expanded.
531 if (II == 0) return true;
532
533 // If the identifier is a macro, and if that macro is enabled, it may be
534 // expanded so it's not a trivial expansion.
535 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
536 // Fast expanding "#define X X" is ok, because X would be disabled.
537 II != MacroIdent)
538 return false;
539
540 // If this is an object-like macro invocation, it is safe to trivially expand
541 // it.
542 if (MI->isObjectLike()) return true;
543
544 // If this is a function-like macro invocation, it's safe to trivially expand
545 // as long as the identifier is not a macro argument.
546 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
547 I != E; ++I)
548 if (*I == II)
549 return false; // Identifier is a macro argument.
550
551 return true;
552}
553
554
555/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
556/// lexed is a '('. If so, consume the token and return true, if not, this
557/// method should have no observable side-effect on the lexed tokens.
558bool Preprocessor::isNextPPTokenLParen() {
559 // Do some quick tests for rejection cases.
560 unsigned Val;
561 if (CurLexer)
562 Val = CurLexer->isNextPPTokenLParen();
563 else
564 Val = CurMacroExpander->isNextTokenLParen();
565
566 if (Val == 2) {
567 // We have run off the end. If it's a source file we don't
568 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
569 // macro stack.
570 if (CurLexer)
571 return false;
572 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
573 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
574 if (Entry.TheLexer)
575 Val = Entry.TheLexer->isNextPPTokenLParen();
576 else
577 Val = Entry.TheMacroExpander->isNextTokenLParen();
578
579 if (Val != 2)
580 break;
581
582 // Ran off the end of a source file?
583 if (Entry.TheLexer)
584 return false;
585 }
586 }
587
588 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
589 // have found something that isn't a '(' or we found the end of the
590 // translation unit. In either case, return false.
591 if (Val != 1)
592 return false;
593
594 Token Tok;
595 LexUnexpandedToken(Tok);
596 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
597 return true;
598}
599
600/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
601/// expanded as a macro, handle it and return the next token as 'Identifier'.
602bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
603 MacroInfo *MI) {
604
605 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
606 if (MI->isBuiltinMacro()) {
607 ExpandBuiltinMacro(Identifier);
608 return false;
609 }
610
611 // If this is the first use of a target-specific macro, warn about it.
612 if (MI->isTargetSpecific()) {
613 MI->setIsTargetSpecific(false); // Don't warn on second use.
614 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
615 diag::port_target_macro_use);
616 }
617
618 /// Args - If this is a function-like macro expansion, this contains,
619 /// for each macro argument, the list of tokens that were provided to the
620 /// invocation.
621 MacroArgs *Args = 0;
622
623 // If this is a function-like macro, read the arguments.
624 if (MI->isFunctionLike()) {
625 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
626 // name isn't a '(', this macro should not be expanded. Otherwise, consume
627 // it.
628 if (!isNextPPTokenLParen())
629 return true;
630
631 // Remember that we are now parsing the arguments to a macro invocation.
632 // Preprocessor directives used inside macro arguments are not portable, and
633 // this enables the warning.
634 InMacroArgs = true;
635 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
636
637 // Finished parsing args.
638 InMacroArgs = false;
639
640 // If there was an error parsing the arguments, bail out.
641 if (Args == 0) return false;
642
643 ++NumFnMacroExpanded;
644 } else {
645 ++NumMacroExpanded;
646 }
647
648 // Notice that this macro has been used.
649 MI->setIsUsed(true);
650
651 // If we started lexing a macro, enter the macro expansion body.
652
653 // If this macro expands to no tokens, don't bother to push it onto the
654 // expansion stack, only to take it right back off.
655 if (MI->getNumTokens() == 0) {
656 // No need for arg info.
657 if (Args) Args->destroy();
658
659 // Ignore this macro use, just return the next token in the current
660 // buffer.
661 bool HadLeadingSpace = Identifier.hasLeadingSpace();
662 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
663
664 Lex(Identifier);
665
666 // If the identifier isn't on some OTHER line, inherit the leading
667 // whitespace/first-on-a-line property of this token. This handles
668 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
669 // empty.
670 if (!Identifier.isAtStartOfLine()) {
671 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
672 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
673 }
674 ++NumFastMacroExpanded;
675 return false;
676
677 } else if (MI->getNumTokens() == 1 &&
678 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
679 // Otherwise, if this macro expands into a single trivially-expanded
680 // token: expand it now. This handles common cases like
681 // "#define VAL 42".
682
683 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
684 // identifier to the expanded token.
685 bool isAtStartOfLine = Identifier.isAtStartOfLine();
686 bool hasLeadingSpace = Identifier.hasLeadingSpace();
687
688 // Remember where the token is instantiated.
689 SourceLocation InstantiateLoc = Identifier.getLocation();
690
691 // Replace the result token.
692 Identifier = MI->getReplacementToken(0);
693
694 // Restore the StartOfLine/LeadingSpace markers.
695 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
696 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
697
698 // Update the tokens location to include both its logical and physical
699 // locations.
700 SourceLocation Loc =
701 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
702 Identifier.setLocation(Loc);
703
704 // If this is #define X X, we must mark the result as unexpandible.
705 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
706 if (NewII->getMacroInfo() == MI)
707 Identifier.setFlag(Token::DisableExpand);
708
709 // Since this is not an identifier token, it can't be macro expanded, so
710 // we're done.
711 ++NumFastMacroExpanded;
712 return false;
713 }
714
715 // Start expanding the macro.
716 EnterMacro(Identifier, Args);
717
718 // Now that the macro is at the top of the include stack, ask the
719 // preprocessor to read the next token from it.
720 Lex(Identifier);
721 return false;
722}
723
724/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
725/// invoked to read all of the actual arguments specified for the macro
726/// invocation. This returns null on error.
727MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
728 MacroInfo *MI) {
729 // The number of fixed arguments to parse.
730 unsigned NumFixedArgsLeft = MI->getNumArgs();
731 bool isVariadic = MI->isVariadic();
732
733 // Outer loop, while there are more arguments, keep reading them.
734 Token Tok;
735 Tok.setKind(tok::comma);
736 --NumFixedArgsLeft; // Start reading the first arg.
737
738 // ArgTokens - Build up a list of tokens that make up each argument. Each
739 // argument is separated by an EOF token. Use a SmallVector so we can avoid
740 // heap allocations in the common case.
741 llvm::SmallVector<Token, 64> ArgTokens;
742
743 unsigned NumActuals = 0;
744 while (Tok.getKind() == tok::comma) {
745 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
746 // that we already consumed the first one.
747 unsigned NumParens = 0;
748
749 while (1) {
750 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
751 // an argument value in a macro could expand to ',' or '(' or ')'.
752 LexUnexpandedToken(Tok);
753
754 if (Tok.getKind() == tok::eof) {
755 Diag(MacroName, diag::err_unterm_macro_invoc);
756 // Do not lose the EOF. Return it to the client.
757 MacroName = Tok;
758 return 0;
759 } else if (Tok.getKind() == tok::r_paren) {
760 // If we found the ) token, the macro arg list is done.
761 if (NumParens-- == 0)
762 break;
763 } else if (Tok.getKind() == tok::l_paren) {
764 ++NumParens;
765 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
766 // Comma ends this argument if there are more fixed arguments expected.
767 if (NumFixedArgsLeft)
768 break;
769
770 // If this is not a variadic macro, too many args were specified.
771 if (!isVariadic) {
772 // Emit the diagnostic at the macro name in case there is a missing ).
773 // Emitting it at the , could be far away from the macro name.
774 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
775 return 0;
776 }
777 // Otherwise, continue to add the tokens to this variable argument.
778 } else if (Tok.getKind() == tok::comment && !KeepMacroComments) {
779 // If this is a comment token in the argument list and we're just in
780 // -C mode (not -CC mode), discard the comment.
781 continue;
782 }
783
784 ArgTokens.push_back(Tok);
785 }
786
787 // Empty arguments are standard in C99 and supported as an extension in
788 // other modes.
789 if (ArgTokens.empty() && !Features.C99)
790 Diag(Tok, diag::ext_empty_fnmacro_arg);
791
792 // Add a marker EOF token to the end of the token list for this argument.
793 Token EOFTok;
794 EOFTok.startToken();
795 EOFTok.setKind(tok::eof);
796 EOFTok.setLocation(Tok.getLocation());
797 EOFTok.setLength(0);
798 ArgTokens.push_back(EOFTok);
799 ++NumActuals;
800 --NumFixedArgsLeft;
801 };
802
803 // Okay, we either found the r_paren. Check to see if we parsed too few
804 // arguments.
805 unsigned MinArgsExpected = MI->getNumArgs();
806
807 // See MacroArgs instance var for description of this.
808 bool isVarargsElided = false;
809
810 if (NumActuals < MinArgsExpected) {
811 // There are several cases where too few arguments is ok, handle them now.
812 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
813 // Varargs where the named vararg parameter is missing: ok as extension.
814 // #define A(x, ...)
815 // A("blah")
816 Diag(Tok, diag::ext_missing_varargs_arg);
817
818 // Remember this occurred if this is a C99 macro invocation with at least
819 // one actual argument.
820 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
821 } else if (MI->getNumArgs() == 1) {
822 // #define A(x)
823 // A()
824 // is ok because it is an empty argument.
825
826 // Empty arguments are standard in C99 and supported as an extension in
827 // other modes.
828 if (ArgTokens.empty() && !Features.C99)
829 Diag(Tok, diag::ext_empty_fnmacro_arg);
830 } else {
831 // Otherwise, emit the error.
832 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
833 return 0;
834 }
835
836 // Add a marker EOF token to the end of the token list for this argument.
837 SourceLocation EndLoc = Tok.getLocation();
838 Tok.startToken();
839 Tok.setKind(tok::eof);
840 Tok.setLocation(EndLoc);
841 Tok.setLength(0);
842 ArgTokens.push_back(Tok);
843 }
844
845 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
846}
847
848/// ComputeDATE_TIME - Compute the current time, enter it into the specified
849/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
850/// the identifier tokens inserted.
851static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
852 Preprocessor &PP) {
853 time_t TT = time(0);
854 struct tm *TM = localtime(&TT);
855
856 static const char * const Months[] = {
857 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
858 };
859
860 char TmpBuffer[100];
861 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
862 TM->tm_year+1900);
863 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
864
865 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
866 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
867}
868
869/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
870/// as a builtin macro, handle it and return the next token as 'Tok'.
871void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
872 // Figure out which token this is.
873 IdentifierInfo *II = Tok.getIdentifierInfo();
874 assert(II && "Can't be a macro without id info!");
875
876 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
877 // lex the token after it.
878 if (II == Ident_Pragma)
879 return Handle_Pragma(Tok);
880
881 ++NumBuiltinMacroExpanded;
882
883 char TmpBuffer[100];
884
885 // Set up the return result.
886 Tok.setIdentifierInfo(0);
887 Tok.clearFlag(Token::NeedsCleaning);
888
889 if (II == Ident__LINE__) {
890 // __LINE__ expands to a simple numeric value.
891 sprintf(TmpBuffer, "%u", SourceMgr.getLogicalLineNumber(Tok.getLocation()));
892 unsigned Length = strlen(TmpBuffer);
893 Tok.setKind(tok::numeric_constant);
894 Tok.setLength(Length);
895 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
896 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
897 SourceLocation Loc = Tok.getLocation();
898 if (II == Ident__BASE_FILE__) {
899 Diag(Tok, diag::ext_pp_base_file);
900 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc);
901 while (NextLoc.isValid()) {
902 Loc = NextLoc;
903 NextLoc = SourceMgr.getIncludeLoc(Loc);
904 }
905 }
906
907 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
908 std::string FN = SourceMgr.getSourceName(SourceMgr.getLogicalLoc(Loc));
909 FN = '"' + Lexer::Stringify(FN) + '"';
910 Tok.setKind(tok::string_literal);
911 Tok.setLength(FN.size());
912 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
913 } else if (II == Ident__DATE__) {
914 if (!DATELoc.isValid())
915 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
916 Tok.setKind(tok::string_literal);
917 Tok.setLength(strlen("\"Mmm dd yyyy\""));
918 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
919 } else if (II == Ident__TIME__) {
920 if (!TIMELoc.isValid())
921 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
922 Tok.setKind(tok::string_literal);
923 Tok.setLength(strlen("\"hh:mm:ss\""));
924 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
925 } else if (II == Ident__INCLUDE_LEVEL__) {
926 Diag(Tok, diag::ext_pp_include_level);
927
928 // Compute the include depth of this token.
929 unsigned Depth = 0;
930 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation());
931 for (; Loc.isValid(); ++Depth)
932 Loc = SourceMgr.getIncludeLoc(Loc);
933
934 // __INCLUDE_LEVEL__ expands to a simple numeric value.
935 sprintf(TmpBuffer, "%u", Depth);
936 unsigned Length = strlen(TmpBuffer);
937 Tok.setKind(tok::numeric_constant);
938 Tok.setLength(Length);
939 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
940 } else if (II == Ident__TIMESTAMP__) {
941 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
942 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
943 Diag(Tok, diag::ext_pp_timestamp);
944
945 // Get the file that we are lexing out of. If we're currently lexing from
946 // a macro, dig into the include stack.
947 const FileEntry *CurFile = 0;
948 Lexer *TheLexer = getCurrentFileLexer();
949
950 if (TheLexer)
951 CurFile = SourceMgr.getFileEntryForLoc(TheLexer->getFileLoc());
952
953 // If this file is older than the file it depends on, emit a diagnostic.
954 const char *Result;
955 if (CurFile) {
956 time_t TT = CurFile->getModificationTime();
957 struct tm *TM = localtime(&TT);
958 Result = asctime(TM);
959 } else {
960 Result = "??? ??? ?? ??:??:?? ????\n";
961 }
962 TmpBuffer[0] = '"';
963 strcpy(TmpBuffer+1, Result);
964 unsigned Len = strlen(TmpBuffer);
965 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
966 Tok.setKind(tok::string_literal);
967 Tok.setLength(Len);
968 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
969 } else {
970 assert(0 && "Unknown identifier!");
971 }
972}
973
974//===----------------------------------------------------------------------===//
975// Lexer Event Handling.
976//===----------------------------------------------------------------------===//
977
978/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
979/// identifier information for the token and install it into the token.
980IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
981 const char *BufPtr) {
982 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
983 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
984
985 // Look up this token, see if it is a macro, or if it is a language keyword.
986 IdentifierInfo *II;
987 if (BufPtr && !Identifier.needsCleaning()) {
988 // No cleaning needed, just use the characters from the lexed buffer.
989 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
990 } else {
991 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
992 llvm::SmallVector<char, 64> IdentifierBuffer;
993 IdentifierBuffer.resize(Identifier.getLength());
994 const char *TmpBuf = &IdentifierBuffer[0];
995 unsigned Size = getSpelling(Identifier, TmpBuf);
996 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
997 }
998 Identifier.setIdentifierInfo(II);
999 return II;
1000}
1001
1002
1003/// HandleIdentifier - This callback is invoked when the lexer reads an
1004/// identifier. This callback looks up the identifier in the map and/or
1005/// potentially macro expands it or turns it into a named token (like 'for').
1006void Preprocessor::HandleIdentifier(Token &Identifier) {
1007 assert(Identifier.getIdentifierInfo() &&
1008 "Can't handle identifiers without identifier info!");
1009
1010 IdentifierInfo &II = *Identifier.getIdentifierInfo();
1011
1012 // If this identifier was poisoned, and if it was not produced from a macro
1013 // expansion, emit an error.
1014 if (II.isPoisoned() && CurLexer) {
1015 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
1016 Diag(Identifier, diag::err_pp_used_poisoned_id);
1017 else
1018 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
1019 }
1020
1021 // If this is a macro to be expanded, do it.
1022 if (MacroInfo *MI = II.getMacroInfo()) {
1023 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
1024 if (MI->isEnabled()) {
1025 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1026 return;
1027 } else {
1028 // C99 6.10.3.4p2 says that a disabled macro may never again be
1029 // expanded, even if it's in a context where it could be expanded in the
1030 // future.
1031 Identifier.setFlag(Token::DisableExpand);
1032 }
1033 }
1034 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
1035 // If this identifier is a macro on some other target, emit a diagnostic.
1036 // This diagnosic is only emitted when macro expansion is enabled, because
1037 // the macro would not have been expanded for the other target either.
1038 II.setIsOtherTargetMacro(false); // Don't warn on second use.
1039 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
1040 diag::port_target_macro_use);
1041
1042 }
1043
1044 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
1045 // then we act as if it is the actual operator and not the textual
1046 // representation of it.
1047 if (II.isCPlusPlusOperatorKeyword())
1048 Identifier.setIdentifierInfo(0);
1049
1050 // Change the kind of this identifier to the appropriate token kind, e.g.
1051 // turning "for" into a keyword.
1052 Identifier.setKind(II.getTokenID());
1053
1054 // If this is an extension token, diagnose its use.
1055 // FIXME: tried (unsuccesfully) to shut this up when compiling with gnu99
1056 // For now, I'm just commenting it out (while I work on attributes).
1057 if (II.isExtensionToken() && Features.C99)
1058 Diag(Identifier, diag::ext_token_used);
1059}
1060
1061/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1062/// the current file. This either returns the EOF token or pops a level off
1063/// the include stack and keeps going.
1064bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
1065 assert(!CurMacroExpander &&
1066 "Ending a file when currently in a macro!");
1067
1068 // See if this file had a controlling macro.
1069 if (CurLexer) { // Not ending a macro, ignore it.
1070 if (const IdentifierInfo *ControllingMacro =
1071 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
1072 // Okay, this has a controlling macro, remember in PerFileInfo.
1073 if (const FileEntry *FE =
1074 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
1075 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
1076 }
1077 }
1078
1079 // If this is a #include'd file, pop it off the include stack and continue
1080 // lexing the #includer file.
1081 if (!IncludeMacroStack.empty()) {
1082 // We're done with the #included file.
1083 RemoveTopOfLexerStack();
1084
1085 // Notify the client, if desired, that we are in a new source file.
1086 if (Callbacks && !isEndOfMacro && CurLexer) {
1087 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1088
1089 // Get the file entry for the current file.
1090 if (const FileEntry *FE =
1091 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
1092 FileType = HeaderInfo.getFileDirFlavor(FE);
1093
1094 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1095 PPCallbacks::ExitFile, FileType);
1096 }
1097
1098 // Client should lex another token.
1099 return false;
1100 }
1101
1102 Result.startToken();
1103 CurLexer->BufferPtr = CurLexer->BufferEnd;
1104 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
1105 Result.setKind(tok::eof);
1106
1107 // We're done with the #included file.
1108 delete CurLexer;
1109 CurLexer = 0;
1110
1111 // This is the end of the top-level file. If the diag::pp_macro_not_used
1112 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1113 // have not been used.
1114 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
1115 for (IdentifierTable::iterator I = Identifiers.begin(),
1116 E = Identifiers.end(); I != E; ++I) {
1117 const IdentifierInfo &II = I->getValue();
1118 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
1119 Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
1120 }
1121 }
1122
1123 return true;
1124}
1125
1126/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
1127/// the current macro expansion or token stream expansion.
1128bool Preprocessor::HandleEndOfMacro(Token &Result) {
1129 assert(CurMacroExpander && !CurLexer &&
1130 "Ending a macro when currently in a #include file!");
1131
1132 // Delete or cache the now-dead macro expander.
1133 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
1134 delete CurMacroExpander;
1135 else
1136 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
1137
1138 // Handle this like a #include file being popped off the stack.
1139 CurMacroExpander = 0;
1140 return HandleEndOfFile(Result, true);
1141}
1142
1143
1144//===----------------------------------------------------------------------===//
1145// Utility Methods for Preprocessor Directive Handling.
1146//===----------------------------------------------------------------------===//
1147
1148/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1149/// current line until the tok::eom token is found.
1150void Preprocessor::DiscardUntilEndOfDirective() {
1151 Token Tmp;
1152 do {
1153 LexUnexpandedToken(Tmp);
1154 } while (Tmp.getKind() != tok::eom);
1155}
1156
1157/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
1158static bool isCXXNamedOperator(const std::string &Spelling) {
1159 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
1160 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
1161 Spelling == "or" || Spelling == "xor";
1162}
1163
1164/// ReadMacroName - Lex and validate a macro name, which occurs after a
1165/// #define or #undef. This sets the token kind to eom and discards the rest
1166/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1167/// this is due to a a #define, 2 if #undef directive, 0 if it is something
1168/// else (e.g. #ifdef).
1169void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
1170 // Read the token, don't allow macro expansion on it.
1171 LexUnexpandedToken(MacroNameTok);
1172
1173 // Missing macro name?
1174 if (MacroNameTok.getKind() == tok::eom)
1175 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1176
1177 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1178 if (II == 0) {
1179 std::string Spelling = getSpelling(MacroNameTok);
1180 if (isCXXNamedOperator(Spelling))
1181 // C++ 2.5p2: Alternative tokens behave the same as its primary token
1182 // except for their spellings.
1183 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
1184 else
1185 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
1186 // Fall through on error.
1187 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
1188 // Error if defining "defined": C99 6.10.8.4.
1189 Diag(MacroNameTok, diag::err_defined_macro_name);
1190 } else if (isDefineUndef && II->getMacroInfo() &&
1191 II->getMacroInfo()->isBuiltinMacro()) {
1192 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
1193 if (isDefineUndef == 1)
1194 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1195 else
1196 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
1197 } else {
1198 // Okay, we got a good identifier node. Return it.
1199 return;
1200 }
1201
1202 // Invalid macro name, read and discard the rest of the line. Then set the
1203 // token kind to tok::eom.
1204 MacroNameTok.setKind(tok::eom);
1205 return DiscardUntilEndOfDirective();
1206}
1207
1208/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1209/// not, emit a diagnostic and consume up until the eom.
1210void Preprocessor::CheckEndOfDirective(const char *DirType) {
1211 Token Tmp;
1212 Lex(Tmp);
1213 // There should be no tokens after the directive, but we allow them as an
1214 // extension.
1215 while (Tmp.getKind() == tok::comment) // Skip comments in -C mode.
1216 Lex(Tmp);
1217
1218 if (Tmp.getKind() != tok::eom) {
1219 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1220 DiscardUntilEndOfDirective();
1221 }
1222}
1223
1224
1225
1226/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1227/// decided that the subsequent tokens are in the #if'd out portion of the
1228/// file. Lex the rest of the file, until we see an #endif. If
1229/// FoundNonSkipPortion is true, then we have already emitted code for part of
1230/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1231/// is true, then #else directives are ok, if not, then we have already seen one
1232/// so a #else directive is a duplicate. When this returns, the caller can lex
1233/// the first valid token.
1234void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
1235 bool FoundNonSkipPortion,
1236 bool FoundElse) {
1237 ++NumSkipped;
1238 assert(CurMacroExpander == 0 && CurLexer &&
1239 "Lexing a macro, not a file?");
1240
1241 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1242 FoundNonSkipPortion, FoundElse);
1243
1244 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1245 // disabling warnings, etc.
1246 CurLexer->LexingRawMode = true;
1247 Token Tok;
1248 while (1) {
1249 CurLexer->Lex(Tok);
1250
1251 // If this is the end of the buffer, we have an error.
1252 if (Tok.getKind() == tok::eof) {
1253 // Emit errors for each unterminated conditional on the stack, including
1254 // the current one.
1255 while (!CurLexer->ConditionalStack.empty()) {
1256 Diag(CurLexer->ConditionalStack.back().IfLoc,
1257 diag::err_pp_unterminated_conditional);
1258 CurLexer->ConditionalStack.pop_back();
1259 }
1260
1261 // Just return and let the caller lex after this #include.
1262 break;
1263 }
1264
1265 // If this token is not a preprocessor directive, just skip it.
1266 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1267 continue;
1268
1269 // We just parsed a # character at the start of a line, so we're in
1270 // directive mode. Tell the lexer this so any newlines we see will be
1271 // converted into an EOM token (this terminates the macro).
1272 CurLexer->ParsingPreprocessorDirective = true;
1273 CurLexer->KeepCommentMode = false;
1274
1275
1276 // Read the next token, the directive flavor.
1277 LexUnexpandedToken(Tok);
1278
1279 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1280 // something bogus), skip it.
1281 if (Tok.getKind() != tok::identifier) {
1282 CurLexer->ParsingPreprocessorDirective = false;
1283 // Restore comment saving mode.
1284 CurLexer->KeepCommentMode = KeepComments;
1285 continue;
1286 }
1287
1288 // If the first letter isn't i or e, it isn't intesting to us. We know that
1289 // this is safe in the face of spelling differences, because there is no way
1290 // to spell an i/e in a strange way that is another letter. Skipping this
1291 // allows us to avoid looking up the identifier info for #define/#undef and
1292 // other common directives.
1293 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1294 char FirstChar = RawCharData[0];
1295 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1296 FirstChar != 'i' && FirstChar != 'e') {
1297 CurLexer->ParsingPreprocessorDirective = false;
1298 // Restore comment saving mode.
1299 CurLexer->KeepCommentMode = KeepComments;
1300 continue;
1301 }
1302
1303 // Get the identifier name without trigraphs or embedded newlines. Note
1304 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1305 // when skipping.
1306 // TODO: could do this with zero copies in the no-clean case by using
1307 // strncmp below.
1308 char Directive[20];
1309 unsigned IdLen;
1310 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1311 IdLen = Tok.getLength();
1312 memcpy(Directive, RawCharData, IdLen);
1313 Directive[IdLen] = 0;
1314 } else {
1315 std::string DirectiveStr = getSpelling(Tok);
1316 IdLen = DirectiveStr.size();
1317 if (IdLen >= 20) {
1318 CurLexer->ParsingPreprocessorDirective = false;
1319 // Restore comment saving mode.
1320 CurLexer->KeepCommentMode = KeepComments;
1321 continue;
1322 }
1323 memcpy(Directive, &DirectiveStr[0], IdLen);
1324 Directive[IdLen] = 0;
1325 }
1326
1327 if (FirstChar == 'i' && Directive[1] == 'f') {
1328 if ((IdLen == 2) || // "if"
1329 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1330 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
1331 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1332 // bother parsing the condition.
1333 DiscardUntilEndOfDirective();
1334 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
1335 /*foundnonskip*/false,
1336 /*fnddelse*/false);
1337 }
1338 } else if (FirstChar == 'e') {
1339 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
1340 CheckEndOfDirective("#endif");
1341 PPConditionalInfo CondInfo;
1342 CondInfo.WasSkipping = true; // Silence bogus warning.
1343 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1344 InCond = InCond; // Silence warning in no-asserts mode.
1345 assert(!InCond && "Can't be skipping if not in a conditional!");
1346
1347 // If we popped the outermost skipping block, we're done skipping!
1348 if (!CondInfo.WasSkipping)
1349 break;
1350 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
1351 // #else directive in a skipping conditional. If not in some other
1352 // skipping conditional, and if #else hasn't already been seen, enter it
1353 // as a non-skipping conditional.
1354 CheckEndOfDirective("#else");
1355 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1356
1357 // If this is a #else with a #else before it, report the error.
1358 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
1359
1360 // Note that we've seen a #else in this conditional.
1361 CondInfo.FoundElse = true;
1362
1363 // If the conditional is at the top level, and the #if block wasn't
1364 // entered, enter the #else block now.
1365 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1366 CondInfo.FoundNonSkip = true;
1367 break;
1368 }
1369 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
1370 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1371
1372 bool ShouldEnter;
1373 // If this is in a skipping block or if we're already handled this #if
1374 // block, don't bother parsing the condition.
1375 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
1376 DiscardUntilEndOfDirective();
1377 ShouldEnter = false;
1378 } else {
1379 // Restore the value of LexingRawMode so that identifiers are
1380 // looked up, etc, inside the #elif expression.
1381 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1382 CurLexer->LexingRawMode = false;
1383 IdentifierInfo *IfNDefMacro = 0;
1384 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
1385 CurLexer->LexingRawMode = true;
1386 }
1387
1388 // If this is a #elif with a #else before it, report the error.
1389 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
1390
1391 // If this condition is true, enter it!
1392 if (ShouldEnter) {
1393 CondInfo.FoundNonSkip = true;
1394 break;
1395 }
1396 }
1397 }
1398
1399 CurLexer->ParsingPreprocessorDirective = false;
1400 // Restore comment saving mode.
1401 CurLexer->KeepCommentMode = KeepComments;
1402 }
1403
1404 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1405 // of the file, just stop skipping and return to lexing whatever came after
1406 // the #if block.
1407 CurLexer->LexingRawMode = false;
1408}
1409
1410//===----------------------------------------------------------------------===//
1411// Preprocessor Directive Handling.
1412//===----------------------------------------------------------------------===//
1413
1414/// HandleDirective - This callback is invoked when the lexer sees a # token
1415/// at the start of a line. This consumes the directive, modifies the
1416/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1417/// read is the correct one.
1418void Preprocessor::HandleDirective(Token &Result) {
1419 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
1420
1421 // We just parsed a # character at the start of a line, so we're in directive
1422 // mode. Tell the lexer this so any newlines we see will be converted into an
1423 // EOM token (which terminates the directive).
1424 CurLexer->ParsingPreprocessorDirective = true;
1425
1426 ++NumDirectives;
1427
1428 // We are about to read a token. For the multiple-include optimization FA to
1429 // work, we have to remember if we had read any tokens *before* this
1430 // pp-directive.
1431 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1432
1433 // Read the next token, the directive flavor. This isn't expanded due to
1434 // C99 6.10.3p8.
1435 LexUnexpandedToken(Result);
1436
1437 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1438 // #define A(x) #x
1439 // A(abc
1440 // #warning blah
1441 // def)
1442 // If so, the user is relying on non-portable behavior, emit a diagnostic.
1443 if (InMacroArgs)
1444 Diag(Result, diag::ext_embedded_directive);
1445
1446TryAgain:
1447 switch (Result.getKind()) {
1448 case tok::eom:
1449 return; // null directive.
1450 case tok::comment:
1451 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1452 LexUnexpandedToken(Result);
1453 goto TryAgain;
1454
1455 case tok::numeric_constant:
1456 // FIXME: implement # 7 line numbers!
1457 DiscardUntilEndOfDirective();
1458 return;
1459 default:
1460 IdentifierInfo *II = Result.getIdentifierInfo();
1461 if (II == 0) break; // Not an identifier.
1462
1463 // Ask what the preprocessor keyword ID is.
1464 switch (II->getPPKeywordID()) {
1465 default: break;
1466 // C99 6.10.1 - Conditional Inclusion.
1467 case tok::pp_if:
1468 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1469 case tok::pp_ifdef:
1470 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1471 case tok::pp_ifndef:
1472 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1473 case tok::pp_elif:
1474 return HandleElifDirective(Result);
1475 case tok::pp_else:
1476 return HandleElseDirective(Result);
1477 case tok::pp_endif:
1478 return HandleEndifDirective(Result);
1479
1480 // C99 6.10.2 - Source File Inclusion.
1481 case tok::pp_include:
1482 return HandleIncludeDirective(Result); // Handle #include.
1483
1484 // C99 6.10.3 - Macro Replacement.
1485 case tok::pp_define:
1486 return HandleDefineDirective(Result, false);
1487 case tok::pp_undef:
1488 return HandleUndefDirective(Result);
1489
1490 // C99 6.10.4 - Line Control.
1491 case tok::pp_line:
1492 // FIXME: implement #line
1493 DiscardUntilEndOfDirective();
1494 return;
1495
1496 // C99 6.10.5 - Error Directive.
1497 case tok::pp_error:
1498 return HandleUserDiagnosticDirective(Result, false);
1499
1500 // C99 6.10.6 - Pragma Directive.
1501 case tok::pp_pragma:
1502 return HandlePragmaDirective();
1503
1504 // GNU Extensions.
1505 case tok::pp_import:
1506 return HandleImportDirective(Result);
1507 case tok::pp_include_next:
1508 return HandleIncludeNextDirective(Result);
1509
1510 case tok::pp_warning:
1511 Diag(Result, diag::ext_pp_warning_directive);
1512 return HandleUserDiagnosticDirective(Result, true);
1513 case tok::pp_ident:
1514 return HandleIdentSCCSDirective(Result);
1515 case tok::pp_sccs:
1516 return HandleIdentSCCSDirective(Result);
1517 case tok::pp_assert:
1518 //isExtension = true; // FIXME: implement #assert
1519 break;
1520 case tok::pp_unassert:
1521 //isExtension = true; // FIXME: implement #unassert
1522 break;
1523
1524 // clang extensions.
1525 case tok::pp_define_target:
1526 return HandleDefineDirective(Result, true);
1527 case tok::pp_define_other_target:
1528 return HandleDefineOtherTargetDirective(Result);
1529 }
1530 break;
1531 }
1532
1533 // If we reached here, the preprocessing token is not valid!
1534 Diag(Result, diag::err_pp_invalid_directive);
1535
1536 // Read the rest of the PP line.
1537 DiscardUntilEndOfDirective();
1538
1539 // Okay, we're done parsing the directive.
1540}
1541
1542void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
1543 bool isWarning) {
1544 // Read the rest of the line raw. We do this because we don't want macros
1545 // to be expanded and we don't require that the tokens be valid preprocessing
1546 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1547 // collapse multiple consequtive white space between tokens, but this isn't
1548 // specified by the standard.
1549 std::string Message = CurLexer->ReadToEndOfLine();
1550
1551 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
1552 return Diag(Tok, DiagID, Message);
1553}
1554
1555/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1556///
1557void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1558 // Yes, this directive is an extension.
1559 Diag(Tok, diag::ext_pp_ident_directive);
1560
1561 // Read the string argument.
1562 Token StrTok;
1563 Lex(StrTok);
1564
1565 // If the token kind isn't a string, it's a malformed directive.
1566 if (StrTok.getKind() != tok::string_literal &&
1567 StrTok.getKind() != tok::wide_string_literal)
1568 return Diag(StrTok, diag::err_pp_malformed_ident);
1569
1570 // Verify that there is nothing after the string, other than EOM.
1571 CheckEndOfDirective("#ident");
1572
1573 if (Callbacks)
1574 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
1575}
1576
1577//===----------------------------------------------------------------------===//
1578// Preprocessor Include Directive Handling.
1579//===----------------------------------------------------------------------===//
1580
1581/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1582/// checked and spelled filename, e.g. as an operand of #include. This returns
1583/// true if the input filename was in <>'s or false if it were in ""'s. The
1584/// caller is expected to provide a buffer that is large enough to hold the
1585/// spelling of the filename, but is also expected to handle the case when
1586/// this method decides to use a different buffer.
1587bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
1588 const char *&BufStart,
1589 const char *&BufEnd) {
1590 // Get the text form of the filename.
1591 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1592
1593 // Make sure the filename is <x> or "x".
1594 bool isAngled;
1595 if (BufStart[0] == '<') {
1596 if (BufEnd[-1] != '>') {
1597 Diag(Loc, diag::err_pp_expects_filename);
1598 BufStart = 0;
1599 return true;
1600 }
1601 isAngled = true;
1602 } else if (BufStart[0] == '"') {
1603 if (BufEnd[-1] != '"') {
1604 Diag(Loc, diag::err_pp_expects_filename);
1605 BufStart = 0;
1606 return true;
1607 }
1608 isAngled = false;
1609 } else {
1610 Diag(Loc, diag::err_pp_expects_filename);
1611 BufStart = 0;
1612 return true;
1613 }
1614
1615 // Diagnose #include "" as invalid.
1616 if (BufEnd-BufStart <= 2) {
1617 Diag(Loc, diag::err_pp_empty_filename);
1618 BufStart = 0;
1619 return "";
1620 }
1621
1622 // Skip the brackets.
1623 ++BufStart;
1624 --BufEnd;
1625 return isAngled;
1626}
1627
1628/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1629/// from a macro as multiple tokens, which need to be glued together. This
1630/// occurs for code like:
1631/// #define FOO <a/b.h>
1632/// #include FOO
1633/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1634///
1635/// This code concatenates and consumes tokens up to the '>' token. It returns
1636/// false if the > was found, otherwise it returns true if it finds and consumes
1637/// the EOM marker.
1638static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
1639 Preprocessor &PP) {
1640 Token CurTok;
1641
1642 PP.Lex(CurTok);
1643 while (CurTok.getKind() != tok::eom) {
1644 // Append the spelling of this token to the buffer. If there was a space
1645 // before it, add it now.
1646 if (CurTok.hasLeadingSpace())
1647 FilenameBuffer.push_back(' ');
1648
1649 // Get the spelling of the token, directly into FilenameBuffer if possible.
1650 unsigned PreAppendSize = FilenameBuffer.size();
1651 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
1652
1653 const char *BufPtr = &FilenameBuffer[PreAppendSize];
1654 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
1655
1656 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1657 if (BufPtr != &FilenameBuffer[PreAppendSize])
1658 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1659
1660 // Resize FilenameBuffer to the correct size.
1661 if (CurTok.getLength() != ActualLen)
1662 FilenameBuffer.resize(PreAppendSize+ActualLen);
1663
1664 // If we found the '>' marker, return success.
1665 if (CurTok.getKind() == tok::greater)
1666 return false;
1667
1668 PP.Lex(CurTok);
1669 }
1670
1671 // If we hit the eom marker, emit an error and return true so that the caller
1672 // knows the EOM has been read.
1673 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
1674 return true;
1675}
1676
1677/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1678/// file to be included from the lexer, then include it! This is a common
1679/// routine with functionality shared between #include, #include_next and
1680/// #import.
1681void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
1682 const DirectoryLookup *LookupFrom,
1683 bool isImport) {
1684
1685 Token FilenameTok;
1686 CurLexer->LexIncludeFilename(FilenameTok);
1687
1688 // Reserve a buffer to get the spelling.
1689 llvm::SmallVector<char, 128> FilenameBuffer;
1690 const char *FilenameStart, *FilenameEnd;
1691
1692 switch (FilenameTok.getKind()) {
1693 case tok::eom:
1694 // If the token kind is EOM, the error has already been diagnosed.
1695 return;
1696
1697 case tok::angle_string_literal:
1698 case tok::string_literal: {
1699 FilenameBuffer.resize(FilenameTok.getLength());
1700 FilenameStart = &FilenameBuffer[0];
1701 unsigned Len = getSpelling(FilenameTok, FilenameStart);
1702 FilenameEnd = FilenameStart+Len;
1703 break;
1704 }
1705
1706 case tok::less:
1707 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1708 // case, glue the tokens together into FilenameBuffer and interpret those.
1709 FilenameBuffer.push_back('<');
1710 if (ConcatenateIncludeName(FilenameBuffer, *this))
1711 return; // Found <eom> but no ">"? Diagnostic already emitted.
1712 FilenameStart = &FilenameBuffer[0];
1713 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
1714 break;
1715 default:
1716 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1717 DiscardUntilEndOfDirective();
1718 return;
1719 }
1720
1721 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
1722 FilenameStart, FilenameEnd);
1723 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1724 // error.
1725 if (FilenameStart == 0) {
1726 DiscardUntilEndOfDirective();
1727 return;
1728 }
1729
1730 // Verify that there is nothing after the filename, other than EOM. Use the
1731 // preprocessor to lex this in case lexing the filename entered a macro.
1732 CheckEndOfDirective("#include");
1733
1734 // Check that we don't have infinite #include recursion.
1735 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
1736 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1737
1738 // Search include directories.
1739 const DirectoryLookup *CurDir;
1740 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
1741 isAngled, LookupFrom, CurDir);
1742 if (File == 0)
1743 return Diag(FilenameTok, diag::err_pp_file_not_found,
1744 std::string(FilenameStart, FilenameEnd));
1745
1746 // Ask HeaderInfo if we should enter this #include file.
1747 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1748 // If it returns true, #including this file will have no effect.
1749 return;
1750 }
1751
1752 // Look up the file, create a File ID for it.
1753 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
1754 if (FileID == 0)
1755 return Diag(FilenameTok, diag::err_pp_file_not_found,
1756 std::string(FilenameStart, FilenameEnd));
1757
1758 // Finally, if all is good, enter the new file!
1759 EnterSourceFile(FileID, CurDir);
1760}
1761
1762/// HandleIncludeNextDirective - Implements #include_next.
1763///
1764void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
1765 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
1766
1767 // #include_next is like #include, except that we start searching after
1768 // the current found directory. If we can't do this, issue a
1769 // diagnostic.
1770 const DirectoryLookup *Lookup = CurDirLookup;
1771 if (isInPrimaryFile()) {
1772 Lookup = 0;
1773 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1774 } else if (Lookup == 0) {
1775 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1776 } else {
1777 // Start looking up in the next directory.
1778 ++Lookup;
1779 }
1780
1781 return HandleIncludeDirective(IncludeNextTok, Lookup);
1782}
1783
1784/// HandleImportDirective - Implements #import.
1785///
1786void Preprocessor::HandleImportDirective(Token &ImportTok) {
1787 Diag(ImportTok, diag::ext_pp_import_directive);
1788
1789 return HandleIncludeDirective(ImportTok, 0, true);
1790}
1791
1792//===----------------------------------------------------------------------===//
1793// Preprocessor Macro Directive Handling.
1794//===----------------------------------------------------------------------===//
1795
1796/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1797/// definition has just been read. Lex the rest of the arguments and the
1798/// closing ), updating MI with what we learn. Return true if an error occurs
1799/// parsing the arg list.
1800bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1801 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
1802
1803 Token Tok;
1804 while (1) {
1805 LexUnexpandedToken(Tok);
1806 switch (Tok.getKind()) {
1807 case tok::r_paren:
1808 // Found the end of the argument list.
1809 if (Arguments.empty()) { // #define FOO()
1810 MI->setArgumentList(Arguments.begin(), Arguments.end());
1811 return false;
1812 }
1813 // Otherwise we have #define FOO(A,)
1814 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1815 return true;
1816 case tok::ellipsis: // #define X(... -> C99 varargs
1817 // Warn if use of C99 feature in non-C99 mode.
1818 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1819
1820 // Lex the token after the identifier.
1821 LexUnexpandedToken(Tok);
1822 if (Tok.getKind() != tok::r_paren) {
1823 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1824 return true;
1825 }
1826 // Add the __VA_ARGS__ identifier as an argument.
1827 Arguments.push_back(Ident__VA_ARGS__);
1828 MI->setIsC99Varargs();
1829 MI->setArgumentList(Arguments.begin(), Arguments.end());
1830 return false;
1831 case tok::eom: // #define X(
1832 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1833 return true;
1834 default:
1835 // Handle keywords and identifiers here to accept things like
1836 // #define Foo(for) for.
1837 IdentifierInfo *II = Tok.getIdentifierInfo();
1838 if (II == 0) {
1839 // #define X(1
1840 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1841 return true;
1842 }
1843
1844 // If this is already used as an argument, it is used multiple times (e.g.
1845 // #define X(A,A.
1846 if (std::find(Arguments.begin(), Arguments.end(), II) !=
1847 Arguments.end()) { // C99 6.10.3p6
1848 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1849 return true;
1850 }
1851
1852 // Add the argument to the macro info.
1853 Arguments.push_back(II);
1854
1855 // Lex the token after the identifier.
1856 LexUnexpandedToken(Tok);
1857
1858 switch (Tok.getKind()) {
1859 default: // #define X(A B
1860 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1861 return true;
1862 case tok::r_paren: // #define X(A)
1863 MI->setArgumentList(Arguments.begin(), Arguments.end());
1864 return false;
1865 case tok::comma: // #define X(A,
1866 break;
1867 case tok::ellipsis: // #define X(A... -> GCC extension
1868 // Diagnose extension.
1869 Diag(Tok, diag::ext_named_variadic_macro);
1870
1871 // Lex the token after the identifier.
1872 LexUnexpandedToken(Tok);
1873 if (Tok.getKind() != tok::r_paren) {
1874 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1875 return true;
1876 }
1877
1878 MI->setIsGNUVarargs();
1879 MI->setArgumentList(Arguments.begin(), Arguments.end());
1880 return false;
1881 }
1882 }
1883 }
1884}
1885
1886/// HandleDefineDirective - Implements #define. This consumes the entire macro
1887/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
1888/// true, then this is a "#define_target", otherwise this is a "#define".
1889///
1890void Preprocessor::HandleDefineDirective(Token &DefineTok,
1891 bool isTargetSpecific) {
1892 ++NumDefined;
1893
1894 Token MacroNameTok;
1895 ReadMacroName(MacroNameTok, 1);
1896
1897 // Error reading macro name? If so, diagnostic already issued.
1898 if (MacroNameTok.getKind() == tok::eom)
1899 return;
1900
1901 // If we are supposed to keep comments in #defines, reenable comment saving
1902 // mode.
1903 CurLexer->KeepCommentMode = KeepMacroComments;
1904
1905 // Create the new macro.
1906 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
1907 if (isTargetSpecific) MI->setIsTargetSpecific();
1908
1909 // If the identifier is an 'other target' macro, clear this bit.
1910 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1911
1912
1913 Token Tok;
1914 LexUnexpandedToken(Tok);
1915
1916 // If this is a function-like macro definition, parse the argument list,
1917 // marking each of the identifiers as being used as macro arguments. Also,
1918 // check other constraints on the first token of the macro body.
1919 if (Tok.getKind() == tok::eom) {
1920 // If there is no body to this macro, we have no special handling here.
1921 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
1922 // This is a function-like macro definition. Read the argument list.
1923 MI->setIsFunctionLike();
1924 if (ReadMacroDefinitionArgList(MI)) {
1925 // Forget about MI.
1926 delete MI;
1927 // Throw away the rest of the line.
1928 if (CurLexer->ParsingPreprocessorDirective)
1929 DiscardUntilEndOfDirective();
1930 return;
1931 }
1932
1933 // Read the first token after the arg list for down below.
1934 LexUnexpandedToken(Tok);
1935 } else if (!Tok.hasLeadingSpace()) {
1936 // C99 requires whitespace between the macro definition and the body. Emit
1937 // a diagnostic for something like "#define X+".
1938 if (Features.C99) {
1939 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
1940 } else {
1941 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1942 // one in some cases!
1943 }
1944 } else {
1945 // This is a normal token with leading space. Clear the leading space
1946 // marker on the first token to get proper expansion.
1947 Tok.clearFlag(Token::LeadingSpace);
1948 }
1949
1950 // If this is a definition of a variadic C99 function-like macro, not using
1951 // the GNU named varargs extension, enabled __VA_ARGS__.
1952
1953 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1954 // This gets unpoisoned where it is allowed.
1955 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1956 if (MI->isC99Varargs())
1957 Ident__VA_ARGS__->setIsPoisoned(false);
1958
1959 // Read the rest of the macro body.
1960 if (MI->isObjectLike()) {
1961 // Object-like macros are very simple, just read their body.
1962 while (Tok.getKind() != tok::eom) {
1963 MI->AddTokenToBody(Tok);
1964 // Get the next token of the macro.
1965 LexUnexpandedToken(Tok);
1966 }
1967
1968 } else {
1969 // Otherwise, read the body of a function-like macro. This has to validate
1970 // the # (stringize) operator.
1971 while (Tok.getKind() != tok::eom) {
1972 MI->AddTokenToBody(Tok);
1973
1974 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
1975 // parameters in function-like macro expansions.
1976 if (Tok.getKind() != tok::hash) {
1977 // Get the next token of the macro.
1978 LexUnexpandedToken(Tok);
1979 continue;
1980 }
1981
1982 // Get the next token of the macro.
1983 LexUnexpandedToken(Tok);
1984
1985 // Not a macro arg identifier?
1986 if (!Tok.getIdentifierInfo() ||
1987 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1988 Diag(Tok, diag::err_pp_stringize_not_parameter);
1989 delete MI;
1990
1991 // Disable __VA_ARGS__ again.
1992 Ident__VA_ARGS__->setIsPoisoned(true);
1993 return;
1994 }
1995
1996 // Things look ok, add the param name token to the macro.
1997 MI->AddTokenToBody(Tok);
1998
1999 // Get the next token of the macro.
2000 LexUnexpandedToken(Tok);
2001 }
2002 }
2003
2004
2005 // Disable __VA_ARGS__ again.
2006 Ident__VA_ARGS__->setIsPoisoned(true);
2007
2008 // Check that there is no paste (##) operator at the begining or end of the
2009 // replacement list.
2010 unsigned NumTokens = MI->getNumTokens();
2011 if (NumTokens != 0) {
2012 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
2013 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
2014 delete MI;
2015 return;
2016 }
2017 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
2018 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
2019 delete MI;
2020 return;
2021 }
2022 }
2023
2024 // If this is the primary source file, remember that this macro hasn't been
2025 // used yet.
2026 if (isInPrimaryFile())
2027 MI->setIsUsed(false);
2028
2029 // Finally, if this identifier already had a macro defined for it, verify that
2030 // the macro bodies are identical and free the old definition.
2031 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
2032 if (!OtherMI->isUsed())
2033 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
2034
2035 // Macros must be identical. This means all tokes and whitespace separation
2036 // must be the same. C99 6.10.3.2.
2037 if (!MI->isIdenticalTo(*OtherMI, *this)) {
2038 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
2039 MacroNameTok.getIdentifierInfo()->getName());
2040 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
2041 }
2042 delete OtherMI;
2043 }
2044
2045 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
2046}
2047
2048/// HandleDefineOtherTargetDirective - Implements #define_other_target.
2049void Preprocessor::HandleDefineOtherTargetDirective(Token &Tok) {
2050 Token MacroNameTok;
2051 ReadMacroName(MacroNameTok, 1);
2052
2053 // Error reading macro name? If so, diagnostic already issued.
2054 if (MacroNameTok.getKind() == tok::eom)
2055 return;
2056
2057 // Check to see if this is the last token on the #undef line.
2058 CheckEndOfDirective("#define_other_target");
2059
2060 // If there is already a macro defined by this name, turn it into a
2061 // target-specific define.
2062 if (MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
2063 MI->setIsTargetSpecific(true);
2064 return;
2065 }
2066
2067 // Mark the identifier as being a macro on some other target.
2068 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
2069}
2070
2071
2072/// HandleUndefDirective - Implements #undef.
2073///
2074void Preprocessor::HandleUndefDirective(Token &UndefTok) {
2075 ++NumUndefined;
2076
2077 Token MacroNameTok;
2078 ReadMacroName(MacroNameTok, 2);
2079
2080 // Error reading macro name? If so, diagnostic already issued.
2081 if (MacroNameTok.getKind() == tok::eom)
2082 return;
2083
2084 // Check to see if this is the last token on the #undef line.
2085 CheckEndOfDirective("#undef");
2086
2087 // Okay, we finally have a valid identifier to undef.
2088 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
2089
2090 // #undef untaints an identifier if it were marked by define_other_target.
2091 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2092
2093 // If the macro is not defined, this is a noop undef, just return.
2094 if (MI == 0) return;
2095
2096 if (!MI->isUsed())
2097 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
2098
2099 // Free macro definition.
2100 delete MI;
2101 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
2102}
2103
2104
2105//===----------------------------------------------------------------------===//
2106// Preprocessor Conditional Directive Handling.
2107//===----------------------------------------------------------------------===//
2108
2109/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
2110/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
2111/// if any tokens have been returned or pp-directives activated before this
2112/// #ifndef has been lexed.
2113///
2114void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
2115 bool ReadAnyTokensBeforeDirective) {
2116 ++NumIf;
2117 Token DirectiveTok = Result;
2118
2119 Token MacroNameTok;
2120 ReadMacroName(MacroNameTok);
2121
2122 // Error reading macro name? If so, diagnostic already issued.
2123 if (MacroNameTok.getKind() == tok::eom)
2124 return;
2125
2126 // Check to see if this is the last token on the #if[n]def line.
2127 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
2128
2129 // If the start of a top-level #ifdef, inform MIOpt.
2130 if (!ReadAnyTokensBeforeDirective &&
2131 CurLexer->getConditionalStackDepth() == 0) {
2132 assert(isIfndef && "#ifdef shouldn't reach here");
2133 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
2134 }
2135
2136 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
2137 MacroInfo *MI = MII->getMacroInfo();
2138
2139 // If there is a macro, process it.
2140 if (MI) {
2141 // Mark it used.
2142 MI->setIsUsed(true);
2143
2144 // If this is the first use of a target-specific macro, warn about it.
2145 if (MI->isTargetSpecific()) {
2146 MI->setIsTargetSpecific(false); // Don't warn on second use.
2147 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2148 diag::port_target_macro_use);
2149 }
2150 } else {
2151 // Use of a target-specific macro for some other target? If so, warn.
2152 if (MII->isOtherTargetMacro()) {
2153 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
2154 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2155 diag::port_target_macro_use);
2156 }
2157 }
2158
2159 // Should we include the stuff contained by this directive?
2160 if (!MI == isIfndef) {
2161 // Yes, remember that we are inside a conditional, then lex the next token.
2162 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
2163 /*foundnonskip*/true, /*foundelse*/false);
2164 } else {
2165 // No, skip the contents of this block and return the first token after it.
2166 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2167 /*Foundnonskip*/false,
2168 /*FoundElse*/false);
2169 }
2170}
2171
2172/// HandleIfDirective - Implements the #if directive.
2173///
2174void Preprocessor::HandleIfDirective(Token &IfToken,
2175 bool ReadAnyTokensBeforeDirective) {
2176 ++NumIf;
2177
2178 // Parse and evaluation the conditional expression.
2179 IdentifierInfo *IfNDefMacro = 0;
2180 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2181
2182 // Should we include the stuff contained by this directive?
2183 if (ConditionalTrue) {
2184 // If this condition is equivalent to #ifndef X, and if this is the first
2185 // directive seen, handle it for the multiple-include optimization.
2186 if (!ReadAnyTokensBeforeDirective &&
2187 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2188 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2189
2190 // Yes, remember that we are inside a conditional, then lex the next token.
2191 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
2192 /*foundnonskip*/true, /*foundelse*/false);
2193 } else {
2194 // No, skip the contents of this block and return the first token after it.
2195 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
2196 /*FoundElse*/false);
2197 }
2198}
2199
2200/// HandleEndifDirective - Implements the #endif directive.
2201///
2202void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2203 ++NumEndif;
2204
2205 // Check that this is the whole directive.
2206 CheckEndOfDirective("#endif");
2207
2208 PPConditionalInfo CondInfo;
2209 if (CurLexer->popConditionalLevel(CondInfo)) {
2210 // No conditionals on the stack: this is an #endif without an #if.
2211 return Diag(EndifToken, diag::err_pp_endif_without_if);
2212 }
2213
2214 // If this the end of a top-level #endif, inform MIOpt.
2215 if (CurLexer->getConditionalStackDepth() == 0)
2216 CurLexer->MIOpt.ExitTopLevelConditional();
2217
2218 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
2219 "This code should only be reachable in the non-skipping case!");
2220}
2221
2222
2223void Preprocessor::HandleElseDirective(Token &Result) {
2224 ++NumElse;
2225
2226 // #else directive in a non-skipping conditional... start skipping.
2227 CheckEndOfDirective("#else");
2228
2229 PPConditionalInfo CI;
2230 if (CurLexer->popConditionalLevel(CI))
2231 return Diag(Result, diag::pp_err_else_without_if);
2232
2233 // If this is a top-level #else, inform the MIOpt.
2234 if (CurLexer->getConditionalStackDepth() == 0)
2235 CurLexer->MIOpt.FoundTopLevelElse();
2236
2237 // If this is a #else with a #else before it, report the error.
2238 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
2239
2240 // Finally, skip the rest of the contents of this block and return the first
2241 // token after it.
2242 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2243 /*FoundElse*/true);
2244}
2245
2246void Preprocessor::HandleElifDirective(Token &ElifToken) {
2247 ++NumElse;
2248
2249 // #elif directive in a non-skipping conditional... start skipping.
2250 // We don't care what the condition is, because we will always skip it (since
2251 // the block immediately before it was included).
2252 DiscardUntilEndOfDirective();
2253
2254 PPConditionalInfo CI;
2255 if (CurLexer->popConditionalLevel(CI))
2256 return Diag(ElifToken, diag::pp_err_elif_without_if);
2257
2258 // If this is a top-level #elif, inform the MIOpt.
2259 if (CurLexer->getConditionalStackDepth() == 0)
2260 CurLexer->MIOpt.FoundTopLevelElse();
2261
2262 // If this is a #elif with a #else before it, report the error.
2263 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
2264
2265 // Finally, skip the rest of the contents of this block and return the first
2266 // token after it.
2267 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2268 /*FoundElse*/CI.FoundElse);
2269}
2270