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