ASTUnit.h revision 5f808c2bfe2f95c984029d76deb4aaebcad30cbc
1//===--- ASTUnit.h - ASTUnit utility ----------------------------*- C++ -*-===// 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// ASTUnit utility class. 11// 12//===----------------------------------------------------------------------===// 13 14#ifndef LLVM_CLANG_FRONTEND_ASTUNIT_H 15#define LLVM_CLANG_FRONTEND_ASTUNIT_H 16 17#include "clang/Index/ASTLocation.h" 18#include "clang/Frontend/PCHBitCodes.h" 19#include "clang/Sema/Sema.h" 20#include "clang/Lex/PreprocessingRecord.h" 21#include "clang/Basic/SourceManager.h" 22#include "clang/Basic/FileManager.h" 23#include "clang-c/Index.h" 24#include "llvm/ADT/IntrusiveRefCntPtr.h" 25#include "llvm/ADT/OwningPtr.h" 26#include "llvm/ADT/SmallVector.h" 27#include "llvm/ADT/StringMap.h" 28#include "llvm/ADT/StringSet.h" 29#include "llvm/System/Path.h" 30#include "llvm/Support/Timer.h" 31#include <map> 32#include <string> 33#include <vector> 34#include <cassert> 35#include <utility> 36#include <sys/types.h> 37 38namespace llvm { 39 class MemoryBuffer; 40} 41 42namespace clang { 43class ASTContext; 44class CodeCompleteConsumer; 45class CompilerInvocation; 46class Decl; 47class Diagnostic; 48class FileEntry; 49class FileManager; 50class HeaderSearch; 51class Preprocessor; 52class SourceManager; 53class TargetInfo; 54 55using namespace idx; 56 57/// \brief Utility class for loading a ASTContext from a PCH file. 58/// 59class ASTUnit { 60public: 61 typedef std::map<FileID, std::vector<PreprocessedEntity *> > 62 PreprocessedEntitiesByFileMap; 63private: 64 llvm::IntrusiveRefCntPtr<Diagnostic> Diagnostics; 65 llvm::OwningPtr<FileManager> FileMgr; 66 llvm::OwningPtr<SourceManager> SourceMgr; 67 llvm::OwningPtr<HeaderSearch> HeaderInfo; 68 llvm::OwningPtr<TargetInfo> Target; 69 llvm::OwningPtr<Preprocessor> PP; 70 llvm::OwningPtr<ASTContext> Ctx; 71 72 /// \brief The AST consumer that received information about the translation 73 /// unit as it was parsed or loaded. 74 llvm::OwningPtr<ASTConsumer> Consumer; 75 76 /// \brief The semantic analysis object used to type-check the translation 77 /// unit. 78 llvm::OwningPtr<Sema> TheSema; 79 80 /// Optional owned invocation, just used to make the invocation used in 81 /// LoadFromCommandLine available. 82 llvm::OwningPtr<CompilerInvocation> Invocation; 83 84 // OnlyLocalDecls - when true, walking this AST should only visit declarations 85 // that come from the AST itself, not from included precompiled headers. 86 // FIXME: This is temporary; eventually, CIndex will always do this. 87 bool OnlyLocalDecls; 88 89 /// \brief Whether to capture any diagnostics produced. 90 bool CaptureDiagnostics; 91 92 /// \brief Track whether the main file was loaded from an AST or not. 93 bool MainFileIsAST; 94 95 /// \brief Whether this AST represents a complete translation unit. 96 bool CompleteTranslationUnit; 97 98 /// Track the top-level decls which appeared in an ASTUnit which was loaded 99 /// from a source file. 100 // 101 // FIXME: This is just an optimization hack to avoid deserializing large parts 102 // of a PCH file when using the Index library on an ASTUnit loaded from 103 // source. In the long term we should make the Index library use efficient and 104 // more scalable search mechanisms. 105 std::vector<Decl*> TopLevelDecls; 106 107 /// The name of the original source file used to generate this ASTUnit. 108 std::string OriginalSourceFile; 109 110 // Critical optimization when using clang_getCursor(). 111 ASTLocation LastLoc; 112 113 /// \brief The set of diagnostics produced when creating this 114 /// translation unit. 115 llvm::SmallVector<StoredDiagnostic, 4> StoredDiagnostics; 116 117 /// \brief Temporary files that should be removed when the ASTUnit is 118 /// destroyed. 119 llvm::SmallVector<llvm::sys::Path, 4> TemporaryFiles; 120 121 /// \brief A mapping from file IDs to the set of preprocessed entities 122 /// stored in that file. 123 /// 124 /// FIXME: This is just an optimization hack to avoid searching through 125 /// many preprocessed entities during cursor traversal in the CIndex library. 126 /// Ideally, we would just be able to perform a binary search within the 127 /// list of preprocessed entities. 128 PreprocessedEntitiesByFileMap PreprocessedEntitiesByFile; 129 130 /// \brief Simple hack to allow us to assert that ASTUnit is not being 131 /// used concurrently, which is not supported. 132 /// 133 /// Clients should create instances of the ConcurrencyCheck class whenever 134 /// using the ASTUnit in a way that isn't intended to be concurrent, which is 135 /// just about any usage. 136 unsigned int ConcurrencyCheckValue; 137 static const unsigned int CheckLocked = 28573289; 138 static const unsigned int CheckUnlocked = 9803453; 139 140 /// \brief Counter that determines when we want to try building a 141 /// precompiled preamble. 142 /// 143 /// If zero, we will never build a precompiled preamble. Otherwise, 144 /// it's treated as a counter that decrements each time we reparse 145 /// without the benefit of a precompiled preamble. When it hits 1, 146 /// we'll attempt to rebuild the precompiled header. This way, if 147 /// building the precompiled preamble fails, we won't try again for 148 /// some number of calls. 149 unsigned PreambleRebuildCounter; 150 151 /// \brief The file in which the precompiled preamble is stored. 152 std::string PreambleFile; 153 154 /// \brief The contents of the preamble that has been precompiled to 155 /// \c PreambleFile. 156 std::vector<char> Preamble; 157 158 /// \brief Whether the preamble ends at the start of a new line. 159 /// 160 /// Used to inform the lexer as to whether it's starting at the beginning of 161 /// a line after skipping the preamble. 162 bool PreambleEndsAtStartOfLine; 163 164 /// \brief The size of the source buffer that we've reserved for the main 165 /// file within the precompiled preamble. 166 unsigned PreambleReservedSize; 167 168 /// \brief Keeps track of the files that were used when computing the 169 /// preamble, with both their buffer size and their modification time. 170 /// 171 /// If any of the files have changed from one compile to the next, 172 /// the preamble must be thrown away. 173 llvm::StringMap<std::pair<off_t, time_t> > FilesInPreamble; 174 175 /// \brief When non-NULL, this is the buffer used to store the contents of 176 /// the main file when it has been padded for use with the precompiled 177 /// preamble. 178 llvm::MemoryBuffer *SavedMainFileBuffer; 179 180 /// \brief The number of warnings that occurred while parsing the preamble. 181 /// 182 /// This value will be used to restore the state of the \c Diagnostic object 183 /// when re-using the precompiled preamble. Note that only the 184 /// number of warnings matters, since we will not save the preamble 185 /// when any errors are present. 186 unsigned NumWarningsInPreamble; 187 188 /// \brief The number of diagnostics that were stored when parsing 189 /// the precompiled preamble. 190 /// 191 /// This value is used to determine how many of the stored 192 /// diagnostics should be retained when reparsing in the presence of 193 /// a precompiled preamble. 194 unsigned NumStoredDiagnosticsInPreamble; 195 196 /// \brief The group of timers associated with this translation unit. 197 llvm::OwningPtr<llvm::TimerGroup> TimerGroup; 198 199 /// \brief A list of the PCH ID numbers for each of the top-level 200 /// declarations parsed within the precompiled preamble. 201 std::vector<pch::DeclID> TopLevelDeclsInPreamble; 202 203 /// 204 /// \defgroup CodeCompleteCaching Code-completion caching 205 /// 206 /// \{ 207 /// 208 209 /// \brief Whether we should be caching code-completion results. 210 bool ShouldCacheCodeCompletionResults; 211 212public: 213 /// \brief A cached code-completion result, which may be introduced in one of 214 /// many different contexts. 215 struct CachedCodeCompletionResult { 216 /// \brief The code-completion string corresponding to this completion 217 /// result. 218 CodeCompletionString *Completion; 219 220 /// \brief A bitmask that indicates which code-completion contexts should 221 /// contain this completion result. 222 /// 223 /// The bits in the bitmask correspond to the values of 224 /// CodeCompleteContext::Kind. To map from a completion context kind to a 225 /// bit, subtract one from the completion context kind and shift 1 by that 226 /// number of bits. Many completions can occur in several different 227 /// contexts. 228 unsigned ShowInContexts; 229 230 /// \brief The priority given to this code-completion result. 231 unsigned Priority; 232 233 /// \brief The libclang cursor kind corresponding to this code-completion 234 /// result. 235 CXCursorKind Kind; 236 237 /// \brief The simplified type class for a non-macro completion result. 238 SimplifiedTypeClass TypeClass; 239 240 /// \brief The type of a non-macro completion result, stored as a unique 241 /// integer used by the string map of cached completion types. 242 /// 243 /// This value will be zero if the type is not known, or a unique value 244 /// determined by the formatted type string. Se \c CachedCompletionTypes 245 /// for more information. 246 unsigned Type; 247 }; 248 249 /// \brief Retrieve the mapping from formatted type names to unique type 250 /// identifiers. 251 llvm::StringMap<unsigned> &getCachedCompletionTypes() { 252 return CachedCompletionTypes; 253 } 254 255private: 256 /// \brief The set of cached code-completion results. 257 std::vector<CachedCodeCompletionResult> CachedCompletionResults; 258 259 /// \brief A mapping from the formatted type name to a unique number for that 260 /// type, which is used for type equality comparisons. 261 llvm::StringMap<unsigned> CachedCompletionTypes; 262 263 /// \brief Cache any "global" code-completion results, so that we can avoid 264 /// recomputing them with each completion. 265 void CacheCodeCompletionResults(); 266 267 /// \brief Clear out and deallocate 268 void ClearCachedCompletionResults(); 269 270 /// 271 /// \} 272 /// 273 274 /// \brief The timers we've created from the various parses, reparses, etc. 275 /// involved in this translation unit. 276 std::vector<llvm::Timer *> Timers; 277 278 ASTUnit(const ASTUnit&); // DO NOT IMPLEMENT 279 ASTUnit &operator=(const ASTUnit &); // DO NOT IMPLEMENT 280 281 explicit ASTUnit(bool MainFileIsAST); 282 283 void CleanTemporaryFiles(); 284 bool Parse(llvm::MemoryBuffer *OverrideMainBuffer); 285 286 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > 287 ComputePreamble(CompilerInvocation &Invocation, 288 unsigned MaxLines, bool &CreatedBuffer); 289 290 llvm::MemoryBuffer *getMainBufferWithPrecompiledPreamble( 291 bool AllowRebuild = true, 292 unsigned MaxLines = 0); 293 void RealizeTopLevelDeclsFromPreamble(); 294 295public: 296 class ConcurrencyCheck { 297 volatile ASTUnit &Self; 298 299 public: 300 explicit ConcurrencyCheck(ASTUnit &Self) 301 : Self(Self) 302 { 303 assert(Self.ConcurrencyCheckValue == CheckUnlocked && 304 "Concurrent access to ASTUnit!"); 305 Self.ConcurrencyCheckValue = CheckLocked; 306 } 307 308 ~ConcurrencyCheck() { 309 Self.ConcurrencyCheckValue = CheckUnlocked; 310 } 311 }; 312 friend class ConcurrencyCheck; 313 314 ~ASTUnit(); 315 316 bool isMainFileAST() const { return MainFileIsAST; } 317 318 const Diagnostic &getDiagnostics() const { return *Diagnostics; } 319 Diagnostic &getDiagnostics() { return *Diagnostics; } 320 321 const SourceManager &getSourceManager() const { return *SourceMgr; } 322 SourceManager &getSourceManager() { return *SourceMgr; } 323 324 const Preprocessor &getPreprocessor() const { return *PP.get(); } 325 Preprocessor &getPreprocessor() { return *PP.get(); } 326 327 const ASTContext &getASTContext() const { return *Ctx.get(); } 328 ASTContext &getASTContext() { return *Ctx.get(); } 329 330 bool hasSema() const { return TheSema; } 331 Sema &getSema() const { 332 assert(TheSema && "ASTUnit does not have a Sema object!"); 333 return *TheSema; 334 } 335 336 const FileManager &getFileManager() const { return *FileMgr; } 337 FileManager &getFileManager() { return *FileMgr; } 338 339 const std::string &getOriginalSourceFileName(); 340 const std::string &getPCHFileName(); 341 342 /// \brief Add a temporary file that the ASTUnit depends on. 343 /// 344 /// This file will be erased when the ASTUnit is destroyed. 345 void addTemporaryFile(const llvm::sys::Path &TempFile) { 346 TemporaryFiles.push_back(TempFile); 347 } 348 349 bool getOnlyLocalDecls() const { return OnlyLocalDecls; } 350 351 /// \brief Retrieve the maximum PCH level of declarations that a 352 /// traversal of the translation unit should consider. 353 unsigned getMaxPCHLevel() const; 354 355 void setLastASTLocation(ASTLocation ALoc) { LastLoc = ALoc; } 356 ASTLocation getLastASTLocation() const { return LastLoc; } 357 358 typedef std::vector<Decl *>::iterator top_level_iterator; 359 360 top_level_iterator top_level_begin() { 361 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!"); 362 if (!TopLevelDeclsInPreamble.empty()) 363 RealizeTopLevelDeclsFromPreamble(); 364 return TopLevelDecls.begin(); 365 } 366 367 top_level_iterator top_level_end() { 368 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!"); 369 if (!TopLevelDeclsInPreamble.empty()) 370 RealizeTopLevelDeclsFromPreamble(); 371 return TopLevelDecls.end(); 372 } 373 374 std::size_t top_level_size() const { 375 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!"); 376 return TopLevelDeclsInPreamble.size() + TopLevelDecls.size(); 377 } 378 379 bool top_level_empty() const { 380 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!"); 381 return TopLevelDeclsInPreamble.empty() && TopLevelDecls.empty(); 382 } 383 384 /// \brief Add a new top-level declaration. 385 void addTopLevelDecl(Decl *D) { 386 TopLevelDecls.push_back(D); 387 } 388 389 /// \brief Add a new top-level declaration, identified by its ID in 390 /// the precompiled preamble. 391 void addTopLevelDeclFromPreamble(pch::DeclID D) { 392 TopLevelDeclsInPreamble.push_back(D); 393 } 394 395 /// \brief Retrieve the mapping from File IDs to the preprocessed entities 396 /// within that file. 397 PreprocessedEntitiesByFileMap &getPreprocessedEntitiesByFile() { 398 return PreprocessedEntitiesByFile; 399 } 400 401 // Retrieve the diagnostics associated with this AST 402 typedef const StoredDiagnostic *stored_diag_iterator; 403 stored_diag_iterator stored_diag_begin() const { 404 return StoredDiagnostics.begin(); 405 } 406 stored_diag_iterator stored_diag_end() const { 407 return StoredDiagnostics.end(); 408 } 409 unsigned stored_diag_size() const { return StoredDiagnostics.size(); } 410 411 llvm::SmallVector<StoredDiagnostic, 4> &getStoredDiagnostics() { 412 return StoredDiagnostics; 413 } 414 415 typedef std::vector<CachedCodeCompletionResult>::iterator 416 cached_completion_iterator; 417 418 cached_completion_iterator cached_completion_begin() { 419 return CachedCompletionResults.begin(); 420 } 421 422 cached_completion_iterator cached_completion_end() { 423 return CachedCompletionResults.end(); 424 } 425 426 unsigned cached_completion_size() const { 427 return CachedCompletionResults.size(); 428 } 429 430 /// \brief Whether this AST represents a complete translation unit. 431 /// 432 /// If false, this AST is only a partial translation unit, e.g., one 433 /// that might still be used as a precompiled header or preamble. 434 bool isCompleteTranslationUnit() const { return CompleteTranslationUnit; } 435 436 /// \brief A mapping from a file name to the memory buffer that stores the 437 /// remapped contents of that file. 438 typedef std::pair<std::string, const llvm::MemoryBuffer *> RemappedFile; 439 440 /// \brief Create a ASTUnit from a PCH file. 441 /// 442 /// \param Filename - The PCH file to load. 443 /// 444 /// \param Diags - The diagnostics engine to use for reporting errors; its 445 /// lifetime is expected to extend past that of the returned ASTUnit. 446 /// 447 /// \returns - The initialized ASTUnit or null if the PCH failed to load. 448 static ASTUnit *LoadFromPCHFile(const std::string &Filename, 449 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 450 bool OnlyLocalDecls = false, 451 RemappedFile *RemappedFiles = 0, 452 unsigned NumRemappedFiles = 0, 453 bool CaptureDiagnostics = false); 454 455 /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, via a 456 /// CompilerInvocation object. 457 /// 458 /// \param CI - The compiler invocation to use; it must have exactly one input 459 /// source file. The ASTUnit takes ownership of the CompilerInvocation object. 460 /// 461 /// \param Diags - The diagnostics engine to use for reporting errors; its 462 /// lifetime is expected to extend past that of the returned ASTUnit. 463 // 464 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we 465 // shouldn't need to specify them at construction time. 466 static ASTUnit *LoadFromCompilerInvocation(CompilerInvocation *CI, 467 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 468 bool OnlyLocalDecls = false, 469 bool CaptureDiagnostics = false, 470 bool PrecompilePreamble = false, 471 bool CompleteTranslationUnit = true, 472 bool CacheCodeCompletionResults = false); 473 474 /// LoadFromCommandLine - Create an ASTUnit from a vector of command line 475 /// arguments, which must specify exactly one source file. 476 /// 477 /// \param ArgBegin - The beginning of the argument vector. 478 /// 479 /// \param ArgEnd - The end of the argument vector. 480 /// 481 /// \param Diags - The diagnostics engine to use for reporting errors; its 482 /// lifetime is expected to extend past that of the returned ASTUnit. 483 /// 484 /// \param ResourceFilesPath - The path to the compiler resource files. 485 // 486 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we 487 // shouldn't need to specify them at construction time. 488 static ASTUnit *LoadFromCommandLine(const char **ArgBegin, 489 const char **ArgEnd, 490 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 491 llvm::StringRef ResourceFilesPath, 492 bool OnlyLocalDecls = false, 493 RemappedFile *RemappedFiles = 0, 494 unsigned NumRemappedFiles = 0, 495 bool CaptureDiagnostics = false, 496 bool PrecompilePreamble = false, 497 bool CompleteTranslationUnit = true, 498 bool CacheCodeCompletionResults = false); 499 500 /// \brief Reparse the source files using the same command-line options that 501 /// were originally used to produce this translation unit. 502 /// 503 /// \returns True if a failure occurred that causes the ASTUnit not to 504 /// contain any translation-unit information, false otherwise. 505 bool Reparse(RemappedFile *RemappedFiles = 0, 506 unsigned NumRemappedFiles = 0); 507 508 /// \brief Perform code completion at the given file, line, and 509 /// column within this translation unit. 510 /// 511 /// \param File The file in which code completion will occur. 512 /// 513 /// \param Line The line at which code completion will occur. 514 /// 515 /// \param Column The column at which code completion will occur. 516 /// 517 /// \param IncludeMacros Whether to include macros in the code-completion 518 /// results. 519 /// 520 /// \param IncludeCodePatterns Whether to include code patterns (such as a 521 /// for loop) in the code-completion results. 522 /// 523 /// FIXME: The Diag, LangOpts, SourceMgr, FileMgr, and 524 /// StoredDiagnostics parameters are all disgusting hacks. They will 525 /// go away. 526 void CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column, 527 RemappedFile *RemappedFiles, unsigned NumRemappedFiles, 528 bool IncludeMacros, bool IncludeCodePatterns, 529 CodeCompleteConsumer &Consumer, 530 Diagnostic &Diag, LangOptions &LangOpts, 531 SourceManager &SourceMgr, FileManager &FileMgr, 532 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics); 533 534 /// \brief Save this translation unit to a file with the given name. 535 /// 536 /// \returns True if an error occurred, false otherwise. 537 bool Save(llvm::StringRef File); 538}; 539 540} // namespace clang 541 542#endif 543