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