ASTUnit.h revision 6aa52ec6b969faabf3764baf79d89810b8249a7e
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/Sema/CodeCompleteConsumer.h" 21#include "clang/Lex/ModuleLoader.h" 22#include "clang/Lex/PreprocessingRecord.h" 23#include "clang/Basic/SourceManager.h" 24#include "clang/Basic/FileManager.h" 25#include "clang/Basic/FileSystemOptions.h" 26#include "clang-c/Index.h" 27#include "llvm/ADT/IntrusiveRefCntPtr.h" 28#include "llvm/ADT/OwningPtr.h" 29#include "llvm/ADT/SmallVector.h" 30#include "llvm/ADT/StringMap.h" 31#include "llvm/Support/Path.h" 32#include <map> 33#include <string> 34#include <vector> 35#include <cassert> 36#include <utility> 37#include <sys/types.h> 38 39namespace llvm { 40 class MemoryBuffer; 41} 42 43namespace clang { 44class ASTContext; 45class ASTReader; 46class CodeCompleteConsumer; 47class CompilerInvocation; 48class Decl; 49class Diagnostic; 50class FileEntry; 51class FileManager; 52class HeaderSearch; 53class Preprocessor; 54class SourceManager; 55class TargetInfo; 56class ASTFrontendAction; 57 58using namespace idx; 59 60/// \brief Allocator for a cached set of global code completions. 61class GlobalCodeCompletionAllocator 62 : public CodeCompletionAllocator, 63 public llvm::RefCountedBase<GlobalCodeCompletionAllocator> 64{ 65 66}; 67 68/// \brief Utility class for loading a ASTContext from an AST file. 69/// 70class ASTUnit : public ModuleLoader { 71public: 72 typedef std::map<FileID, std::vector<PreprocessedEntity *> > 73 PreprocessedEntitiesByFileMap; 74 75private: 76 llvm::IntrusiveRefCntPtr<Diagnostic> Diagnostics; 77 llvm::IntrusiveRefCntPtr<FileManager> FileMgr; 78 llvm::IntrusiveRefCntPtr<SourceManager> SourceMgr; 79 llvm::OwningPtr<HeaderSearch> HeaderInfo; 80 llvm::IntrusiveRefCntPtr<TargetInfo> Target; 81 llvm::IntrusiveRefCntPtr<Preprocessor> PP; 82 llvm::IntrusiveRefCntPtr<ASTContext> Ctx; 83 84 FileSystemOptions FileSystemOpts; 85 86 /// \brief The AST consumer that received information about the translation 87 /// unit as it was parsed or loaded. 88 llvm::OwningPtr<ASTConsumer> Consumer; 89 90 /// \brief The semantic analysis object used to type-check the translation 91 /// unit. 92 llvm::OwningPtr<Sema> TheSema; 93 94 /// Optional owned invocation, just used to make the invocation used in 95 /// LoadFromCommandLine available. 96 llvm::IntrusiveRefCntPtr<CompilerInvocation> Invocation; 97 98 /// \brief The set of target features. 99 /// 100 /// FIXME: each time we reparse, we need to restore the set of target 101 /// features from this vector, because TargetInfo::CreateTargetInfo() 102 /// mangles the target options in place. Yuck! 103 std::vector<std::string> TargetFeatures; 104 105 // OnlyLocalDecls - when true, walking this AST should only visit declarations 106 // that come from the AST itself, not from included precompiled headers. 107 // FIXME: This is temporary; eventually, CIndex will always do this. 108 bool OnlyLocalDecls; 109 110 /// \brief Whether to capture any diagnostics produced. 111 bool CaptureDiagnostics; 112 113 /// \brief Track whether the main file was loaded from an AST or not. 114 bool MainFileIsAST; 115 116 /// \brief What kind of translation unit this AST represents. 117 TranslationUnitKind TUKind; 118 119 /// \brief Whether we should time each operation. 120 bool WantTiming; 121 122 /// \brief Whether the ASTUnit should delete the remapped buffers. 123 bool OwnsRemappedFileBuffers; 124 125 /// Track the top-level decls which appeared in an ASTUnit which was loaded 126 /// from a source file. 127 // 128 // FIXME: This is just an optimization hack to avoid deserializing large parts 129 // of a PCH file when using the Index library on an ASTUnit loaded from 130 // source. In the long term we should make the Index library use efficient and 131 // more scalable search mechanisms. 132 std::vector<Decl*> TopLevelDecls; 133 134 /// \brief The list of preprocessed entities which appeared when the ASTUnit 135 /// was loaded. 136 /// 137 /// FIXME: This is just an optimization hack to avoid deserializing large 138 /// parts of a PCH file while performing a walk or search. In the long term, 139 /// we should provide more scalable search mechanisms. 140 std::vector<PreprocessedEntity *> PreprocessedEntities; 141 142 /// The name of the original source file used to generate this ASTUnit. 143 std::string OriginalSourceFile; 144 145 // Critical optimization when using clang_getCursor(). 146 ASTLocation LastLoc; 147 148 /// \brief The set of diagnostics produced when creating the preamble. 149 SmallVector<StoredDiagnostic, 4> PreambleDiagnostics; 150 151 /// \brief The set of diagnostics produced when creating this 152 /// translation unit. 153 SmallVector<StoredDiagnostic, 4> StoredDiagnostics; 154 155 /// \brief The number of stored diagnostics that come from the driver 156 /// itself. 157 /// 158 /// Diagnostics that come from the driver are retained from one parse to 159 /// the next. 160 unsigned NumStoredDiagnosticsFromDriver; 161 162 /// \brief Temporary files that should be removed when the ASTUnit is 163 /// destroyed. 164 SmallVector<llvm::sys::Path, 4> TemporaryFiles; 165 166 /// \brief A mapping from file IDs to the set of preprocessed entities 167 /// stored in that file. 168 /// 169 /// FIXME: This is just an optimization hack to avoid searching through 170 /// many preprocessed entities during cursor traversal in the CIndex library. 171 /// Ideally, we would just be able to perform a binary search within the 172 /// list of preprocessed entities. 173 PreprocessedEntitiesByFileMap PreprocessedEntitiesByFile; 174 175 /// \brief Simple hack to allow us to assert that ASTUnit is not being 176 /// used concurrently, which is not supported. 177 /// 178 /// Clients should create instances of the ConcurrencyCheck class whenever 179 /// using the ASTUnit in a way that isn't intended to be concurrent, which is 180 /// just about any usage. 181 unsigned int ConcurrencyCheckValue; 182 static const unsigned int CheckLocked = 28573289; 183 static const unsigned int CheckUnlocked = 9803453; 184 185 /// \brief Counter that determines when we want to try building a 186 /// precompiled preamble. 187 /// 188 /// If zero, we will never build a precompiled preamble. Otherwise, 189 /// it's treated as a counter that decrements each time we reparse 190 /// without the benefit of a precompiled preamble. When it hits 1, 191 /// we'll attempt to rebuild the precompiled header. This way, if 192 /// building the precompiled preamble fails, we won't try again for 193 /// some number of calls. 194 unsigned PreambleRebuildCounter; 195 196 /// \brief The file in which the precompiled preamble is stored. 197 std::string PreambleFile; 198 199 /// \brief The contents of the preamble that has been precompiled to 200 /// \c PreambleFile. 201 std::vector<char> Preamble; 202 203 /// \brief Whether the preamble ends at the start of a new line. 204 /// 205 /// Used to inform the lexer as to whether it's starting at the beginning of 206 /// a line after skipping the preamble. 207 bool PreambleEndsAtStartOfLine; 208 209 /// \brief The size of the source buffer that we've reserved for the main 210 /// file within the precompiled preamble. 211 unsigned PreambleReservedSize; 212 213 /// \brief Keeps track of the files that were used when computing the 214 /// preamble, with both their buffer size and their modification time. 215 /// 216 /// If any of the files have changed from one compile to the next, 217 /// the preamble must be thrown away. 218 llvm::StringMap<std::pair<off_t, time_t> > FilesInPreamble; 219 220 /// \brief When non-NULL, this is the buffer used to store the contents of 221 /// the main file when it has been padded for use with the precompiled 222 /// preamble. 223 llvm::MemoryBuffer *SavedMainFileBuffer; 224 225 /// \brief When non-NULL, this is the buffer used to store the 226 /// contents of the preamble when it has been padded to build the 227 /// precompiled preamble. 228 llvm::MemoryBuffer *PreambleBuffer; 229 230 /// \brief The number of warnings that occurred while parsing the preamble. 231 /// 232 /// This value will be used to restore the state of the \c Diagnostic object 233 /// when re-using the precompiled preamble. Note that only the 234 /// number of warnings matters, since we will not save the preamble 235 /// when any errors are present. 236 unsigned NumWarningsInPreamble; 237 238 /// \brief A list of the serialization ID numbers for each of the top-level 239 /// declarations parsed within the precompiled preamble. 240 std::vector<serialization::DeclID> TopLevelDeclsInPreamble; 241 242 /// \brief A list of the offsets into the precompiled preamble which 243 /// correspond to preprocessed entities. 244 std::vector<uint64_t> PreprocessedEntitiesInPreamble; 245 246 /// \brief Whether we should be caching code-completion results. 247 bool ShouldCacheCodeCompletionResults; 248 249 /// \brief Whether we want to include nested macro expansions in the 250 /// detailed preprocessing record. 251 bool NestedMacroExpansions; 252 253 static void ConfigureDiags(llvm::IntrusiveRefCntPtr<Diagnostic> &Diags, 254 const char **ArgBegin, const char **ArgEnd, 255 ASTUnit &AST, bool CaptureDiagnostics); 256 257 void TranslateStoredDiagnostics(ASTReader *MMan, StringRef ModName, 258 SourceManager &SrcMan, 259 const SmallVectorImpl<StoredDiagnostic> &Diags, 260 SmallVectorImpl<StoredDiagnostic> &Out); 261 262public: 263 /// \brief A cached code-completion result, which may be introduced in one of 264 /// many different contexts. 265 struct CachedCodeCompletionResult { 266 /// \brief The code-completion string corresponding to this completion 267 /// result. 268 CodeCompletionString *Completion; 269 270 /// \brief A bitmask that indicates which code-completion contexts should 271 /// contain this completion result. 272 /// 273 /// The bits in the bitmask correspond to the values of 274 /// CodeCompleteContext::Kind. To map from a completion context kind to a 275 /// bit, subtract one from the completion context kind and shift 1 by that 276 /// number of bits. Many completions can occur in several different 277 /// contexts. 278 unsigned ShowInContexts; 279 280 /// \brief The priority given to this code-completion result. 281 unsigned Priority; 282 283 /// \brief The libclang cursor kind corresponding to this code-completion 284 /// result. 285 CXCursorKind Kind; 286 287 /// \brief The availability of this code-completion result. 288 CXAvailabilityKind Availability; 289 290 /// \brief The simplified type class for a non-macro completion result. 291 SimplifiedTypeClass TypeClass; 292 293 /// \brief The type of a non-macro completion result, stored as a unique 294 /// integer used by the string map of cached completion types. 295 /// 296 /// This value will be zero if the type is not known, or a unique value 297 /// determined by the formatted type string. Se \c CachedCompletionTypes 298 /// for more information. 299 unsigned Type; 300 }; 301 302 /// \brief Retrieve the mapping from formatted type names to unique type 303 /// identifiers. 304 llvm::StringMap<unsigned> &getCachedCompletionTypes() { 305 return CachedCompletionTypes; 306 } 307 308 /// \brief Retrieve the allocator used to cache global code completions. 309 llvm::IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> 310 getCachedCompletionAllocator() { 311 return CachedCompletionAllocator; 312 } 313 314 /// \brief Retrieve the allocator used to cache global code completions. 315 /// Creates the allocator if it doesn't already exist. 316 llvm::IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> 317 getCursorCompletionAllocator() { 318 if (!CursorCompletionAllocator.getPtr()) { 319 CursorCompletionAllocator = new GlobalCodeCompletionAllocator; 320 } 321 return CursorCompletionAllocator; 322 } 323 324private: 325 /// \brief Allocator used to store cached code completions. 326 llvm::IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> 327 CachedCompletionAllocator; 328 329 /// \brief Allocator used to store code completions for arbitrary cursors. 330 llvm::IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> 331 CursorCompletionAllocator; 332 333 /// \brief The set of cached code-completion results. 334 std::vector<CachedCodeCompletionResult> CachedCompletionResults; 335 336 /// \brief A mapping from the formatted type name to a unique number for that 337 /// type, which is used for type equality comparisons. 338 llvm::StringMap<unsigned> CachedCompletionTypes; 339 340 /// \brief A string hash of the top-level declaration and macro definition 341 /// names processed the last time that we reparsed the file. 342 /// 343 /// This hash value is used to determine when we need to refresh the 344 /// global code-completion cache. 345 unsigned CompletionCacheTopLevelHashValue; 346 347 /// \brief A string hash of the top-level declaration and macro definition 348 /// names processed the last time that we reparsed the precompiled preamble. 349 /// 350 /// This hash value is used to determine when we need to refresh the 351 /// global code-completion cache after a rebuild of the precompiled preamble. 352 unsigned PreambleTopLevelHashValue; 353 354 /// \brief The current hash value for the top-level declaration and macro 355 /// definition names 356 unsigned CurrentTopLevelHashValue; 357 358 /// \brief Bit used by CIndex to mark when a translation unit may be in an 359 /// inconsistent state, and is not safe to free. 360 unsigned UnsafeToFree : 1; 361 362 /// \brief Cache any "global" code-completion results, so that we can avoid 363 /// recomputing them with each completion. 364 void CacheCodeCompletionResults(); 365 366 /// \brief Clear out and deallocate 367 void ClearCachedCompletionResults(); 368 369 ASTUnit(const ASTUnit&); // DO NOT IMPLEMENT 370 ASTUnit &operator=(const ASTUnit &); // DO NOT IMPLEMENT 371 372 explicit ASTUnit(bool MainFileIsAST); 373 374 void CleanTemporaryFiles(); 375 bool Parse(llvm::MemoryBuffer *OverrideMainBuffer); 376 377 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > 378 ComputePreamble(CompilerInvocation &Invocation, 379 unsigned MaxLines, bool &CreatedBuffer); 380 381 llvm::MemoryBuffer *getMainBufferWithPrecompiledPreamble( 382 const CompilerInvocation &PreambleInvocationIn, 383 bool AllowRebuild = true, 384 unsigned MaxLines = 0); 385 void RealizeTopLevelDeclsFromPreamble(); 386 void RealizePreprocessedEntitiesFromPreamble(); 387 388public: 389 class ConcurrencyCheck { 390 volatile ASTUnit &Self; 391 392 public: 393 explicit ConcurrencyCheck(ASTUnit &Self) 394 : Self(Self) 395 { 396 assert(Self.ConcurrencyCheckValue == CheckUnlocked && 397 "Concurrent access to ASTUnit!"); 398 Self.ConcurrencyCheckValue = CheckLocked; 399 } 400 401 ~ConcurrencyCheck() { 402 Self.ConcurrencyCheckValue = CheckUnlocked; 403 } 404 }; 405 friend class ConcurrencyCheck; 406 407 ~ASTUnit(); 408 409 bool isMainFileAST() const { return MainFileIsAST; } 410 411 bool isUnsafeToFree() const { return UnsafeToFree; } 412 void setUnsafeToFree(bool Value) { UnsafeToFree = Value; } 413 414 const Diagnostic &getDiagnostics() const { return *Diagnostics; } 415 Diagnostic &getDiagnostics() { return *Diagnostics; } 416 417 const SourceManager &getSourceManager() const { return *SourceMgr; } 418 SourceManager &getSourceManager() { return *SourceMgr; } 419 420 const Preprocessor &getPreprocessor() const { return *PP; } 421 Preprocessor &getPreprocessor() { return *PP; } 422 423 const ASTContext &getASTContext() const { return *Ctx; } 424 ASTContext &getASTContext() { return *Ctx; } 425 426 bool hasSema() const { return TheSema; } 427 Sema &getSema() const { 428 assert(TheSema && "ASTUnit does not have a Sema object!"); 429 return *TheSema; 430 } 431 432 const FileManager &getFileManager() const { return *FileMgr; } 433 FileManager &getFileManager() { return *FileMgr; } 434 435 const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; } 436 437 const std::string &getOriginalSourceFileName(); 438 439 /// \brief Add a temporary file that the ASTUnit depends on. 440 /// 441 /// This file will be erased when the ASTUnit is destroyed. 442 void addTemporaryFile(const llvm::sys::Path &TempFile) { 443 TemporaryFiles.push_back(TempFile); 444 } 445 446 bool getOnlyLocalDecls() const { return OnlyLocalDecls; } 447 448 bool getOwnsRemappedFileBuffers() const { return OwnsRemappedFileBuffers; } 449 void setOwnsRemappedFileBuffers(bool val) { OwnsRemappedFileBuffers = val; } 450 451 /// \brief Retrieve the maximum PCH level of declarations that a 452 /// traversal of the translation unit should consider. 453 unsigned getMaxPCHLevel() const; 454 455 void setLastASTLocation(ASTLocation ALoc) { LastLoc = ALoc; } 456 ASTLocation getLastASTLocation() const { return LastLoc; } 457 458 459 StringRef getMainFileName() const; 460 461 typedef std::vector<Decl *>::iterator top_level_iterator; 462 463 top_level_iterator top_level_begin() { 464 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!"); 465 if (!TopLevelDeclsInPreamble.empty()) 466 RealizeTopLevelDeclsFromPreamble(); 467 return TopLevelDecls.begin(); 468 } 469 470 top_level_iterator top_level_end() { 471 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!"); 472 if (!TopLevelDeclsInPreamble.empty()) 473 RealizeTopLevelDeclsFromPreamble(); 474 return TopLevelDecls.end(); 475 } 476 477 std::size_t top_level_size() const { 478 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!"); 479 return TopLevelDeclsInPreamble.size() + TopLevelDecls.size(); 480 } 481 482 bool top_level_empty() const { 483 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!"); 484 return TopLevelDeclsInPreamble.empty() && TopLevelDecls.empty(); 485 } 486 487 /// \brief Add a new top-level declaration. 488 void addTopLevelDecl(Decl *D) { 489 TopLevelDecls.push_back(D); 490 } 491 492 /// \brief Add a new top-level declaration, identified by its ID in 493 /// the precompiled preamble. 494 void addTopLevelDeclFromPreamble(serialization::DeclID D) { 495 TopLevelDeclsInPreamble.push_back(D); 496 } 497 498 /// \brief Retrieve a reference to the current top-level name hash value. 499 /// 500 /// Note: This is used internally by the top-level tracking action 501 unsigned &getCurrentTopLevelHashValue() { return CurrentTopLevelHashValue; } 502 503 typedef std::vector<PreprocessedEntity *>::iterator pp_entity_iterator; 504 505 pp_entity_iterator pp_entity_begin(); 506 pp_entity_iterator pp_entity_end(); 507 508 /// \brief Add a new preprocessed entity that's stored at the given offset 509 /// in the precompiled preamble. 510 void addPreprocessedEntityFromPreamble(uint64_t Offset) { 511 PreprocessedEntitiesInPreamble.push_back(Offset); 512 } 513 514 /// \brief Retrieve the mapping from File IDs to the preprocessed entities 515 /// within that file. 516 PreprocessedEntitiesByFileMap &getPreprocessedEntitiesByFile() { 517 return PreprocessedEntitiesByFile; 518 } 519 520 // Retrieve the diagnostics associated with this AST 521 typedef const StoredDiagnostic *stored_diag_iterator; 522 stored_diag_iterator stored_diag_begin() const { 523 return StoredDiagnostics.begin(); 524 } 525 stored_diag_iterator stored_diag_end() const { 526 return StoredDiagnostics.end(); 527 } 528 unsigned stored_diag_size() const { return StoredDiagnostics.size(); } 529 530 SmallVector<StoredDiagnostic, 4> &getStoredDiagnostics() { 531 return StoredDiagnostics; 532 } 533 534 typedef std::vector<CachedCodeCompletionResult>::iterator 535 cached_completion_iterator; 536 537 cached_completion_iterator cached_completion_begin() { 538 return CachedCompletionResults.begin(); 539 } 540 541 cached_completion_iterator cached_completion_end() { 542 return CachedCompletionResults.end(); 543 } 544 545 unsigned cached_completion_size() const { 546 return CachedCompletionResults.size(); 547 } 548 549 llvm::MemoryBuffer *getBufferForFile(StringRef Filename, 550 std::string *ErrorStr = 0); 551 552 /// \brief Determine what kind of translation unit this AST represents. 553 TranslationUnitKind getTranslationUnitKind() const { return TUKind; } 554 555 typedef llvm::PointerUnion<const char *, const llvm::MemoryBuffer *> 556 FilenameOrMemBuf; 557 /// \brief A mapping from a file name to the memory buffer that stores the 558 /// remapped contents of that file. 559 typedef std::pair<std::string, FilenameOrMemBuf> RemappedFile; 560 561 /// \brief Create a ASTUnit. Gets ownership of the passed CompilerInvocation. 562 static ASTUnit *create(CompilerInvocation *CI, 563 llvm::IntrusiveRefCntPtr<Diagnostic> Diags); 564 565 /// \brief Create a ASTUnit from an AST file. 566 /// 567 /// \param Filename - The AST file to load. 568 /// 569 /// \param Diags - The diagnostics engine to use for reporting errors; its 570 /// lifetime is expected to extend past that of the returned ASTUnit. 571 /// 572 /// \returns - The initialized ASTUnit or null if the AST failed to load. 573 static ASTUnit *LoadFromASTFile(const std::string &Filename, 574 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 575 const FileSystemOptions &FileSystemOpts, 576 bool OnlyLocalDecls = false, 577 RemappedFile *RemappedFiles = 0, 578 unsigned NumRemappedFiles = 0, 579 bool CaptureDiagnostics = false); 580 581private: 582 /// \brief Helper function for \c LoadFromCompilerInvocation() and 583 /// \c LoadFromCommandLine(), which loads an AST from a compiler invocation. 584 /// 585 /// \param PrecompilePreamble Whether to precompile the preamble of this 586 /// translation unit, to improve the performance of reparsing. 587 /// 588 /// \returns \c true if a catastrophic failure occurred (which means that the 589 /// \c ASTUnit itself is invalid), or \c false otherwise. 590 bool LoadFromCompilerInvocation(bool PrecompilePreamble); 591 592public: 593 594 /// \brief Create an ASTUnit from a source file, via a CompilerInvocation 595 /// object, by invoking the optionally provided ASTFrontendAction. 596 /// 597 /// \param CI - The compiler invocation to use; it must have exactly one input 598 /// source file. The ASTUnit takes ownership of the CompilerInvocation object. 599 /// 600 /// \param Diags - The diagnostics engine to use for reporting errors; its 601 /// lifetime is expected to extend past that of the returned ASTUnit. 602 /// 603 /// \param Action - The ASTFrontendAction to invoke. Its ownership is not 604 /// transfered. 605 static ASTUnit *LoadFromCompilerInvocationAction(CompilerInvocation *CI, 606 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 607 ASTFrontendAction *Action = 0); 608 609 /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, via a 610 /// CompilerInvocation object. 611 /// 612 /// \param CI - The compiler invocation to use; it must have exactly one input 613 /// source file. The ASTUnit takes ownership of the CompilerInvocation object. 614 /// 615 /// \param Diags - The diagnostics engine to use for reporting errors; its 616 /// lifetime is expected to extend past that of the returned ASTUnit. 617 // 618 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we 619 // shouldn't need to specify them at construction time. 620 static ASTUnit *LoadFromCompilerInvocation(CompilerInvocation *CI, 621 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 622 bool OnlyLocalDecls = false, 623 bool CaptureDiagnostics = false, 624 bool PrecompilePreamble = false, 625 TranslationUnitKind TUKind = TU_Complete, 626 bool CacheCodeCompletionResults = false, 627 bool NestedMacroExpansions = true); 628 629 /// LoadFromCommandLine - Create an ASTUnit from a vector of command line 630 /// arguments, which must specify exactly one source file. 631 /// 632 /// \param ArgBegin - The beginning of the argument vector. 633 /// 634 /// \param ArgEnd - The end of the argument vector. 635 /// 636 /// \param Diags - The diagnostics engine to use for reporting errors; its 637 /// lifetime is expected to extend past that of the returned ASTUnit. 638 /// 639 /// \param ResourceFilesPath - The path to the compiler resource files. 640 // 641 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we 642 // shouldn't need to specify them at construction time. 643 static ASTUnit *LoadFromCommandLine(const char **ArgBegin, 644 const char **ArgEnd, 645 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 646 StringRef ResourceFilesPath, 647 bool OnlyLocalDecls = false, 648 bool CaptureDiagnostics = false, 649 RemappedFile *RemappedFiles = 0, 650 unsigned NumRemappedFiles = 0, 651 bool RemappedFilesKeepOriginalName = true, 652 bool PrecompilePreamble = false, 653 TranslationUnitKind TUKind = TU_Complete, 654 bool CacheCodeCompletionResults = false, 655 bool NestedMacroExpansions = true); 656 657 /// \brief Reparse the source files using the same command-line options that 658 /// were originally used to produce this translation unit. 659 /// 660 /// \returns True if a failure occurred that causes the ASTUnit not to 661 /// contain any translation-unit information, false otherwise. 662 bool Reparse(RemappedFile *RemappedFiles = 0, 663 unsigned NumRemappedFiles = 0); 664 665 /// \brief Perform code completion at the given file, line, and 666 /// column within this translation unit. 667 /// 668 /// \param File The file in which code completion will occur. 669 /// 670 /// \param Line The line at which code completion will occur. 671 /// 672 /// \param Column The column at which code completion will occur. 673 /// 674 /// \param IncludeMacros Whether to include macros in the code-completion 675 /// results. 676 /// 677 /// \param IncludeCodePatterns Whether to include code patterns (such as a 678 /// for loop) in the code-completion results. 679 /// 680 /// FIXME: The Diag, LangOpts, SourceMgr, FileMgr, StoredDiagnostics, and 681 /// OwnedBuffers parameters are all disgusting hacks. They will go away. 682 void CodeComplete(StringRef File, unsigned Line, unsigned Column, 683 RemappedFile *RemappedFiles, unsigned NumRemappedFiles, 684 bool IncludeMacros, bool IncludeCodePatterns, 685 CodeCompleteConsumer &Consumer, 686 Diagnostic &Diag, LangOptions &LangOpts, 687 SourceManager &SourceMgr, FileManager &FileMgr, 688 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics, 689 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers); 690 691 /// \brief Save this translation unit to a file with the given name. 692 /// 693 /// \returns An indication of whether the save was successful or not. 694 CXSaveError Save(StringRef File); 695 696 /// \brief Serialize this translation unit with the given output stream. 697 /// 698 /// \returns True if an error occurred, false otherwise. 699 bool serialize(raw_ostream &OS); 700 701 virtual ModuleKey loadModule(SourceLocation ImportLoc, 702 IdentifierInfo &ModuleName, 703 SourceLocation ModuleNameLoc) { 704 // ASTUnit doesn't know how to load modules (not that this matters). 705 return 0; 706 } 707}; 708 709} // namespace clang 710 711#endif 712