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