ASTUnit.h revision 671947b18dba342f9aba022ee992babef325a833
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/Serialization/ASTBitCodes.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/System/Path.h" 29#include "llvm/Support/Timer.h" 30#include <map> 31#include <string> 32#include <vector> 33#include <cassert> 34#include <utility> 35#include <sys/types.h> 36 37namespace llvm { 38 class MemoryBuffer; 39} 40 41namespace clang { 42class ASTContext; 43class CodeCompleteConsumer; 44class CompilerInvocation; 45class Decl; 46class Diagnostic; 47class FileEntry; 48class FileManager; 49class HeaderSearch; 50class Preprocessor; 51class SourceManager; 52class TargetInfo; 53 54using namespace idx; 55 56/// \brief Utility class for loading a ASTContext from an AST file. 57/// 58class ASTUnit { 59public: 60 typedef std::map<FileID, std::vector<PreprocessedEntity *> > 61 PreprocessedEntitiesByFileMap; 62 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 When non-NULL, this is the buffer used to store the 181 /// contents of the preamble when it has been padded to build the 182 /// precompiled preamble. 183 llvm::MemoryBuffer *PreambleBuffer; 184 185 /// \brief The number of warnings that occurred while parsing the preamble. 186 /// 187 /// This value will be used to restore the state of the \c Diagnostic object 188 /// when re-using the precompiled preamble. Note that only the 189 /// number of warnings matters, since we will not save the preamble 190 /// when any errors are present. 191 unsigned NumWarningsInPreamble; 192 193 /// \brief The number of diagnostics that were stored when parsing 194 /// the precompiled preamble. 195 /// 196 /// This value is used to determine how many of the stored 197 /// diagnostics should be retained when reparsing in the presence of 198 /// a precompiled preamble. 199 unsigned NumStoredDiagnosticsInPreamble; 200 201 /// \brief The group of timers associated with this translation unit. 202 llvm::OwningPtr<llvm::TimerGroup> TimerGroup; 203 204 /// \brief A list of the serialization ID numbers for each of the top-level 205 /// declarations parsed within the precompiled preamble. 206 std::vector<serialization::DeclID> TopLevelDeclsInPreamble; 207 208 /// 209 /// \defgroup CodeCompleteCaching Code-completion caching 210 /// 211 /// \{ 212 /// 213 214 /// \brief Whether we should be caching code-completion results. 215 bool ShouldCacheCodeCompletionResults; 216 217public: 218 /// \brief A cached code-completion result, which may be introduced in one of 219 /// many different contexts. 220 struct CachedCodeCompletionResult { 221 /// \brief The code-completion string corresponding to this completion 222 /// result. 223 CodeCompletionString *Completion; 224 225 /// \brief A bitmask that indicates which code-completion contexts should 226 /// contain this completion result. 227 /// 228 /// The bits in the bitmask correspond to the values of 229 /// CodeCompleteContext::Kind. To map from a completion context kind to a 230 /// bit, subtract one from the completion context kind and shift 1 by that 231 /// number of bits. Many completions can occur in several different 232 /// contexts. 233 unsigned ShowInContexts; 234 235 /// \brief The priority given to this code-completion result. 236 unsigned Priority; 237 238 /// \brief The libclang cursor kind corresponding to this code-completion 239 /// result. 240 CXCursorKind Kind; 241 242 /// \brief The simplified type class for a non-macro completion result. 243 SimplifiedTypeClass TypeClass; 244 245 /// \brief The type of a non-macro completion result, stored as a unique 246 /// integer used by the string map of cached completion types. 247 /// 248 /// This value will be zero if the type is not known, or a unique value 249 /// determined by the formatted type string. Se \c CachedCompletionTypes 250 /// for more information. 251 unsigned Type; 252 }; 253 254 /// \brief Retrieve the mapping from formatted type names to unique type 255 /// identifiers. 256 llvm::StringMap<unsigned> &getCachedCompletionTypes() { 257 return CachedCompletionTypes; 258 } 259 260private: 261 /// \brief The set of cached code-completion results. 262 std::vector<CachedCodeCompletionResult> CachedCompletionResults; 263 264 /// \brief A mapping from the formatted type name to a unique number for that 265 /// type, which is used for type equality comparisons. 266 llvm::StringMap<unsigned> CachedCompletionTypes; 267 268 /// \brief The number of top-level declarations present the last time we 269 /// cached code-completion results. 270 /// 271 /// The value is used to help detect when we should repopulate the global 272 /// completion cache. 273 unsigned NumTopLevelDeclsAtLastCompletionCache; 274 275 /// \brief The number of reparses left until we'll consider updating the 276 /// code-completion cache. 277 /// 278 /// This is meant to avoid thrashing during reparsing, by not allowing the 279 /// code-completion cache to be updated on every reparse. 280 unsigned CacheCodeCompletionCoolDown; 281 282 /// \brief Bit used by CIndex to mark when a translation unit may be in an 283 /// inconsistent state, and is not safe to free. 284 unsigned UnsafeToFree : 1; 285 286 /// \brief Cache any "global" code-completion results, so that we can avoid 287 /// recomputing them with each completion. 288 void CacheCodeCompletionResults(); 289 290 /// \brief Clear out and deallocate 291 void ClearCachedCompletionResults(); 292 293 /// 294 /// \} 295 /// 296 297 /// \brief The timers we've created from the various parses, reparses, etc. 298 /// involved in this translation unit. 299 std::vector<llvm::Timer *> Timers; 300 301 ASTUnit(const ASTUnit&); // DO NOT IMPLEMENT 302 ASTUnit &operator=(const ASTUnit &); // DO NOT IMPLEMENT 303 304 explicit ASTUnit(bool MainFileIsAST); 305 306 void CleanTemporaryFiles(); 307 bool Parse(llvm::MemoryBuffer *OverrideMainBuffer); 308 309 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > 310 ComputePreamble(CompilerInvocation &Invocation, 311 unsigned MaxLines, bool &CreatedBuffer); 312 313 llvm::MemoryBuffer *getMainBufferWithPrecompiledPreamble( 314 bool AllowRebuild = true, 315 unsigned MaxLines = 0); 316 void RealizeTopLevelDeclsFromPreamble(); 317 318public: 319 class ConcurrencyCheck { 320 volatile ASTUnit &Self; 321 322 public: 323 explicit ConcurrencyCheck(ASTUnit &Self) 324 : Self(Self) 325 { 326 assert(Self.ConcurrencyCheckValue == CheckUnlocked && 327 "Concurrent access to ASTUnit!"); 328 Self.ConcurrencyCheckValue = CheckLocked; 329 } 330 331 ~ConcurrencyCheck() { 332 Self.ConcurrencyCheckValue = CheckUnlocked; 333 } 334 }; 335 friend class ConcurrencyCheck; 336 337 ~ASTUnit(); 338 339 bool isMainFileAST() const { return MainFileIsAST; } 340 341 bool isUnsafeToFree() const { return UnsafeToFree; } 342 void setUnsafeToFree(bool Value) { UnsafeToFree = Value; } 343 344 const Diagnostic &getDiagnostics() const { return *Diagnostics; } 345 Diagnostic &getDiagnostics() { return *Diagnostics; } 346 347 const SourceManager &getSourceManager() const { return *SourceMgr; } 348 SourceManager &getSourceManager() { return *SourceMgr; } 349 350 const Preprocessor &getPreprocessor() const { return *PP.get(); } 351 Preprocessor &getPreprocessor() { return *PP.get(); } 352 353 const ASTContext &getASTContext() const { return *Ctx.get(); } 354 ASTContext &getASTContext() { return *Ctx.get(); } 355 356 bool hasSema() const { return TheSema; } 357 Sema &getSema() const { 358 assert(TheSema && "ASTUnit does not have a Sema object!"); 359 return *TheSema; 360 } 361 362 const FileManager &getFileManager() const { return *FileMgr; } 363 FileManager &getFileManager() { return *FileMgr; } 364 365 const std::string &getOriginalSourceFileName(); 366 const std::string &getASTFileName(); 367 368 /// \brief Add a temporary file that the ASTUnit depends on. 369 /// 370 /// This file will be erased when the ASTUnit is destroyed. 371 void addTemporaryFile(const llvm::sys::Path &TempFile) { 372 TemporaryFiles.push_back(TempFile); 373 } 374 375 bool getOnlyLocalDecls() const { return OnlyLocalDecls; } 376 377 /// \brief Retrieve the maximum PCH level of declarations that a 378 /// traversal of the translation unit should consider. 379 unsigned getMaxPCHLevel() const; 380 381 void setLastASTLocation(ASTLocation ALoc) { LastLoc = ALoc; } 382 ASTLocation getLastASTLocation() const { return LastLoc; } 383 384 typedef std::vector<Decl *>::iterator top_level_iterator; 385 386 top_level_iterator top_level_begin() { 387 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!"); 388 if (!TopLevelDeclsInPreamble.empty()) 389 RealizeTopLevelDeclsFromPreamble(); 390 return TopLevelDecls.begin(); 391 } 392 393 top_level_iterator top_level_end() { 394 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!"); 395 if (!TopLevelDeclsInPreamble.empty()) 396 RealizeTopLevelDeclsFromPreamble(); 397 return TopLevelDecls.end(); 398 } 399 400 std::size_t top_level_size() const { 401 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!"); 402 return TopLevelDeclsInPreamble.size() + TopLevelDecls.size(); 403 } 404 405 bool top_level_empty() const { 406 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!"); 407 return TopLevelDeclsInPreamble.empty() && TopLevelDecls.empty(); 408 } 409 410 /// \brief Add a new top-level declaration. 411 void addTopLevelDecl(Decl *D) { 412 TopLevelDecls.push_back(D); 413 } 414 415 /// \brief Add a new top-level declaration, identified by its ID in 416 /// the precompiled preamble. 417 void addTopLevelDeclFromPreamble(serialization::DeclID D) { 418 TopLevelDeclsInPreamble.push_back(D); 419 } 420 421 /// \brief Retrieve the mapping from File IDs to the preprocessed entities 422 /// within that file. 423 PreprocessedEntitiesByFileMap &getPreprocessedEntitiesByFile() { 424 return PreprocessedEntitiesByFile; 425 } 426 427 // Retrieve the diagnostics associated with this AST 428 typedef const StoredDiagnostic *stored_diag_iterator; 429 stored_diag_iterator stored_diag_begin() const { 430 return StoredDiagnostics.begin(); 431 } 432 stored_diag_iterator stored_diag_end() const { 433 return StoredDiagnostics.end(); 434 } 435 unsigned stored_diag_size() const { return StoredDiagnostics.size(); } 436 437 llvm::SmallVector<StoredDiagnostic, 4> &getStoredDiagnostics() { 438 return StoredDiagnostics; 439 } 440 441 typedef std::vector<CachedCodeCompletionResult>::iterator 442 cached_completion_iterator; 443 444 cached_completion_iterator cached_completion_begin() { 445 return CachedCompletionResults.begin(); 446 } 447 448 cached_completion_iterator cached_completion_end() { 449 return CachedCompletionResults.end(); 450 } 451 452 unsigned cached_completion_size() const { 453 return CachedCompletionResults.size(); 454 } 455 456 /// \brief Whether this AST represents a complete translation unit. 457 /// 458 /// If false, this AST is only a partial translation unit, e.g., one 459 /// that might still be used as a precompiled header or preamble. 460 bool isCompleteTranslationUnit() const { return CompleteTranslationUnit; } 461 462 /// \brief A mapping from a file name to the memory buffer that stores the 463 /// remapped contents of that file. 464 typedef std::pair<std::string, const llvm::MemoryBuffer *> RemappedFile; 465 466 /// \brief Create a ASTUnit from an AST file. 467 /// 468 /// \param Filename - The AST file to load. 469 /// 470 /// \param Diags - The diagnostics engine to use for reporting errors; its 471 /// lifetime is expected to extend past that of the returned ASTUnit. 472 /// 473 /// \returns - The initialized ASTUnit or null if the AST failed to load. 474 static ASTUnit *LoadFromASTFile(const std::string &Filename, 475 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 476 bool OnlyLocalDecls = false, 477 RemappedFile *RemappedFiles = 0, 478 unsigned NumRemappedFiles = 0, 479 bool CaptureDiagnostics = false); 480 481 /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, via a 482 /// CompilerInvocation object. 483 /// 484 /// \param CI - The compiler invocation to use; it must have exactly one input 485 /// source file. The ASTUnit takes ownership of the CompilerInvocation object. 486 /// 487 /// \param Diags - The diagnostics engine to use for reporting errors; its 488 /// lifetime is expected to extend past that of the returned ASTUnit. 489 // 490 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we 491 // shouldn't need to specify them at construction time. 492 static ASTUnit *LoadFromCompilerInvocation(CompilerInvocation *CI, 493 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 494 bool OnlyLocalDecls = false, 495 bool CaptureDiagnostics = false, 496 bool PrecompilePreamble = false, 497 bool CompleteTranslationUnit = true, 498 bool CacheCodeCompletionResults = false); 499 500 /// LoadFromCommandLine - Create an ASTUnit from a vector of command line 501 /// arguments, which must specify exactly one source file. 502 /// 503 /// \param ArgBegin - The beginning of the argument vector. 504 /// 505 /// \param ArgEnd - The end of the argument vector. 506 /// 507 /// \param Diags - The diagnostics engine to use for reporting errors; its 508 /// lifetime is expected to extend past that of the returned ASTUnit. 509 /// 510 /// \param ResourceFilesPath - The path to the compiler resource files. 511 // 512 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we 513 // shouldn't need to specify them at construction time. 514 static ASTUnit *LoadFromCommandLine(const char **ArgBegin, 515 const char **ArgEnd, 516 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 517 llvm::StringRef ResourceFilesPath, 518 bool OnlyLocalDecls = false, 519 RemappedFile *RemappedFiles = 0, 520 unsigned NumRemappedFiles = 0, 521 bool CaptureDiagnostics = false, 522 bool PrecompilePreamble = false, 523 bool CompleteTranslationUnit = true, 524 bool CacheCodeCompletionResults = false); 525 526 /// \brief Reparse the source files using the same command-line options that 527 /// were originally used to produce this translation unit. 528 /// 529 /// \returns True if a failure occurred that causes the ASTUnit not to 530 /// contain any translation-unit information, false otherwise. 531 bool Reparse(RemappedFile *RemappedFiles = 0, 532 unsigned NumRemappedFiles = 0); 533 534 /// \brief Perform code completion at the given file, line, and 535 /// column within this translation unit. 536 /// 537 /// \param File The file in which code completion will occur. 538 /// 539 /// \param Line The line at which code completion will occur. 540 /// 541 /// \param Column The column at which code completion will occur. 542 /// 543 /// \param IncludeMacros Whether to include macros in the code-completion 544 /// results. 545 /// 546 /// \param IncludeCodePatterns Whether to include code patterns (such as a 547 /// for loop) in the code-completion results. 548 /// 549 /// FIXME: The Diag, LangOpts, SourceMgr, FileMgr, and 550 /// StoredDiagnostics parameters are all disgusting hacks. They will 551 /// go away. 552 void CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column, 553 RemappedFile *RemappedFiles, unsigned NumRemappedFiles, 554 bool IncludeMacros, bool IncludeCodePatterns, 555 CodeCompleteConsumer &Consumer, 556 Diagnostic &Diag, LangOptions &LangOpts, 557 SourceManager &SourceMgr, FileManager &FileMgr, 558 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics); 559 560 /// \brief Save this translation unit to a file with the given name. 561 /// 562 /// \returns True if an error occurred, false otherwise. 563 bool Save(llvm::StringRef File); 564}; 565 566} // namespace clang 567 568#endif 569