1 //===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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[DNI] - 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 "MacroArgs.h"
30 #include "clang/Lex/ExternalPreprocessorSource.h"
31 #include "clang/Lex/HeaderSearch.h"
32 #include "clang/Lex/MacroInfo.h"
33 #include "clang/Lex/Pragma.h"
34 #include "clang/Lex/PreprocessingRecord.h"
35 #include "clang/Lex/ScratchBuffer.h"
36 #include "clang/Lex/LexDiagnostic.h"
37 #include "clang/Lex/CodeCompletionHandler.h"
38 #include "clang/Basic/SourceManager.h"
39 #include "clang/Basic/FileManager.h"
40 #include "clang/Basic/TargetInfo.h"
41 #include "llvm/ADT/APFloat.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/raw_ostream.h"
45 using namespace clang;
46 
47 //===----------------------------------------------------------------------===//
48 ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
49 
50 Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
51                            const TargetInfo &target, SourceManager &SM,
52                            HeaderSearch &Headers,
53                            IdentifierInfoLookup* IILookup,
54                            bool OwnsHeaders)
55   : Diags(&diags), Features(opts), Target(target),FileMgr(Headers.getFileMgr()),
56     SourceMgr(SM),
57     HeaderInfo(Headers), ExternalSource(0),
58     Identifiers(opts, IILookup), BuiltinInfo(Target), CodeComplete(0),
59     CodeCompletionFile(0), SkipMainFilePreamble(0, true), CurPPLexer(0),
60     CurDirLookup(0), Callbacks(0), MacroArgCache(0), Record(0), MIChainHead(0),
61     MICache(0) {
62   ScratchBuf = new ScratchBuffer(SourceMgr);
63   CounterValue = 0; // __COUNTER__ starts at 0.
64   OwnsHeaderSearch = OwnsHeaders;
65 
66   // Clear stats.
67   NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
68   NumIf = NumElse = NumEndif = 0;
69   NumEnteredSourceFiles = 0;
70   NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
71   NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
72   MaxIncludeStackDepth = 0;
73   NumSkipped = 0;
74 
75   // Default to discarding comments.
76   KeepComments = false;
77   KeepMacroComments = false;
78 
79   // Macro expansion is enabled.
80   DisableMacroExpansion = false;
81   InMacroArgs = false;
82   NumCachedTokenLexers = 0;
83 
84   CachedLexPos = 0;
85 
86   // We haven't read anything from the external source.
87   ReadMacrosFromExternalSource = false;
88 
89   // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
90   // This gets unpoisoned where it is allowed.
91   (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
92 
93   // Initialize the pragma handlers.
94   PragmaHandlers = new PragmaNamespace(llvm::StringRef());
95   RegisterBuiltinPragmas();
96 
97   // Initialize builtin macros like __LINE__ and friends.
98   RegisterBuiltinMacros();
99 }
100 
101 Preprocessor::~Preprocessor() {
102   assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
103 
104   while (!IncludeMacroStack.empty()) {
105     delete IncludeMacroStack.back().TheLexer;
106     delete IncludeMacroStack.back().TheTokenLexer;
107     IncludeMacroStack.pop_back();
108   }
109 
110   // Free any macro definitions.
111   for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next)
112     I->MI.Destroy();
113 
114   // Free any cached macro expanders.
115   for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
116     delete TokenLexerCache[i];
117 
118   // Free any cached MacroArgs.
119   for (MacroArgs *ArgList = MacroArgCache; ArgList; )
120     ArgList = ArgList->deallocate();
121 
122   // Release pragma information.
123   delete PragmaHandlers;
124 
125   // Delete the scratch buffer info.
126   delete ScratchBuf;
127 
128   // Delete the header search info, if we own it.
129   if (OwnsHeaderSearch)
130     delete &HeaderInfo;
131 
132   delete Callbacks;
133 }
134 
135 void Preprocessor::setPTHManager(PTHManager* pm) {
136   PTH.reset(pm);
137   FileMgr.addStatCache(PTH->createStatCache());
138 }
139 
140 void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
141   llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
142                << getSpelling(Tok) << "'";
143 
144   if (!DumpFlags) return;
145 
146   llvm::errs() << "\t";
147   if (Tok.isAtStartOfLine())
148     llvm::errs() << " [StartOfLine]";
149   if (Tok.hasLeadingSpace())
150     llvm::errs() << " [LeadingSpace]";
151   if (Tok.isExpandDisabled())
152     llvm::errs() << " [ExpandDisabled]";
153   if (Tok.needsCleaning()) {
154     const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
155     llvm::errs() << " [UnClean='" << llvm::StringRef(Start, Tok.getLength())
156                  << "']";
157   }
158 
159   llvm::errs() << "\tLoc=<";
160   DumpLocation(Tok.getLocation());
161   llvm::errs() << ">";
162 }
163 
164 void Preprocessor::DumpLocation(SourceLocation Loc) const {
165   Loc.dump(SourceMgr);
166 }
167 
168 void Preprocessor::DumpMacro(const MacroInfo &MI) const {
169   llvm::errs() << "MACRO: ";
170   for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
171     DumpToken(MI.getReplacementToken(i));
172     llvm::errs() << "  ";
173   }
174   llvm::errs() << "\n";
175 }
176 
177 void Preprocessor::PrintStats() {
178   llvm::errs() << "\n*** Preprocessor Stats:\n";
179   llvm::errs() << NumDirectives << " directives found:\n";
180   llvm::errs() << "  " << NumDefined << " #define.\n";
181   llvm::errs() << "  " << NumUndefined << " #undef.\n";
182   llvm::errs() << "  #include/#include_next/#import:\n";
183   llvm::errs() << "    " << NumEnteredSourceFiles << " source files entered.\n";
184   llvm::errs() << "    " << MaxIncludeStackDepth << " max include stack depth\n";
185   llvm::errs() << "  " << NumIf << " #if/#ifndef/#ifdef.\n";
186   llvm::errs() << "  " << NumElse << " #else/#elif.\n";
187   llvm::errs() << "  " << NumEndif << " #endif.\n";
188   llvm::errs() << "  " << NumPragma << " #pragma.\n";
189   llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
190 
191   llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
192              << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
193              << NumFastMacroExpanded << " on the fast path.\n";
194   llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
195              << " token paste (##) operations performed, "
196              << NumFastTokenPaste << " on the fast path.\n";
197 }
198 
199 Preprocessor::macro_iterator
200 Preprocessor::macro_begin(bool IncludeExternalMacros) const {
201   if (IncludeExternalMacros && ExternalSource &&
202       !ReadMacrosFromExternalSource) {
203     ReadMacrosFromExternalSource = true;
204     ExternalSource->ReadDefinedMacros();
205   }
206 
207   return Macros.begin();
208 }
209 
210 Preprocessor::macro_iterator
211 Preprocessor::macro_end(bool IncludeExternalMacros) const {
212   if (IncludeExternalMacros && ExternalSource &&
213       !ReadMacrosFromExternalSource) {
214     ReadMacrosFromExternalSource = true;
215     ExternalSource->ReadDefinedMacros();
216   }
217 
218   return Macros.end();
219 }
220 
221 bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
222                                           unsigned TruncateAtLine,
223                                           unsigned TruncateAtColumn) {
224   using llvm::MemoryBuffer;
225 
226   CodeCompletionFile = File;
227 
228   // Okay to clear out the code-completion point by passing NULL.
229   if (!CodeCompletionFile)
230     return false;
231 
232   // Load the actual file's contents.
233   bool Invalid = false;
234   const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
235   if (Invalid)
236     return true;
237 
238   // Find the byte position of the truncation point.
239   const char *Position = Buffer->getBufferStart();
240   for (unsigned Line = 1; Line < TruncateAtLine; ++Line) {
241     for (; *Position; ++Position) {
242       if (*Position != '\r' && *Position != '\n')
243         continue;
244 
245       // Eat \r\n or \n\r as a single line.
246       if ((Position[1] == '\r' || Position[1] == '\n') &&
247           Position[0] != Position[1])
248         ++Position;
249       ++Position;
250       break;
251     }
252   }
253 
254   Position += TruncateAtColumn - 1;
255 
256   // Truncate the buffer.
257   if (Position < Buffer->getBufferEnd()) {
258     llvm::StringRef Data(Buffer->getBufferStart(),
259                          Position-Buffer->getBufferStart());
260     MemoryBuffer *TruncatedBuffer
261       = MemoryBuffer::getMemBufferCopy(Data, Buffer->getBufferIdentifier());
262     SourceMgr.overrideFileContents(File, TruncatedBuffer);
263   }
264 
265   return false;
266 }
267 
268 bool Preprocessor::isCodeCompletionFile(SourceLocation FileLoc) const {
269   return CodeCompletionFile && FileLoc.isFileID() &&
270     SourceMgr.getFileEntryForID(SourceMgr.getFileID(FileLoc))
271       == CodeCompletionFile;
272 }
273 
274 void Preprocessor::CodeCompleteNaturalLanguage() {
275   SetCodeCompletionPoint(0, 0, 0);
276   getDiagnostics().setSuppressAllDiagnostics(true);
277   if (CodeComplete)
278     CodeComplete->CodeCompleteNaturalLanguage();
279 }
280 
281 /// getSpelling - This method is used to get the spelling of a token into a
282 /// SmallVector. Note that the returned StringRef may not point to the
283 /// supplied buffer if a copy can be avoided.
284 llvm::StringRef Preprocessor::getSpelling(const Token &Tok,
285                                           llvm::SmallVectorImpl<char> &Buffer,
286                                           bool *Invalid) const {
287   // NOTE: this has to be checked *before* testing for an IdentifierInfo.
288   if (Tok.isNot(tok::raw_identifier)) {
289     // Try the fast path.
290     if (const IdentifierInfo *II = Tok.getIdentifierInfo())
291       return II->getName();
292   }
293 
294   // Resize the buffer if we need to copy into it.
295   if (Tok.needsCleaning())
296     Buffer.resize(Tok.getLength());
297 
298   const char *Ptr = Buffer.data();
299   unsigned Len = getSpelling(Tok, Ptr, Invalid);
300   return llvm::StringRef(Ptr, Len);
301 }
302 
303 /// CreateString - Plop the specified string into a scratch buffer and return a
304 /// location for it.  If specified, the source location provides a source
305 /// location for the token.
306 void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok,
307                                 SourceLocation InstantiationLoc) {
308   Tok.setLength(Len);
309 
310   const char *DestPtr;
311   SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr);
312 
313   if (InstantiationLoc.isValid())
314     Loc = SourceMgr.createInstantiationLoc(Loc, InstantiationLoc,
315                                            InstantiationLoc, Len);
316   Tok.setLocation(Loc);
317 
318   // If this is a raw identifier or a literal token, set the pointer data.
319   if (Tok.is(tok::raw_identifier))
320     Tok.setRawIdentifierData(DestPtr);
321   else if (Tok.isLiteral())
322     Tok.setLiteralData(DestPtr);
323 }
324 
325 
326 
327 //===----------------------------------------------------------------------===//
328 // Preprocessor Initialization Methods
329 //===----------------------------------------------------------------------===//
330 
331 
332 /// EnterMainSourceFile - Enter the specified FileID as the main source file,
333 /// which implicitly adds the builtin defines etc.
334 void Preprocessor::EnterMainSourceFile() {
335   // We do not allow the preprocessor to reenter the main file.  Doing so will
336   // cause FileID's to accumulate information from both runs (e.g. #line
337   // information) and predefined macros aren't guaranteed to be set properly.
338   assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
339   FileID MainFileID = SourceMgr.getMainFileID();
340 
341   // Enter the main file source buffer.
342   EnterSourceFile(MainFileID, 0, SourceLocation());
343 
344   // If we've been asked to skip bytes in the main file (e.g., as part of a
345   // precompiled preamble), do so now.
346   if (SkipMainFilePreamble.first > 0)
347     CurLexer->SkipBytes(SkipMainFilePreamble.first,
348                         SkipMainFilePreamble.second);
349 
350   // Tell the header info that the main file was entered.  If the file is later
351   // #imported, it won't be re-entered.
352   if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
353     HeaderInfo.IncrementIncludeCount(FE);
354 
355   // Preprocess Predefines to populate the initial preprocessor state.
356   llvm::MemoryBuffer *SB =
357     llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
358   assert(SB && "Cannot create predefined source buffer");
359   FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
360   assert(!FID.isInvalid() && "Could not create FileID for predefines?");
361 
362   // Start parsing the predefines.
363   EnterSourceFile(FID, 0, SourceLocation());
364 }
365 
366 void Preprocessor::EndSourceFile() {
367   // Notify the client that we reached the end of the source file.
368   if (Callbacks)
369     Callbacks->EndOfMainFile();
370 }
371 
372 //===----------------------------------------------------------------------===//
373 // Lexer Event Handling.
374 //===----------------------------------------------------------------------===//
375 
376 /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
377 /// identifier information for the token and install it into the token,
378 /// updating the token kind accordingly.
379 IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
380   assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!");
381 
382   // Look up this token, see if it is a macro, or if it is a language keyword.
383   IdentifierInfo *II;
384   if (!Identifier.needsCleaning()) {
385     // No cleaning needed, just use the characters from the lexed buffer.
386     II = getIdentifierInfo(llvm::StringRef(Identifier.getRawIdentifierData(),
387                                            Identifier.getLength()));
388   } else {
389     // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
390     llvm::SmallString<64> IdentifierBuffer;
391     llvm::StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
392     II = getIdentifierInfo(CleanedStr);
393   }
394 
395   // Update the token info (identifier info and appropriate token kind).
396   Identifier.setIdentifierInfo(II);
397   Identifier.setKind(II->getTokenID());
398 
399   return II;
400 }
401 
402 
403 /// HandleIdentifier - This callback is invoked when the lexer reads an
404 /// identifier.  This callback looks up the identifier in the map and/or
405 /// potentially macro expands it or turns it into a named token (like 'for').
406 ///
407 /// Note that callers of this method are guarded by checking the
408 /// IdentifierInfo's 'isHandleIdentifierCase' bit.  If this method changes, the
409 /// IdentifierInfo methods that compute these properties will need to change to
410 /// match.
411 void Preprocessor::HandleIdentifier(Token &Identifier) {
412   assert(Identifier.getIdentifierInfo() &&
413          "Can't handle identifiers without identifier info!");
414 
415   IdentifierInfo &II = *Identifier.getIdentifierInfo();
416 
417   // If this identifier was poisoned, and if it was not produced from a macro
418   // expansion, emit an error.
419   if (II.isPoisoned() && CurPPLexer) {
420     if (&II != Ident__VA_ARGS__)   // We warn about __VA_ARGS__ with poisoning.
421       Diag(Identifier, diag::err_pp_used_poisoned_id);
422     else
423       Diag(Identifier, diag::ext_pp_bad_vaargs_use);
424   }
425 
426   // If this is a macro to be expanded, do it.
427   if (MacroInfo *MI = getMacroInfo(&II)) {
428     if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
429       if (MI->isEnabled()) {
430         if (!HandleMacroExpandedIdentifier(Identifier, MI))
431           return;
432       } else {
433         // C99 6.10.3.4p2 says that a disabled macro may never again be
434         // expanded, even if it's in a context where it could be expanded in the
435         // future.
436         Identifier.setFlag(Token::DisableExpand);
437       }
438     }
439   }
440 
441   // C++ 2.11p2: If this is an alternative representation of a C++ operator,
442   // then we act as if it is the actual operator and not the textual
443   // representation of it.
444   if (II.isCPlusPlusOperatorKeyword())
445     Identifier.setIdentifierInfo(0);
446 
447   // If this is an extension token, diagnose its use.
448   // We avoid diagnosing tokens that originate from macro definitions.
449   // FIXME: This warning is disabled in cases where it shouldn't be,
450   // like "#define TY typeof", "TY(1) x".
451   if (II.isExtensionToken() && !DisableMacroExpansion)
452     Diag(Identifier, diag::ext_token_used);
453 }
454 
455 void Preprocessor::AddCommentHandler(CommentHandler *Handler) {
456   assert(Handler && "NULL comment handler");
457   assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
458          CommentHandlers.end() && "Comment handler already registered");
459   CommentHandlers.push_back(Handler);
460 }
461 
462 void Preprocessor::RemoveCommentHandler(CommentHandler *Handler) {
463   std::vector<CommentHandler *>::iterator Pos
464   = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
465   assert(Pos != CommentHandlers.end() && "Comment handler not registered");
466   CommentHandlers.erase(Pos);
467 }
468 
469 bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
470   bool AnyPendingTokens = false;
471   for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
472        HEnd = CommentHandlers.end();
473        H != HEnd; ++H) {
474     if ((*H)->HandleComment(*this, Comment))
475       AnyPendingTokens = true;
476   }
477   if (!AnyPendingTokens || getCommentRetentionState())
478     return false;
479   Lex(result);
480   return true;
481 }
482 
483 CommentHandler::~CommentHandler() { }
484 
485 CodeCompletionHandler::~CodeCompletionHandler() { }
486 
487 void Preprocessor::createPreprocessingRecord() {
488   if (Record)
489     return;
490 
491   Record = new PreprocessingRecord;
492   addPPCallbacks(Record);
493 }
494