ASTUnit.h revision 9a022bb007a3e77e1ac1330f955a239cfb1dd0fb
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/Serialization/ASTBitCodes.h" 18#include "clang/Sema/Sema.h" 19#include "clang/Sema/CodeCompleteConsumer.h" 20#include "clang/Lex/ModuleLoader.h" 21#include "clang/Lex/PreprocessingRecord.h" 22#include "clang/AST/ASTContext.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/Basic/TargetOptions.h" 28#include "clang-c/Index.h" 29#include "llvm/ADT/IntrusiveRefCntPtr.h" 30#include "llvm/ADT/OwningPtr.h" 31#include "llvm/ADT/SmallVector.h" 32#include "llvm/ADT/StringMap.h" 33#include "llvm/Support/Path.h" 34#include <map> 35#include <string> 36#include <vector> 37#include <cassert> 38#include <utility> 39#include <sys/types.h> 40 41namespace llvm { 42 class MemoryBuffer; 43} 44 45namespace clang { 46class ASTContext; 47class ASTReader; 48class CodeCompleteConsumer; 49class CompilerInvocation; 50class CompilerInstance; 51class Decl; 52class DiagnosticsEngine; 53class FileEntry; 54class FileManager; 55class HeaderSearch; 56class Preprocessor; 57class SourceManager; 58class TargetInfo; 59class ASTFrontendAction; 60class ASTDeserializationListener; 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 TargetOptions TargetOpts; 76 77 struct ASTWriterData; 78 OwningPtr<ASTWriterData> WriterData; 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 OwningPtr<ASTConsumer> Consumer; 85 86 /// \brief The semantic analysis object used to type-check the translation 87 /// unit. 88 OwningPtr<Sema> TheSema; 89 90 /// Optional owned invocation, just used to make the invocation used in 91 /// LoadFromCommandLine available. 92 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 /// \brief Sorted (by file offset) vector of pairs of file offset/Decl. 131 typedef SmallVector<std::pair<unsigned, Decl *>, 64> LocDeclsTy; 132 typedef llvm::DenseMap<FileID, LocDeclsTy *> FileDeclsTy; 133 134 /// \brief Map from FileID to the file-level declarations that it contains. 135 /// The files and decls are only local (and non-preamble) ones. 136 FileDeclsTy FileDecls; 137 138 /// The name of the original source file used to generate this ASTUnit. 139 std::string OriginalSourceFile; 140 141 /// \brief The set of diagnostics produced when creating the preamble. 142 SmallVector<StoredDiagnostic, 4> PreambleDiagnostics; 143 144 /// \brief The set of diagnostics produced when creating this 145 /// translation unit. 146 SmallVector<StoredDiagnostic, 4> StoredDiagnostics; 147 148 /// \brief The set of diagnostics produced when failing to parse, e.g. due 149 /// to failure to load the PCH. 150 SmallVector<StoredDiagnostic, 4> FailedParseDiagnostics; 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 : 1; 259 260 /// \brief Whether to include brief documentation within the set of code 261 /// completions cached. 262 bool IncludeBriefCommentsInCodeCompletion : 1; 263 264 /// \brief True if non-system source files should be treated as volatile 265 /// (likely to change while trying to use them). 266 bool UserFilesAreVolatile : 1; 267 268 /// \brief The language options used when we load an AST file. 269 LangOptions ASTFileLangOpts; 270 271 static void ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags, 272 const char **ArgBegin, const char **ArgEnd, 273 ASTUnit &AST, bool CaptureDiagnostics); 274 275 void TranslateStoredDiagnostics(ASTReader *MMan, StringRef ModName, 276 SourceManager &SrcMan, 277 const SmallVectorImpl<StoredDiagnostic> &Diags, 278 SmallVectorImpl<StoredDiagnostic> &Out); 279 280 void clearFileLevelDecls(); 281 282public: 283 /// \brief A cached code-completion result, which may be introduced in one of 284 /// many different contexts. 285 struct CachedCodeCompletionResult { 286 /// \brief The code-completion string corresponding to this completion 287 /// result. 288 CodeCompletionString *Completion; 289 290 /// \brief A bitmask that indicates which code-completion contexts should 291 /// contain this completion result. 292 /// 293 /// The bits in the bitmask correspond to the values of 294 /// CodeCompleteContext::Kind. To map from a completion context kind to a 295 /// bit, shift 1 by that number of bits. Many completions can occur in 296 /// several different contexts. 297 uint64_t ShowInContexts; 298 299 /// \brief The priority given to this code-completion result. 300 unsigned Priority; 301 302 /// \brief The libclang cursor kind corresponding to this code-completion 303 /// result. 304 CXCursorKind Kind; 305 306 /// \brief The availability of this code-completion result. 307 CXAvailabilityKind Availability; 308 309 /// \brief The simplified type class for a non-macro completion result. 310 SimplifiedTypeClass TypeClass; 311 312 /// \brief The type of a non-macro completion result, stored as a unique 313 /// integer used by the string map of cached completion types. 314 /// 315 /// This value will be zero if the type is not known, or a unique value 316 /// determined by the formatted type string. Se \c CachedCompletionTypes 317 /// for more information. 318 unsigned Type; 319 }; 320 321 /// \brief Retrieve the mapping from formatted type names to unique type 322 /// identifiers. 323 llvm::StringMap<unsigned> &getCachedCompletionTypes() { 324 return CachedCompletionTypes; 325 } 326 327 /// \brief Retrieve the allocator used to cache global code completions. 328 IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> 329 getCachedCompletionAllocator() { 330 return CachedCompletionAllocator; 331 } 332 333 CodeCompletionTUInfo &getCodeCompletionTUInfo() { 334 if (!CCTUInfo) 335 CCTUInfo.reset(new CodeCompletionTUInfo( 336 new GlobalCodeCompletionAllocator)); 337 return *CCTUInfo; 338 } 339 340private: 341 /// \brief Allocator used to store cached code completions. 342 IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> 343 CachedCompletionAllocator; 344 345 OwningPtr<CodeCompletionTUInfo> CCTUInfo; 346 347 /// \brief The set of cached code-completion results. 348 std::vector<CachedCodeCompletionResult> CachedCompletionResults; 349 350 /// \brief A mapping from the formatted type name to a unique number for that 351 /// type, which is used for type equality comparisons. 352 llvm::StringMap<unsigned> CachedCompletionTypes; 353 354 /// \brief A string hash of the top-level declaration and macro definition 355 /// names processed the last time that we reparsed the file. 356 /// 357 /// This hash value is used to determine when we need to refresh the 358 /// global code-completion cache. 359 unsigned CompletionCacheTopLevelHashValue; 360 361 /// \brief A string hash of the top-level declaration and macro definition 362 /// names processed the last time that we reparsed the precompiled preamble. 363 /// 364 /// This hash value is used to determine when we need to refresh the 365 /// global code-completion cache after a rebuild of the precompiled preamble. 366 unsigned PreambleTopLevelHashValue; 367 368 /// \brief The current hash value for the top-level declaration and macro 369 /// definition names 370 unsigned CurrentTopLevelHashValue; 371 372 /// \brief Bit used by CIndex to mark when a translation unit may be in an 373 /// inconsistent state, and is not safe to free. 374 unsigned UnsafeToFree : 1; 375 376 /// \brief Cache any "global" code-completion results, so that we can avoid 377 /// recomputing them with each completion. 378 void CacheCodeCompletionResults(); 379 380 /// \brief Clear out and deallocate 381 void ClearCachedCompletionResults(); 382 383 ASTUnit(const ASTUnit &) LLVM_DELETED_FUNCTION; 384 void operator=(const ASTUnit &) LLVM_DELETED_FUNCTION; 385 386 explicit ASTUnit(bool MainFileIsAST); 387 388 void CleanTemporaryFiles(); 389 bool Parse(llvm::MemoryBuffer *OverrideMainBuffer); 390 391 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > 392 ComputePreamble(CompilerInvocation &Invocation, 393 unsigned MaxLines, bool &CreatedBuffer); 394 395 llvm::MemoryBuffer *getMainBufferWithPrecompiledPreamble( 396 const CompilerInvocation &PreambleInvocationIn, 397 bool AllowRebuild = true, 398 unsigned MaxLines = 0); 399 void RealizeTopLevelDeclsFromPreamble(); 400 401 /// \brief Transfers ownership of the objects (like SourceManager) from 402 /// \param CI to this ASTUnit. 403 void transferASTDataFromCompilerInstance(CompilerInstance &CI); 404 405 /// \brief Allows us to assert that ASTUnit is not being used concurrently, 406 /// which is not supported. 407 /// 408 /// Clients should create instances of the ConcurrencyCheck class whenever 409 /// using the ASTUnit in a way that isn't intended to be concurrent, which is 410 /// just about any usage. 411 /// Becomes a noop in release mode; only useful for debug mode checking. 412 class ConcurrencyState { 413#ifndef NDEBUG 414 void *Mutex; // a llvm::sys::MutexImpl in debug; 415#endif 416 417 public: 418 ConcurrencyState(); 419 ~ConcurrencyState(); 420 421 void start(); 422 void finish(); 423 }; 424 ConcurrencyState ConcurrencyCheckValue; 425 426public: 427 class ConcurrencyCheck { 428 ASTUnit &Self; 429 430 public: 431 explicit ConcurrencyCheck(ASTUnit &Self) 432 : Self(Self) 433 { 434 Self.ConcurrencyCheckValue.start(); 435 } 436 ~ConcurrencyCheck() { 437 Self.ConcurrencyCheckValue.finish(); 438 } 439 }; 440 friend class ConcurrencyCheck; 441 442 ~ASTUnit(); 443 444 bool isMainFileAST() const { return MainFileIsAST; } 445 446 bool isUnsafeToFree() const { return UnsafeToFree; } 447 void setUnsafeToFree(bool Value) { UnsafeToFree = Value; } 448 449 const DiagnosticsEngine &getDiagnostics() const { return *Diagnostics; } 450 DiagnosticsEngine &getDiagnostics() { return *Diagnostics; } 451 452 const SourceManager &getSourceManager() const { return *SourceMgr; } 453 SourceManager &getSourceManager() { return *SourceMgr; } 454 455 const Preprocessor &getPreprocessor() const { return *PP; } 456 Preprocessor &getPreprocessor() { return *PP; } 457 458 const ASTContext &getASTContext() const { return *Ctx; } 459 ASTContext &getASTContext() { return *Ctx; } 460 461 void setASTContext(ASTContext *ctx) { Ctx = ctx; } 462 void setPreprocessor(Preprocessor *pp); 463 464 bool hasSema() const { return TheSema; } 465 Sema &getSema() const { 466 assert(TheSema && "ASTUnit does not have a Sema object!"); 467 return *TheSema; 468 } 469 470 const FileManager &getFileManager() const { return *FileMgr; } 471 FileManager &getFileManager() { return *FileMgr; } 472 473 const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; } 474 475 const std::string &getOriginalSourceFileName(); 476 477 ASTDeserializationListener *getDeserializationListener(); 478 479 /// \brief Add a temporary file that the ASTUnit depends on. 480 /// 481 /// This file will be erased when the ASTUnit is destroyed. 482 void addTemporaryFile(const llvm::sys::Path &TempFile); 483 484 bool getOnlyLocalDecls() const { return OnlyLocalDecls; } 485 486 bool getOwnsRemappedFileBuffers() const { return OwnsRemappedFileBuffers; } 487 void setOwnsRemappedFileBuffers(bool val) { OwnsRemappedFileBuffers = val; } 488 489 StringRef getMainFileName() const; 490 491 typedef std::vector<Decl *>::iterator top_level_iterator; 492 493 top_level_iterator top_level_begin() { 494 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!"); 495 if (!TopLevelDeclsInPreamble.empty()) 496 RealizeTopLevelDeclsFromPreamble(); 497 return TopLevelDecls.begin(); 498 } 499 500 top_level_iterator top_level_end() { 501 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!"); 502 if (!TopLevelDeclsInPreamble.empty()) 503 RealizeTopLevelDeclsFromPreamble(); 504 return TopLevelDecls.end(); 505 } 506 507 std::size_t top_level_size() const { 508 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!"); 509 return TopLevelDeclsInPreamble.size() + TopLevelDecls.size(); 510 } 511 512 bool top_level_empty() const { 513 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!"); 514 return TopLevelDeclsInPreamble.empty() && TopLevelDecls.empty(); 515 } 516 517 /// \brief Add a new top-level declaration. 518 void addTopLevelDecl(Decl *D) { 519 TopLevelDecls.push_back(D); 520 } 521 522 /// \brief Add a new local file-level declaration. 523 void addFileLevelDecl(Decl *D); 524 525 /// \brief Get the decls that are contained in a file in the Offset/Length 526 /// range. \p Length can be 0 to indicate a point at \p Offset instead of 527 /// a range. 528 void findFileRegionDecls(FileID File, unsigned Offset, unsigned Length, 529 SmallVectorImpl<Decl *> &Decls); 530 531 /// \brief Add a new top-level declaration, identified by its ID in 532 /// the precompiled preamble. 533 void addTopLevelDeclFromPreamble(serialization::DeclID D) { 534 TopLevelDeclsInPreamble.push_back(D); 535 } 536 537 /// \brief Retrieve a reference to the current top-level name hash value. 538 /// 539 /// Note: This is used internally by the top-level tracking action 540 unsigned &getCurrentTopLevelHashValue() { return CurrentTopLevelHashValue; } 541 542 /// \brief Get the source location for the given file:line:col triplet. 543 /// 544 /// The difference with SourceManager::getLocation is that this method checks 545 /// whether the requested location points inside the precompiled preamble 546 /// in which case the returned source location will be a "loaded" one. 547 SourceLocation getLocation(const FileEntry *File, 548 unsigned Line, unsigned Col) const; 549 550 /// \brief Get the source location for the given file:offset pair. 551 SourceLocation getLocation(const FileEntry *File, unsigned Offset) const; 552 553 /// \brief If \p Loc is a loaded location from the preamble, returns 554 /// the corresponding local location of the main file, otherwise it returns 555 /// \p Loc. 556 SourceLocation mapLocationFromPreamble(SourceLocation Loc); 557 558 /// \brief If \p Loc is a local location of the main file but inside the 559 /// preamble chunk, returns the corresponding loaded location from the 560 /// preamble, otherwise it returns \p Loc. 561 SourceLocation mapLocationToPreamble(SourceLocation Loc); 562 563 bool isInPreambleFileID(SourceLocation Loc); 564 bool isInMainFileID(SourceLocation Loc); 565 SourceLocation getStartOfMainFileID(); 566 SourceLocation getEndOfPreambleFileID(); 567 568 /// \see mapLocationFromPreamble. 569 SourceRange mapRangeFromPreamble(SourceRange R) { 570 return SourceRange(mapLocationFromPreamble(R.getBegin()), 571 mapLocationFromPreamble(R.getEnd())); 572 } 573 574 /// \see mapLocationToPreamble. 575 SourceRange mapRangeToPreamble(SourceRange R) { 576 return SourceRange(mapLocationToPreamble(R.getBegin()), 577 mapLocationToPreamble(R.getEnd())); 578 } 579 580 // Retrieve the diagnostics associated with this AST 581 typedef StoredDiagnostic *stored_diag_iterator; 582 typedef const StoredDiagnostic *stored_diag_const_iterator; 583 stored_diag_const_iterator stored_diag_begin() const { 584 return StoredDiagnostics.begin(); 585 } 586 stored_diag_iterator stored_diag_begin() { 587 return StoredDiagnostics.begin(); 588 } 589 stored_diag_const_iterator stored_diag_end() const { 590 return StoredDiagnostics.end(); 591 } 592 stored_diag_iterator stored_diag_end() { 593 return StoredDiagnostics.end(); 594 } 595 unsigned stored_diag_size() const { return StoredDiagnostics.size(); } 596 597 stored_diag_iterator stored_diag_afterDriver_begin() { 598 if (NumStoredDiagnosticsFromDriver > StoredDiagnostics.size()) 599 NumStoredDiagnosticsFromDriver = 0; 600 return StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver; 601 } 602 603 typedef std::vector<CachedCodeCompletionResult>::iterator 604 cached_completion_iterator; 605 606 cached_completion_iterator cached_completion_begin() { 607 return CachedCompletionResults.begin(); 608 } 609 610 cached_completion_iterator cached_completion_end() { 611 return CachedCompletionResults.end(); 612 } 613 614 unsigned cached_completion_size() const { 615 return CachedCompletionResults.size(); 616 } 617 618 /// \brief Returns an iterator range for the local preprocessing entities 619 /// of the local Preprocessor, if this is a parsed source file, or the loaded 620 /// preprocessing entities of the primary module if this is an AST file. 621 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator> 622 getLocalPreprocessingEntities() const; 623 624 /// \brief Type for a function iterating over a number of declarations. 625 /// \returns true to continue iteration and false to abort. 626 typedef bool (*DeclVisitorFn)(void *context, const Decl *D); 627 628 /// \brief Iterate over local declarations (locally parsed if this is a parsed 629 /// source file or the loaded declarations of the primary module if this is an 630 /// AST file). 631 /// \returns true if the iteration was complete or false if it was aborted. 632 bool visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn); 633 634 /// \brief Get the PCH file if one was included. 635 const FileEntry *getPCHFile(); 636 637 /// \brief Returns true if the ASTUnit was constructed from a serialized 638 /// module file. 639 bool isModuleFile(); 640 641 llvm::MemoryBuffer *getBufferForFile(StringRef Filename, 642 std::string *ErrorStr = 0); 643 644 /// \brief Determine what kind of translation unit this AST represents. 645 TranslationUnitKind getTranslationUnitKind() const { return TUKind; } 646 647 typedef llvm::PointerUnion<const char *, const llvm::MemoryBuffer *> 648 FilenameOrMemBuf; 649 /// \brief A mapping from a file name to the memory buffer that stores the 650 /// remapped contents of that file. 651 typedef std::pair<std::string, FilenameOrMemBuf> RemappedFile; 652 653 /// \brief Create a ASTUnit. Gets ownership of the passed CompilerInvocation. 654 static ASTUnit *create(CompilerInvocation *CI, 655 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, 656 bool CaptureDiagnostics, 657 bool UserFilesAreVolatile); 658 659 /// \brief Create a ASTUnit from an AST file. 660 /// 661 /// \param Filename - The AST file to load. 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 /// \returns - The initialized ASTUnit or null if the AST failed to load. 667 static ASTUnit *LoadFromASTFile(const std::string &Filename, 668 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, 669 const FileSystemOptions &FileSystemOpts, 670 bool OnlyLocalDecls = false, 671 RemappedFile *RemappedFiles = 0, 672 unsigned NumRemappedFiles = 0, 673 bool CaptureDiagnostics = false, 674 bool AllowPCHWithCompilerErrors = false, 675 bool UserFilesAreVolatile = false); 676 677private: 678 /// \brief Helper function for \c LoadFromCompilerInvocation() and 679 /// \c LoadFromCommandLine(), which loads an AST from a compiler invocation. 680 /// 681 /// \param PrecompilePreamble Whether to precompile the preamble of this 682 /// translation unit, to improve the performance of reparsing. 683 /// 684 /// \returns \c true if a catastrophic failure occurred (which means that the 685 /// \c ASTUnit itself is invalid), or \c false otherwise. 686 bool LoadFromCompilerInvocation(bool PrecompilePreamble); 687 688public: 689 690 /// \brief Create an ASTUnit from a source file, via a CompilerInvocation 691 /// object, by invoking the optionally provided ASTFrontendAction. 692 /// 693 /// \param CI - The compiler invocation to use; it must have exactly one input 694 /// source file. The ASTUnit takes ownership of the CompilerInvocation object. 695 /// 696 /// \param Diags - The diagnostics engine to use for reporting errors; its 697 /// lifetime is expected to extend past that of the returned ASTUnit. 698 /// 699 /// \param Action - The ASTFrontendAction to invoke. Its ownership is not 700 /// transfered. 701 /// 702 /// \param Unit - optionally an already created ASTUnit. Its ownership is not 703 /// transfered. 704 /// 705 /// \param Persistent - if true the returned ASTUnit will be complete. 706 /// false means the caller is only interested in getting info through the 707 /// provided \see Action. 708 /// 709 /// \param ErrAST - If non-null and parsing failed without any AST to return 710 /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit 711 /// mainly to allow the caller to see the diagnostics. 712 /// This will only receive an ASTUnit if a new one was created. If an already 713 /// created ASTUnit was passed in \p Unit then the caller can check that. 714 /// 715 static ASTUnit *LoadFromCompilerInvocationAction(CompilerInvocation *CI, 716 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, 717 ASTFrontendAction *Action = 0, 718 ASTUnit *Unit = 0, 719 bool Persistent = true, 720 StringRef ResourceFilesPath = StringRef(), 721 bool OnlyLocalDecls = false, 722 bool CaptureDiagnostics = false, 723 bool PrecompilePreamble = false, 724 bool CacheCodeCompletionResults = false, 725 bool IncludeBriefCommentsInCodeCompletion = false, 726 bool UserFilesAreVolatile = false, 727 OwningPtr<ASTUnit> *ErrAST = 0); 728 729 /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, via a 730 /// CompilerInvocation object. 731 /// 732 /// \param CI - The compiler invocation to use; it must have exactly one input 733 /// source file. The ASTUnit takes ownership of the CompilerInvocation object. 734 /// 735 /// \param Diags - The diagnostics engine to use for reporting errors; its 736 /// lifetime is expected to extend past that of the returned ASTUnit. 737 // 738 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we 739 // shouldn't need to specify them at construction time. 740 static ASTUnit *LoadFromCompilerInvocation(CompilerInvocation *CI, 741 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, 742 bool OnlyLocalDecls = false, 743 bool CaptureDiagnostics = false, 744 bool PrecompilePreamble = false, 745 TranslationUnitKind TUKind = TU_Complete, 746 bool CacheCodeCompletionResults = false, 747 bool IncludeBriefCommentsInCodeCompletion = false, 748 bool UserFilesAreVolatile = false); 749 750 /// LoadFromCommandLine - Create an ASTUnit from a vector of command line 751 /// arguments, which must specify exactly one source file. 752 /// 753 /// \param ArgBegin - The beginning of the argument vector. 754 /// 755 /// \param ArgEnd - The end of the argument vector. 756 /// 757 /// \param Diags - The diagnostics engine to use for reporting errors; its 758 /// lifetime is expected to extend past that of the returned ASTUnit. 759 /// 760 /// \param ResourceFilesPath - The path to the compiler resource files. 761 /// 762 /// \param ErrAST - If non-null and parsing failed without any AST to return 763 /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit 764 /// mainly to allow the caller to see the diagnostics. 765 /// 766 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we 767 // shouldn't need to specify them at construction time. 768 static ASTUnit *LoadFromCommandLine(const char **ArgBegin, 769 const char **ArgEnd, 770 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, 771 StringRef ResourceFilesPath, 772 bool OnlyLocalDecls = false, 773 bool CaptureDiagnostics = false, 774 RemappedFile *RemappedFiles = 0, 775 unsigned NumRemappedFiles = 0, 776 bool RemappedFilesKeepOriginalName = true, 777 bool PrecompilePreamble = false, 778 TranslationUnitKind TUKind = TU_Complete, 779 bool CacheCodeCompletionResults = false, 780 bool IncludeBriefCommentsInCodeCompletion = false, 781 bool AllowPCHWithCompilerErrors = false, 782 bool SkipFunctionBodies = false, 783 bool UserFilesAreVolatile = false, 784 bool ForSerialization = false, 785 OwningPtr<ASTUnit> *ErrAST = 0); 786 787 /// \brief Reparse the source files using the same command-line options that 788 /// were originally used to produce this translation unit. 789 /// 790 /// \returns True if a failure occurred that causes the ASTUnit not to 791 /// contain any translation-unit information, false otherwise. 792 bool Reparse(RemappedFile *RemappedFiles = 0, 793 unsigned NumRemappedFiles = 0); 794 795 /// \brief Perform code completion at the given file, line, and 796 /// column within this translation unit. 797 /// 798 /// \param File The file in which code completion will occur. 799 /// 800 /// \param Line The line at which code completion will occur. 801 /// 802 /// \param Column The column at which code completion will occur. 803 /// 804 /// \param IncludeMacros Whether to include macros in the code-completion 805 /// results. 806 /// 807 /// \param IncludeCodePatterns Whether to include code patterns (such as a 808 /// for loop) in the code-completion results. 809 /// 810 /// \param IncludeBriefComments Whether to include brief documentation within 811 /// the set of code completions returned. 812 /// 813 /// FIXME: The Diag, LangOpts, SourceMgr, FileMgr, StoredDiagnostics, and 814 /// OwnedBuffers parameters are all disgusting hacks. They will go away. 815 void CodeComplete(StringRef File, unsigned Line, unsigned Column, 816 RemappedFile *RemappedFiles, unsigned NumRemappedFiles, 817 bool IncludeMacros, bool IncludeCodePatterns, 818 bool IncludeBriefComments, 819 CodeCompleteConsumer &Consumer, 820 DiagnosticsEngine &Diag, LangOptions &LangOpts, 821 SourceManager &SourceMgr, FileManager &FileMgr, 822 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics, 823 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers); 824 825 /// \brief Save this translation unit to a file with the given name. 826 /// 827 /// \returns true if there was a file error or false if the save was 828 /// successful. 829 bool Save(StringRef File); 830 831 /// \brief Serialize this translation unit with the given output stream. 832 /// 833 /// \returns True if an error occurred, false otherwise. 834 bool serialize(raw_ostream &OS); 835 836 virtual Module *loadModule(SourceLocation ImportLoc, ModuleIdPath Path, 837 Module::NameVisibilityKind Visibility, 838 bool IsInclusionDirective) { 839 // ASTUnit doesn't know how to load modules (not that this matters). 840 return 0; 841 } 842}; 843 844} // namespace clang 845 846#endif 847