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