ASTUnit.h revision 8fa0a80b4482ad94e82c4a19e23de17fd69140b5
1fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org//===--- ASTUnit.h - ASTUnit utility ----------------------------*- C++ -*-===// 2fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org// 3fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org// The LLVM Compiler Infrastructure 4fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org// 5fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org// This file is distributed under the University of Illinois Open Source 6fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org// License. See LICENSE.TXT for details. 7fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org// 8fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org//===----------------------------------------------------------------------===// 9fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org// 10fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org// ASTUnit utility class. 11fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org// 12fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org//===----------------------------------------------------------------------===// 13fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org 14fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org#ifndef LLVM_CLANG_FRONTEND_ASTUNIT_H 15fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org#define LLVM_CLANG_FRONTEND_ASTUNIT_H 16fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org 17fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org#include "clang/Index/ASTLocation.h" 18fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org#include "clang/Serialization/ASTBitCodes.h" 19fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org#include "clang/Sema/Sema.h" 20fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org#include "clang/Sema/CodeCompleteConsumer.h" 21fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org#include "clang/Lex/PreprocessingRecord.h" 22fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org#include "clang/Basic/SourceManager.h" 23fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org#include "clang/Basic/FileManager.h" 24fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org#include "clang/Basic/FileSystemOptions.h" 25fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org#include "clang-c/Index.h" 26fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org#include "llvm/ADT/IntrusiveRefCntPtr.h" 27fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org#include "llvm/ADT/OwningPtr.h" 28fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org#include "llvm/ADT/SmallVector.h" 29fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org#include "llvm/ADT/StringMap.h" 30fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org#include "llvm/Support/Path.h" 31fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org#include <map> 32fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org#include <string> 33fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org#include <vector> 34fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org#include <cassert> 35fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org#include <utility> 36fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org#include <sys/types.h> 37f539318f0d3dba743ec1886d5d9df0fb1be628a1tfarina 38fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.orgnamespace llvm { 39fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org class MemoryBuffer; 40fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org} 41fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org 42fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.orgnamespace clang { 43fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.orgclass ASTContext; 44fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.orgclass ASTReader; 45fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.orgclass CodeCompleteConsumer; 46fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.orgclass CompilerInvocation; 47fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.orgclass Decl; 48fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.orgclass Diagnostic; 49fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.orgclass FileEntry; 50fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.orgclass FileManager; 51fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.orgclass HeaderSearch; 52fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.orgclass Preprocessor; 53fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.orgclass SourceManager; 54fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.orgclass TargetInfo; 55fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.orgclass ASTFrontendAction; 56fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org 57fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.orgusing namespace idx; 58fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org 59fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org/// \brief Allocator for a cached set of global code completions. 60fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.orgclass GlobalCodeCompletionAllocator 61fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org : public CodeCompletionAllocator, 62fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org public llvm::RefCountedBase<GlobalCodeCompletionAllocator> 63fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org{ 64fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org 65fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org}; 66fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org 67fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org/// \brief Utility class for loading a ASTContext from an AST file. 68fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org/// 69fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.orgclass ASTUnit { 70fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.orgpublic: 71fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org typedef std::map<FileID, std::vector<PreprocessedEntity *> > 72fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org PreprocessedEntitiesByFileMap; 73fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org 74fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.orgprivate: 75fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org llvm::IntrusiveRefCntPtr<Diagnostic> Diagnostics; 766aeabb16942ead34a2ec985843549f7f4c1ea762senorblanco@chromium.org llvm::IntrusiveRefCntPtr<FileManager> FileMgr; 776aeabb16942ead34a2ec985843549f7f4c1ea762senorblanco@chromium.org llvm::IntrusiveRefCntPtr<SourceManager> SourceMgr; 78fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org llvm::OwningPtr<HeaderSearch> HeaderInfo; 79fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org llvm::IntrusiveRefCntPtr<TargetInfo> Target; 80fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org llvm::IntrusiveRefCntPtr<Preprocessor> PP; 81fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org llvm::IntrusiveRefCntPtr<ASTContext> Ctx; 82fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org 836aeabb16942ead34a2ec985843549f7f4c1ea762senorblanco@chromium.org FileSystemOptions FileSystemOpts; 84fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org 85fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org /// \brief The AST consumer that received information about the translation 86fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org /// unit as it was parsed or loaded. 87fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org llvm::OwningPtr<ASTConsumer> Consumer; 88fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org 89fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org /// \brief The semantic analysis object used to type-check the translation 90fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org /// unit. 91fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org llvm::OwningPtr<Sema> TheSema; 92fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org 93fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org /// Optional owned invocation, just used to make the invocation used in 94fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org /// LoadFromCommandLine available. 95fd0ec2c76a27ce26a62da23eb75017839959e7cbsenorblanco@chromium.org llvm::IntrusiveRefCntPtr<CompilerInvocation> Invocation; 96 97 /// \brief The set of target features. 98 /// 99 /// FIXME: each time we reparse, we need to restore the set of target 100 /// features from this vector, because TargetInfo::CreateTargetInfo() 101 /// mangles the target options in place. Yuck! 102 std::vector<std::string> TargetFeatures; 103 104 // OnlyLocalDecls - when true, walking this AST should only visit declarations 105 // that come from the AST itself, not from included precompiled headers. 106 // FIXME: This is temporary; eventually, CIndex will always do this. 107 bool OnlyLocalDecls; 108 109 /// \brief Whether to capture any diagnostics produced. 110 bool CaptureDiagnostics; 111 112 /// \brief Track whether the main file was loaded from an AST or not. 113 bool MainFileIsAST; 114 115 /// \brief Whether this AST represents a complete translation unit. 116 bool CompleteTranslationUnit; 117 118 /// \brief Whether we should time each operation. 119 bool WantTiming; 120 121 /// \brief Whether the ASTUnit should delete the remapped buffers. 122 bool OwnsRemappedFileBuffers; 123 124 /// Track the top-level decls which appeared in an ASTUnit which was loaded 125 /// from a source file. 126 // 127 // FIXME: This is just an optimization hack to avoid deserializing large parts 128 // of a PCH file when using the Index library on an ASTUnit loaded from 129 // source. In the long term we should make the Index library use efficient and 130 // more scalable search mechanisms. 131 std::vector<Decl*> TopLevelDecls; 132 133 /// \brief The list of preprocessed entities which appeared when the ASTUnit 134 /// was loaded. 135 /// 136 /// FIXME: This is just an optimization hack to avoid deserializing large 137 /// parts of a PCH file while performing a walk or search. In the long term, 138 /// we should provide more scalable search mechanisms. 139 std::vector<PreprocessedEntity *> PreprocessedEntities; 140 141 /// The name of the original source file used to generate this ASTUnit. 142 std::string OriginalSourceFile; 143 144 // Critical optimization when using clang_getCursor(). 145 ASTLocation LastLoc; 146 147 /// \brief The set of diagnostics produced when creating the preamble. 148 SmallVector<StoredDiagnostic, 4> PreambleDiagnostics; 149 150 /// \brief The set of diagnostics produced when creating this 151 /// translation unit. 152 SmallVector<StoredDiagnostic, 4> StoredDiagnostics; 153 154 /// \brief The number of stored diagnostics that come from the driver 155 /// itself. 156 /// 157 /// Diagnostics that come from the driver are retained from one parse to 158 /// the next. 159 unsigned NumStoredDiagnosticsFromDriver; 160 161 /// \brief Temporary files that should be removed when the ASTUnit is 162 /// destroyed. 163 SmallVector<llvm::sys::Path, 4> TemporaryFiles; 164 165 /// \brief A mapping from file IDs to the set of preprocessed entities 166 /// stored in that file. 167 /// 168 /// FIXME: This is just an optimization hack to avoid searching through 169 /// many preprocessed entities during cursor traversal in the CIndex library. 170 /// Ideally, we would just be able to perform a binary search within the 171 /// list of preprocessed entities. 172 PreprocessedEntitiesByFileMap PreprocessedEntitiesByFile; 173 174 /// \brief Simple hack to allow us to assert that ASTUnit is not being 175 /// used concurrently, which is not supported. 176 /// 177 /// Clients should create instances of the ConcurrencyCheck class whenever 178 /// using the ASTUnit in a way that isn't intended to be concurrent, which is 179 /// just about any usage. 180 unsigned int ConcurrencyCheckValue; 181 static const unsigned int CheckLocked = 28573289; 182 static const unsigned int CheckUnlocked = 9803453; 183 184 /// \brief Counter that determines when we want to try building a 185 /// precompiled preamble. 186 /// 187 /// If zero, we will never build a precompiled preamble. Otherwise, 188 /// it's treated as a counter that decrements each time we reparse 189 /// without the benefit of a precompiled preamble. When it hits 1, 190 /// we'll attempt to rebuild the precompiled header. This way, if 191 /// building the precompiled preamble fails, we won't try again for 192 /// some number of calls. 193 unsigned PreambleRebuildCounter; 194 195 /// \brief The file in which the precompiled preamble is stored. 196 std::string PreambleFile; 197 198 /// \brief The contents of the preamble that has been precompiled to 199 /// \c PreambleFile. 200 std::vector<char> Preamble; 201 202 /// \brief Whether the preamble ends at the start of a new line. 203 /// 204 /// Used to inform the lexer as to whether it's starting at the beginning of 205 /// a line after skipping the preamble. 206 bool PreambleEndsAtStartOfLine; 207 208 /// \brief The size of the source buffer that we've reserved for the main 209 /// file within the precompiled preamble. 210 unsigned PreambleReservedSize; 211 212 /// \brief Keeps track of the files that were used when computing the 213 /// preamble, with both their buffer size and their modification time. 214 /// 215 /// If any of the files have changed from one compile to the next, 216 /// the preamble must be thrown away. 217 llvm::StringMap<std::pair<off_t, time_t> > FilesInPreamble; 218 219 /// \brief When non-NULL, this is the buffer used to store the contents of 220 /// the main file when it has been padded for use with the precompiled 221 /// preamble. 222 llvm::MemoryBuffer *SavedMainFileBuffer; 223 224 /// \brief When non-NULL, this is the buffer used to store the 225 /// contents of the preamble when it has been padded to build the 226 /// precompiled preamble. 227 llvm::MemoryBuffer *PreambleBuffer; 228 229 /// \brief The number of warnings that occurred while parsing the preamble. 230 /// 231 /// This value will be used to restore the state of the \c Diagnostic object 232 /// when re-using the precompiled preamble. Note that only the 233 /// number of warnings matters, since we will not save the preamble 234 /// when any errors are present. 235 unsigned NumWarningsInPreamble; 236 237 /// \brief A list of the serialization ID numbers for each of the top-level 238 /// declarations parsed within the precompiled preamble. 239 std::vector<serialization::DeclID> TopLevelDeclsInPreamble; 240 241 /// \brief A list of the offsets into the precompiled preamble which 242 /// correspond to preprocessed entities. 243 std::vector<uint64_t> PreprocessedEntitiesInPreamble; 244 245 /// \brief Whether we should be caching code-completion results. 246 bool ShouldCacheCodeCompletionResults; 247 248 /// \brief Whether we want to include nested macro expansions in the 249 /// detailed preprocessing record. 250 bool NestedMacroExpansions; 251 252 static void ConfigureDiags(llvm::IntrusiveRefCntPtr<Diagnostic> &Diags, 253 const char **ArgBegin, const char **ArgEnd, 254 ASTUnit &AST, bool CaptureDiagnostics); 255 256 void TranslateStoredDiagnostics(ASTReader *MMan, StringRef ModName, 257 SourceManager &SrcMan, 258 const SmallVectorImpl<StoredDiagnostic> &Diags, 259 SmallVectorImpl<StoredDiagnostic> &Out); 260 261public: 262 /// \brief A cached code-completion result, which may be introduced in one of 263 /// many different contexts. 264 struct CachedCodeCompletionResult { 265 /// \brief The code-completion string corresponding to this completion 266 /// result. 267 CodeCompletionString *Completion; 268 269 /// \brief A bitmask that indicates which code-completion contexts should 270 /// contain this completion result. 271 /// 272 /// The bits in the bitmask correspond to the values of 273 /// CodeCompleteContext::Kind. To map from a completion context kind to a 274 /// bit, subtract one from the completion context kind and shift 1 by that 275 /// number of bits. Many completions can occur in several different 276 /// contexts. 277 unsigned ShowInContexts; 278 279 /// \brief The priority given to this code-completion result. 280 unsigned Priority; 281 282 /// \brief The libclang cursor kind corresponding to this code-completion 283 /// result. 284 CXCursorKind Kind; 285 286 /// \brief The availability of this code-completion result. 287 CXAvailabilityKind Availability; 288 289 /// \brief The simplified type class for a non-macro completion result. 290 SimplifiedTypeClass TypeClass; 291 292 /// \brief The type of a non-macro completion result, stored as a unique 293 /// integer used by the string map of cached completion types. 294 /// 295 /// This value will be zero if the type is not known, or a unique value 296 /// determined by the formatted type string. Se \c CachedCompletionTypes 297 /// for more information. 298 unsigned Type; 299 }; 300 301 /// \brief Retrieve the mapping from formatted type names to unique type 302 /// identifiers. 303 llvm::StringMap<unsigned> &getCachedCompletionTypes() { 304 return CachedCompletionTypes; 305 } 306 307 /// \brief Retrieve the allocator used to cache global code completions. 308 llvm::IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> 309 getCachedCompletionAllocator() { 310 return CachedCompletionAllocator; 311 } 312 313 /// \brief Retrieve the allocator used to cache global code completions. 314 /// Creates the allocator if it doesn't already exist. 315 llvm::IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> 316 getCursorCompletionAllocator() { 317 if (!CursorCompletionAllocator.getPtr()) { 318 CursorCompletionAllocator = new GlobalCodeCompletionAllocator; 319 } 320 return CursorCompletionAllocator; 321 } 322 323private: 324 /// \brief Allocator used to store cached code completions. 325 llvm::IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> 326 CachedCompletionAllocator; 327 328 /// \brief Allocator used to store code completions for arbitrary cursors. 329 llvm::IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> 330 CursorCompletionAllocator; 331 332 /// \brief The set of cached code-completion results. 333 std::vector<CachedCodeCompletionResult> CachedCompletionResults; 334 335 /// \brief A mapping from the formatted type name to a unique number for that 336 /// type, which is used for type equality comparisons. 337 llvm::StringMap<unsigned> CachedCompletionTypes; 338 339 /// \brief A string hash of the top-level declaration and macro definition 340 /// names processed the last time that we reparsed the file. 341 /// 342 /// This hash value is used to determine when we need to refresh the 343 /// global code-completion cache. 344 unsigned CompletionCacheTopLevelHashValue; 345 346 /// \brief A string hash of the top-level declaration and macro definition 347 /// names processed the last time that we reparsed the precompiled preamble. 348 /// 349 /// This hash value is used to determine when we need to refresh the 350 /// global code-completion cache after a rebuild of the precompiled preamble. 351 unsigned PreambleTopLevelHashValue; 352 353 /// \brief The current hash value for the top-level declaration and macro 354 /// definition names 355 unsigned CurrentTopLevelHashValue; 356 357 /// \brief Bit used by CIndex to mark when a translation unit may be in an 358 /// inconsistent state, and is not safe to free. 359 unsigned UnsafeToFree : 1; 360 361 /// \brief Cache any "global" code-completion results, so that we can avoid 362 /// recomputing them with each completion. 363 void CacheCodeCompletionResults(); 364 365 /// \brief Clear out and deallocate 366 void ClearCachedCompletionResults(); 367 368 ASTUnit(const ASTUnit&); // DO NOT IMPLEMENT 369 ASTUnit &operator=(const ASTUnit &); // DO NOT IMPLEMENT 370 371 explicit ASTUnit(bool MainFileIsAST); 372 373 void CleanTemporaryFiles(); 374 bool Parse(llvm::MemoryBuffer *OverrideMainBuffer); 375 376 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > 377 ComputePreamble(CompilerInvocation &Invocation, 378 unsigned MaxLines, bool &CreatedBuffer); 379 380 llvm::MemoryBuffer *getMainBufferWithPrecompiledPreamble( 381 const CompilerInvocation &PreambleInvocationIn, 382 bool AllowRebuild = true, 383 unsigned MaxLines = 0); 384 void RealizeTopLevelDeclsFromPreamble(); 385 void RealizePreprocessedEntitiesFromPreamble(); 386 387public: 388 class ConcurrencyCheck { 389 volatile ASTUnit &Self; 390 391 public: 392 explicit ConcurrencyCheck(ASTUnit &Self) 393 : Self(Self) 394 { 395 assert(Self.ConcurrencyCheckValue == CheckUnlocked && 396 "Concurrent access to ASTUnit!"); 397 Self.ConcurrencyCheckValue = CheckLocked; 398 } 399 400 ~ConcurrencyCheck() { 401 Self.ConcurrencyCheckValue = CheckUnlocked; 402 } 403 }; 404 friend class ConcurrencyCheck; 405 406 ~ASTUnit(); 407 408 bool isMainFileAST() const { return MainFileIsAST; } 409 410 bool isUnsafeToFree() const { return UnsafeToFree; } 411 void setUnsafeToFree(bool Value) { UnsafeToFree = Value; } 412 413 const Diagnostic &getDiagnostics() const { return *Diagnostics; } 414 Diagnostic &getDiagnostics() { return *Diagnostics; } 415 416 const SourceManager &getSourceManager() const { return *SourceMgr; } 417 SourceManager &getSourceManager() { return *SourceMgr; } 418 419 const Preprocessor &getPreprocessor() const { return *PP; } 420 Preprocessor &getPreprocessor() { return *PP; } 421 422 const ASTContext &getASTContext() const { return *Ctx; } 423 ASTContext &getASTContext() { return *Ctx; } 424 425 bool hasSema() const { return TheSema; } 426 Sema &getSema() const { 427 assert(TheSema && "ASTUnit does not have a Sema object!"); 428 return *TheSema; 429 } 430 431 const FileManager &getFileManager() const { return *FileMgr; } 432 FileManager &getFileManager() { return *FileMgr; } 433 434 const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; } 435 436 const std::string &getOriginalSourceFileName(); 437 const std::string &getASTFileName(); 438 439 /// \brief Add a temporary file that the ASTUnit depends on. 440 /// 441 /// This file will be erased when the ASTUnit is destroyed. 442 void addTemporaryFile(const llvm::sys::Path &TempFile) { 443 TemporaryFiles.push_back(TempFile); 444 } 445 446 bool getOnlyLocalDecls() const { return OnlyLocalDecls; } 447 448 bool getOwnsRemappedFileBuffers() const { return OwnsRemappedFileBuffers; } 449 void setOwnsRemappedFileBuffers(bool val) { OwnsRemappedFileBuffers = val; } 450 451 /// \brief Retrieve the maximum PCH level of declarations that a 452 /// traversal of the translation unit should consider. 453 unsigned getMaxPCHLevel() const; 454 455 void setLastASTLocation(ASTLocation ALoc) { LastLoc = ALoc; } 456 ASTLocation getLastASTLocation() const { return LastLoc; } 457 458 459 StringRef getMainFileName() const; 460 461 typedef std::vector<Decl *>::iterator top_level_iterator; 462 463 top_level_iterator top_level_begin() { 464 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!"); 465 if (!TopLevelDeclsInPreamble.empty()) 466 RealizeTopLevelDeclsFromPreamble(); 467 return TopLevelDecls.begin(); 468 } 469 470 top_level_iterator top_level_end() { 471 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!"); 472 if (!TopLevelDeclsInPreamble.empty()) 473 RealizeTopLevelDeclsFromPreamble(); 474 return TopLevelDecls.end(); 475 } 476 477 std::size_t top_level_size() const { 478 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!"); 479 return TopLevelDeclsInPreamble.size() + TopLevelDecls.size(); 480 } 481 482 bool top_level_empty() const { 483 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!"); 484 return TopLevelDeclsInPreamble.empty() && TopLevelDecls.empty(); 485 } 486 487 /// \brief Add a new top-level declaration. 488 void addTopLevelDecl(Decl *D) { 489 TopLevelDecls.push_back(D); 490 } 491 492 /// \brief Add a new top-level declaration, identified by its ID in 493 /// the precompiled preamble. 494 void addTopLevelDeclFromPreamble(serialization::DeclID D) { 495 TopLevelDeclsInPreamble.push_back(D); 496 } 497 498 /// \brief Retrieve a reference to the current top-level name hash value. 499 /// 500 /// Note: This is used internally by the top-level tracking action 501 unsigned &getCurrentTopLevelHashValue() { return CurrentTopLevelHashValue; } 502 503 typedef std::vector<PreprocessedEntity *>::iterator pp_entity_iterator; 504 505 pp_entity_iterator pp_entity_begin(); 506 pp_entity_iterator pp_entity_end(); 507 508 /// \brief Add a new preprocessed entity that's stored at the given offset 509 /// in the precompiled preamble. 510 void addPreprocessedEntityFromPreamble(uint64_t Offset) { 511 PreprocessedEntitiesInPreamble.push_back(Offset); 512 } 513 514 /// \brief Retrieve the mapping from File IDs to the preprocessed entities 515 /// within that file. 516 PreprocessedEntitiesByFileMap &getPreprocessedEntitiesByFile() { 517 return PreprocessedEntitiesByFile; 518 } 519 520 // Retrieve the diagnostics associated with this AST 521 typedef const StoredDiagnostic *stored_diag_iterator; 522 stored_diag_iterator stored_diag_begin() const { 523 return StoredDiagnostics.begin(); 524 } 525 stored_diag_iterator stored_diag_end() const { 526 return StoredDiagnostics.end(); 527 } 528 unsigned stored_diag_size() const { return StoredDiagnostics.size(); } 529 530 SmallVector<StoredDiagnostic, 4> &getStoredDiagnostics() { 531 return StoredDiagnostics; 532 } 533 534 typedef std::vector<CachedCodeCompletionResult>::iterator 535 cached_completion_iterator; 536 537 cached_completion_iterator cached_completion_begin() { 538 return CachedCompletionResults.begin(); 539 } 540 541 cached_completion_iterator cached_completion_end() { 542 return CachedCompletionResults.end(); 543 } 544 545 unsigned cached_completion_size() const { 546 return CachedCompletionResults.size(); 547 } 548 549 llvm::MemoryBuffer *getBufferForFile(StringRef Filename, 550 std::string *ErrorStr = 0); 551 552 /// \brief Whether this AST represents a complete translation unit. 553 /// 554 /// If false, this AST is only a partial translation unit, e.g., one 555 /// that might still be used as a precompiled header or preamble. 556 bool isCompleteTranslationUnit() const { return CompleteTranslationUnit; } 557 558 typedef llvm::PointerUnion<const char *, const llvm::MemoryBuffer *> 559 FilenameOrMemBuf; 560 /// \brief A mapping from a file name to the memory buffer that stores the 561 /// remapped contents of that file. 562 typedef std::pair<std::string, FilenameOrMemBuf> RemappedFile; 563 564 /// \brief Create a ASTUnit. Gets ownership of the passed CompilerInvocation. 565 static ASTUnit *create(CompilerInvocation *CI, 566 llvm::IntrusiveRefCntPtr<Diagnostic> Diags); 567 568 /// \brief Create a ASTUnit from an AST file. 569 /// 570 /// \param Filename - The AST file to load. 571 /// 572 /// \param Diags - The diagnostics engine to use for reporting errors; its 573 /// lifetime is expected to extend past that of the returned ASTUnit. 574 /// 575 /// \returns - The initialized ASTUnit or null if the AST failed to load. 576 static ASTUnit *LoadFromASTFile(const std::string &Filename, 577 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 578 const FileSystemOptions &FileSystemOpts, 579 bool OnlyLocalDecls = false, 580 RemappedFile *RemappedFiles = 0, 581 unsigned NumRemappedFiles = 0, 582 bool CaptureDiagnostics = false); 583 584private: 585 /// \brief Helper function for \c LoadFromCompilerInvocation() and 586 /// \c LoadFromCommandLine(), which loads an AST from a compiler invocation. 587 /// 588 /// \param PrecompilePreamble Whether to precompile the preamble of this 589 /// translation unit, to improve the performance of reparsing. 590 /// 591 /// \returns \c true if a catastrophic failure occurred (which means that the 592 /// \c ASTUnit itself is invalid), or \c false otherwise. 593 bool LoadFromCompilerInvocation(bool PrecompilePreamble); 594 595public: 596 597 /// \brief Create an ASTUnit from a source file, via a CompilerInvocation 598 /// object, by invoking the optionally provided ASTFrontendAction. 599 /// 600 /// \param CI - The compiler invocation to use; it must have exactly one input 601 /// source file. The ASTUnit takes ownership of the CompilerInvocation object. 602 /// 603 /// \param Diags - The diagnostics engine to use for reporting errors; its 604 /// lifetime is expected to extend past that of the returned ASTUnit. 605 /// 606 /// \param Action - The ASTFrontendAction to invoke. Its ownership is not 607 /// transfered. 608 static ASTUnit *LoadFromCompilerInvocationAction(CompilerInvocation *CI, 609 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 610 ASTFrontendAction *Action = 0); 611 612 /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, via a 613 /// CompilerInvocation object. 614 /// 615 /// \param CI - The compiler invocation to use; it must have exactly one input 616 /// source file. The ASTUnit takes ownership of the CompilerInvocation object. 617 /// 618 /// \param Diags - The diagnostics engine to use for reporting errors; its 619 /// lifetime is expected to extend past that of the returned ASTUnit. 620 // 621 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we 622 // shouldn't need to specify them at construction time. 623 static ASTUnit *LoadFromCompilerInvocation(CompilerInvocation *CI, 624 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 625 bool OnlyLocalDecls = false, 626 bool CaptureDiagnostics = false, 627 bool PrecompilePreamble = false, 628 bool CompleteTranslationUnit = true, 629 bool CacheCodeCompletionResults = false, 630 bool NestedMacroExpansions = true); 631 632 /// LoadFromCommandLine - Create an ASTUnit from a vector of command line 633 /// arguments, which must specify exactly one source file. 634 /// 635 /// \param ArgBegin - The beginning of the argument vector. 636 /// 637 /// \param ArgEnd - The end of the argument vector. 638 /// 639 /// \param Diags - The diagnostics engine to use for reporting errors; its 640 /// lifetime is expected to extend past that of the returned ASTUnit. 641 /// 642 /// \param ResourceFilesPath - The path to the compiler resource files. 643 // 644 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we 645 // shouldn't need to specify them at construction time. 646 static ASTUnit *LoadFromCommandLine(const char **ArgBegin, 647 const char **ArgEnd, 648 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 649 StringRef ResourceFilesPath, 650 bool OnlyLocalDecls = false, 651 bool CaptureDiagnostics = false, 652 RemappedFile *RemappedFiles = 0, 653 unsigned NumRemappedFiles = 0, 654 bool RemappedFilesKeepOriginalName = true, 655 bool PrecompilePreamble = false, 656 bool CompleteTranslationUnit = true, 657 bool CacheCodeCompletionResults = false, 658 bool CXXPrecompilePreamble = false, 659 bool CXXChainedPCH = false, 660 bool NestedMacroExpansions = true); 661 662 /// \brief Reparse the source files using the same command-line options that 663 /// were originally used to produce this translation unit. 664 /// 665 /// \returns True if a failure occurred that causes the ASTUnit not to 666 /// contain any translation-unit information, false otherwise. 667 bool Reparse(RemappedFile *RemappedFiles = 0, 668 unsigned NumRemappedFiles = 0); 669 670 /// \brief Perform code completion at the given file, line, and 671 /// column within this translation unit. 672 /// 673 /// \param File The file in which code completion will occur. 674 /// 675 /// \param Line The line at which code completion will occur. 676 /// 677 /// \param Column The column at which code completion will occur. 678 /// 679 /// \param IncludeMacros Whether to include macros in the code-completion 680 /// results. 681 /// 682 /// \param IncludeCodePatterns Whether to include code patterns (such as a 683 /// for loop) in the code-completion results. 684 /// 685 /// FIXME: The Diag, LangOpts, SourceMgr, FileMgr, StoredDiagnostics, and 686 /// OwnedBuffers parameters are all disgusting hacks. They will go away. 687 void CodeComplete(StringRef File, unsigned Line, unsigned Column, 688 RemappedFile *RemappedFiles, unsigned NumRemappedFiles, 689 bool IncludeMacros, bool IncludeCodePatterns, 690 CodeCompleteConsumer &Consumer, 691 Diagnostic &Diag, LangOptions &LangOpts, 692 SourceManager &SourceMgr, FileManager &FileMgr, 693 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics, 694 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers); 695 696 /// \brief Save this translation unit to a file with the given name. 697 /// 698 /// \returns An indication of whether the save was successful or not. 699 CXSaveError Save(StringRef File); 700 701 /// \brief Serialize this translation unit with the given output stream. 702 /// 703 /// \returns True if an error occurred, false otherwise. 704 bool serialize(raw_ostream &OS); 705}; 706 707} // namespace clang 708 709#endif 710