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