From 56d91b49b13fe55c918afbda19f6165b5fbff87a Mon Sep 17 00:00:00 2001 From: Dimitry Andric Date: Wed, 15 Aug 2012 20:02:54 +0000 Subject: Vendor import of clang trunk r161861: http://llvm.org/svn/llvm-project/cfe/trunk@161861 --- .gitignore | 6 + CMakeLists.txt | 29 +- bindings/python/clang/cindex.py | 1759 +++++--- bindings/python/clang/enumerations.py | 34 + .../tests/cindex/INPUTS/compile_commands.json | 17 + bindings/python/tests/cindex/test_cdb.py | 89 + bindings/python/tests/cindex/test_cursor.py | 151 + bindings/python/tests/cindex/test_location.py | 9 + bindings/python/tests/cindex/test_token_kind.py | 43 + bindings/python/tests/cindex/test_tokens.py | 52 + .../python/tests/cindex/test_translation_unit.py | 187 +- bindings/python/tests/cindex/test_type.py | 26 +- bindings/python/tests/cindex/util.py | 42 +- bindings/xml/comment-xml-schema.rng | 434 ++ docs/AddressSanitizer.html | 57 +- docs/AutomaticReferenceCounting.html | 4 +- docs/ClangPlugins.html | 170 + docs/ClangTools.html | 118 + docs/HowToSetupToolingForLLVM.html | 186 + docs/InternalsManual.html | 32 +- docs/IntroductionToTheClangAST.html | 139 + docs/JSONCompilationDatabase.html | 89 + docs/LanguageExtensions.html | 120 +- docs/LibTooling.html | 229 + docs/ObjectiveCLiterals.html | 199 +- docs/RAVFrontendAction.html | 224 + docs/ReleaseNotes.html | 273 +- docs/ThreadSanitizer.html | 125 + docs/Tooling.html | 120 + docs/UsersManual.html | 202 +- docs/tools/clang.pod | 8 + examples/CMakeLists.txt | 2 +- examples/PrintFunctionNames/CMakeLists.txt | 19 +- examples/analyzer-plugin/CMakeLists.txt | 17 +- examples/clang-interpreter/CMakeLists.txt | 59 +- include/clang-c/CXCompilationDatabase.h | 146 + include/clang-c/CXString.h | 61 + include/clang-c/Index.h | 932 +++- include/clang-c/Platform.h | 45 + include/clang/AST/ASTContext.h | 152 +- include/clang/AST/ASTImporter.h | 3 +- include/clang/AST/ASTVector.h | 4 +- include/clang/AST/Attr.h | 46 +- include/clang/AST/BaseSubobject.h | 6 +- include/clang/AST/CMakeLists.txt | 5 + include/clang/AST/CXXInheritance.h | 3 +- include/clang/AST/Comment.h | 1059 +++++ include/clang/AST/CommentBriefParser.h | 56 + include/clang/AST/CommentCommandTraits.h | 156 + include/clang/AST/CommentDiagnostic.h | 29 + include/clang/AST/CommentLexer.h | 353 ++ include/clang/AST/CommentParser.h | 124 + include/clang/AST/CommentSema.h | 230 + include/clang/AST/CommentVisitor.h | 66 + include/clang/AST/Decl.h | 114 +- include/clang/AST/DeclBase.h | 64 +- include/clang/AST/DeclCXX.h | 193 +- include/clang/AST/DeclContextInternals.h | 4 +- include/clang/AST/DeclFriend.h | 8 +- include/clang/AST/DeclObjC.h | 233 +- include/clang/AST/DeclTemplate.h | 160 +- include/clang/AST/DeclarationName.h | 39 +- include/clang/AST/EvaluatedExprVisitor.h | 2 +- include/clang/AST/Expr.h | 94 +- include/clang/AST/ExprCXX.h | 179 +- include/clang/AST/ExprObjC.h | 84 +- include/clang/AST/ExternalASTSource.h | 3 + include/clang/AST/Makefile | 8 +- include/clang/AST/Mangle.h | 4 +- include/clang/AST/NSAPI.h | 74 +- include/clang/AST/NestedNameSpecifier.h | 15 +- include/clang/AST/OperationKinds.h | 2 +- include/clang/AST/RawCommentList.h | 220 + include/clang/AST/RecordLayout.h | 88 +- include/clang/AST/RecursiveASTVisitor.h | 180 +- include/clang/AST/Redeclarable.h | 29 +- include/clang/AST/Stmt.h | 122 +- include/clang/AST/StmtObjC.h | 56 +- include/clang/AST/TemplateBase.h | 101 +- include/clang/AST/Type.h | 137 +- include/clang/AST/TypeLoc.h | 13 +- include/clang/ASTMatchers/ASTMatchFinder.h | 141 + include/clang/ASTMatchers/ASTMatchers.h | 1799 ++++++++ include/clang/ASTMatchers/ASTMatchersInternal.h | 901 ++++ include/clang/ASTMatchers/ASTMatchersMacros.h | 224 + include/clang/Analysis/Analyses/FormatString.h | 65 +- include/clang/Analysis/Analyses/ThreadSafety.h | 9 +- .../clang/Analysis/Analyses/UninitializedValues.h | 60 +- include/clang/Analysis/AnalysisContext.h | 50 +- include/clang/Analysis/CFG.h | 12 +- include/clang/Analysis/CallGraph.h | 10 +- include/clang/Analysis/ProgramPoint.h | 169 +- .../Analysis/Visitors/CFGRecStmtDeclVisitor.h | 2 + include/clang/Basic/ABI.h | 43 +- include/clang/Basic/AddressSpaces.h | 18 +- include/clang/Basic/AllDiagnostics.h | 9 +- include/clang/Basic/Attr.td | 397 +- include/clang/Basic/AttrKinds.h | 9 +- include/clang/Basic/Builtins.def | 80 +- include/clang/Basic/Builtins.h | 35 +- include/clang/Basic/BuiltinsHexagon.def | 1531 ++++--- include/clang/Basic/BuiltinsMips.def | 125 + include/clang/Basic/BuiltinsNVPTX.def | 62 + include/clang/Basic/BuiltinsPTX.def | 62 - include/clang/Basic/BuiltinsX86.def | 125 +- include/clang/Basic/CMakeLists.txt | 1 + include/clang/Basic/CommentNodes.td | 27 + include/clang/Basic/ConvertUTF.h | 35 + include/clang/Basic/Diagnostic.h | 490 ++- include/clang/Basic/Diagnostic.td | 1 + include/clang/Basic/DiagnosticCommentKinds.td | 125 + include/clang/Basic/DiagnosticCommonKinds.td | 6 + include/clang/Basic/DiagnosticDriverKinds.td | 21 +- include/clang/Basic/DiagnosticFrontendKinds.td | 16 +- include/clang/Basic/DiagnosticGroups.td | 44 +- include/clang/Basic/DiagnosticIDs.h | 96 +- include/clang/Basic/DiagnosticLexKinds.td | 30 +- include/clang/Basic/DiagnosticParseKinds.td | 65 +- include/clang/Basic/DiagnosticSemaKinds.td | 1131 +++-- .../clang/Basic/DiagnosticSerializationKinds.td | 4 +- include/clang/Basic/ExceptionSpecificationType.h | 15 +- include/clang/Basic/ExpressionTraits.h | 7 +- include/clang/Basic/FileManager.h | 93 +- include/clang/Basic/FileSystemOptions.h | 7 +- include/clang/Basic/FileSystemStatCache.h | 18 +- include/clang/Basic/IdentifierTable.h | 103 +- include/clang/Basic/LLVM.h | 7 +- include/clang/Basic/Lambda.h | 15 +- include/clang/Basic/LangOptions.def | 10 +- include/clang/Basic/LangOptions.h | 29 +- include/clang/Basic/Linkage.h | 23 +- include/clang/Basic/MacroBuilder.h | 13 +- include/clang/Basic/Makefile | 1 + include/clang/Basic/Module.h | 13 +- include/clang/Basic/ObjCRuntime.h | 264 ++ include/clang/Basic/OnDiskHashTable.h | 8 +- include/clang/Basic/OpenCL.h | 9 +- include/clang/Basic/OperatorKinds.h | 13 +- include/clang/Basic/PartialDiagnostic.h | 61 +- include/clang/Basic/PrettyStackTrace.h | 15 +- include/clang/Basic/SourceLocation.h | 102 +- include/clang/Basic/SourceManager.h | 659 ++- include/clang/Basic/SourceManagerInternals.h | 55 +- include/clang/Basic/Specifiers.h | 52 +- include/clang/Basic/StmtNodes.td | 5 +- include/clang/Basic/TargetBuiltins.h | 36 +- include/clang/Basic/TargetInfo.h | 273 +- include/clang/Basic/TargetOptions.h | 7 +- include/clang/Basic/TemplateKinds.h | 7 +- include/clang/Basic/TokenKinds.def | 64 +- include/clang/Basic/TokenKinds.h | 21 +- include/clang/Basic/TypeTraits.h | 15 +- include/clang/Basic/Version.h | 38 +- include/clang/Basic/VersionTuple.h | 45 +- include/clang/Basic/Visibility.h | 19 +- include/clang/Basic/arm_neon.td | 1 + include/clang/Driver/Arg.h | 42 +- include/clang/Driver/ArgList.h | 8 + include/clang/Driver/CC1Options.h | 32 - include/clang/Driver/CC1Options.td | 366 +- include/clang/Driver/CMakeLists.txt | 4 - include/clang/Driver/Compilation.h | 2 + include/clang/Driver/Driver.h | 8 +- include/clang/Driver/Makefile | 8 +- include/clang/Driver/ObjCRuntime.h | 49 - include/clang/Driver/OptParser.td | 5 +- include/clang/Driver/OptTable.h | 50 +- include/clang/Driver/Option.h | 6 + include/clang/Driver/Options.td | 566 ++- include/clang/Driver/ToolChain.h | 21 +- include/clang/Driver/Types.def | 12 +- include/clang/Driver/Types.h | 6 +- include/clang/Frontend/ASTConsumers.h | 8 +- include/clang/Frontend/ASTUnit.h | 42 +- include/clang/Frontend/Analyses.def | 4 +- include/clang/Frontend/AnalyzerOptions.h | 2 - include/clang/Frontend/CodeGenOptions.h | 180 +- include/clang/Frontend/CompilerInstance.h | 3 +- include/clang/Frontend/CompilerInvocation.h | 42 +- include/clang/Frontend/DiagnosticOptions.h | 3 + include/clang/Frontend/DiagnosticRenderer.h | 34 +- include/clang/Frontend/FrontendAction.h | 2 +- include/clang/Frontend/FrontendActions.h | 6 + include/clang/Frontend/FrontendOptions.h | 20 +- include/clang/Frontend/HeaderSearchOptions.h | 28 +- include/clang/Frontend/LangStandards.def | 6 + include/clang/Frontend/PreprocessorOutputOptions.h | 4 +- include/clang/Frontend/TextDiagnostic.h | 26 +- include/clang/Frontend/TextDiagnosticPrinter.h | 2 - include/clang/Frontend/VerifyDiagnosticConsumer.h | 138 +- include/clang/Lex/CodeCompletionHandler.h | 6 +- include/clang/Lex/DirectoryLookup.h | 10 +- include/clang/Lex/HeaderMap.h | 2 +- include/clang/Lex/HeaderSearch.h | 138 +- include/clang/Lex/Lexer.h | 35 +- include/clang/Lex/LiteralSupport.h | 1 + include/clang/Lex/MacroInfo.h | 15 +- include/clang/Lex/ModuleMap.h | 6 +- include/clang/Lex/MultipleIncludeOpt.h | 43 +- include/clang/Lex/PPCallbacks.h | 123 +- include/clang/Lex/Pragma.h | 10 +- include/clang/Lex/PreprocessingRecord.h | 18 +- include/clang/Lex/Preprocessor.h | 134 +- include/clang/Lex/PreprocessorLexer.h | 55 +- include/clang/Lex/Token.h | 53 +- include/clang/Parse/Parser.h | 281 +- include/clang/Rewrite/FrontendActions.h | 5 + include/clang/Rewrite/Rewriter.h | 7 + include/clang/Rewrite/Rewriters.h | 5 + include/clang/Rewrite/TokenRewriter.h | 2 +- include/clang/Sema/AttributeList.h | 81 +- include/clang/Sema/CodeCompleteConsumer.h | 142 +- include/clang/Sema/CodeCompleteOptions.h | 37 + include/clang/Sema/DeclSpec.h | 188 +- include/clang/Sema/DelayedDiagnostic.h | 66 +- include/clang/Sema/Designator.h | 8 - include/clang/Sema/Initialization.h | 8 +- include/clang/Sema/Overload.h | 23 +- include/clang/Sema/ParsedTemplate.h | 10 +- include/clang/Sema/Scope.h | 4 +- include/clang/Sema/ScopeInfo.h | 19 +- include/clang/Sema/Sema.h | 1016 +++-- include/clang/Sema/Template.h | 11 +- include/clang/Sema/TemplateDeduction.h | 39 +- include/clang/Sema/Weak.h | 2 +- include/clang/Serialization/ASTBitCodes.h | 63 +- include/clang/Serialization/ASTReader.h | 36 +- include/clang/Serialization/ASTWriter.h | 13 +- .../StaticAnalyzer/Core/BugReporter/BugReporter.h | 20 +- .../Core/BugReporter/BugReporterVisitor.h | 6 +- .../Core/BugReporter/PathDiagnostic.h | 36 +- include/clang/StaticAnalyzer/Core/Checker.h | 65 +- include/clang/StaticAnalyzer/Core/CheckerManager.h | 71 +- .../StaticAnalyzer/Core/PathSensitive/APSIntType.h | 106 + .../Core/PathSensitive/AnalysisManager.h | 10 +- .../Core/PathSensitive/BasicValueFactory.h | 39 +- .../StaticAnalyzer/Core/PathSensitive/CallEvent.h | 962 +++++ .../Core/PathSensitive/CheckerContext.h | 9 + .../StaticAnalyzer/Core/PathSensitive/CoreEngine.h | 19 +- .../Core/PathSensitive/ExplodedGraph.h | 6 +- .../StaticAnalyzer/Core/PathSensitive/ExprEngine.h | 94 +- .../Core/PathSensitive/FunctionSummary.h | 7 +- .../StaticAnalyzer/Core/PathSensitive/MemRegion.h | 86 +- .../Core/PathSensitive/ObjCMessage.h | 293 -- .../Core/PathSensitive/ProgramState.h | 102 +- .../Core/PathSensitive/SValBuilder.h | 25 +- .../StaticAnalyzer/Core/PathSensitive/SVals.h | 42 +- .../StaticAnalyzer/Core/PathSensitive/Store.h | 70 +- .../StaticAnalyzer/Core/PathSensitive/SubEngine.h | 2 +- .../Core/PathSensitive/SymbolManager.h | 14 +- include/clang/Tooling/ArgumentsAdjusters.h | 59 + include/clang/Tooling/CommandLineClangTool.h | 80 + include/clang/Tooling/CompilationDatabase.h | 28 +- include/clang/Tooling/Refactoring.h | 151 + include/clang/Tooling/RefactoringCallbacks.h | 90 + include/clang/Tooling/Tooling.h | 85 +- lib/ARCMigrate/ARCMT.cpp | 67 +- lib/ARCMigrate/CMakeLists.txt | 18 +- lib/ARCMigrate/FileRemapper.cpp | 4 +- lib/ARCMigrate/Internals.h | 4 + lib/ARCMigrate/ObjCMT.cpp | 2 + lib/ARCMigrate/TransAPIUses.cpp | 1 + lib/ARCMigrate/TransARCAssign.cpp | 1 + lib/ARCMigrate/TransAutoreleasePool.cpp | 3 +- lib/ARCMigrate/TransBlockObjCVariable.cpp | 19 +- lib/ARCMigrate/TransEmptyStatementsAndDealloc.cpp | 7 +- lib/ARCMigrate/TransGCAttrs.cpp | 9 +- lib/ARCMigrate/TransGCCalls.cpp | 9 +- lib/ARCMigrate/TransProperties.cpp | 11 +- lib/ARCMigrate/TransRetainReleaseDealloc.cpp | 99 +- lib/ARCMigrate/TransUnbridgedCasts.cpp | 85 +- lib/ARCMigrate/TransUnusedInitDelegate.cpp | 3 +- lib/ARCMigrate/TransZeroOutPropsInDealloc.cpp | 1 + lib/ARCMigrate/TransformActions.cpp | 1 + lib/ARCMigrate/Transforms.cpp | 59 +- lib/ARCMigrate/Transforms.h | 14 +- lib/AST/APValue.cpp | 6 +- lib/AST/ASTContext.cpp | 569 ++- lib/AST/ASTDiagnostic.cpp | 934 ++++ lib/AST/ASTImporter.cpp | 117 +- lib/AST/CMakeLists.txt | 30 +- lib/AST/CXXABI.h | 2 +- lib/AST/CXXInheritance.cpp | 22 +- lib/AST/Comment.cpp | 264 ++ lib/AST/CommentBriefParser.cpp | 122 + lib/AST/CommentCommandTraits.cpp | 134 + lib/AST/CommentDumper.cpp | 231 + lib/AST/CommentLexer.cpp | 815 ++++ lib/AST/CommentParser.cpp | 722 ++++ lib/AST/CommentSema.cpp | 739 ++++ lib/AST/Decl.cpp | 346 +- lib/AST/DeclBase.cpp | 57 +- lib/AST/DeclCXX.cpp | 179 +- lib/AST/DeclFriend.cpp | 6 + lib/AST/DeclObjC.cpp | 56 +- lib/AST/DeclPrinter.cpp | 54 +- lib/AST/DeclTemplate.cpp | 18 +- lib/AST/DeclarationName.cpp | 55 +- lib/AST/DumpXML.cpp | 15 +- lib/AST/Expr.cpp | 522 ++- lib/AST/ExprCXX.cpp | 67 +- lib/AST/ExprClassification.cpp | 25 +- lib/AST/ExprConstant.cpp | 346 +- lib/AST/ItaniumCXXABI.cpp | 2 +- lib/AST/ItaniumMangle.cpp | 38 +- lib/AST/LambdaMangleContext.cpp | 2 + lib/AST/Mangle.cpp | 29 +- lib/AST/MicrosoftCXXABI.cpp | 4 +- lib/AST/MicrosoftMangle.cpp | 822 +++- lib/AST/NSAPI.cpp | 107 +- lib/AST/ParentMap.cpp | 13 +- lib/AST/RawCommentList.cpp | 271 ++ lib/AST/RecordLayout.cpp | 12 +- lib/AST/RecordLayoutBuilder.cpp | 307 +- lib/AST/Stmt.cpp | 132 +- lib/AST/StmtDumper.cpp | 22 +- lib/AST/StmtPrinter.cpp | 116 +- lib/AST/StmtProfile.cpp | 9 +- lib/AST/TemplateBase.cpp | 33 +- lib/AST/Type.cpp | 51 +- lib/AST/TypeLoc.cpp | 1 + lib/AST/TypePrinter.cpp | 1453 ++++--- lib/AST/VTTBuilder.cpp | 1 + lib/AST/VTableBuilder.cpp | 17 +- lib/ASTMatchers/ASTMatchFinder.cpp | 547 +++ lib/ASTMatchers/ASTMatchersInternal.cpp | 102 + lib/ASTMatchers/CMakeLists.txt | 17 + lib/ASTMatchers/Makefile | 13 + lib/Analysis/AnalysisDeclContext.cpp | 63 +- lib/Analysis/CFG.cpp | 500 ++- lib/Analysis/CMakeLists.txt | 18 +- lib/Analysis/CallGraph.cpp | 7 +- lib/Analysis/CocoaConventions.cpp | 2 + lib/Analysis/FormatString.cpp | 138 +- lib/Analysis/LiveVariables.cpp | 19 + lib/Analysis/PrintfFormatString.cpp | 122 +- lib/Analysis/ProgramPoint.cpp | 6 +- lib/Analysis/PseudoConstantAnalysis.cpp | 1 + lib/Analysis/ScanfFormatString.cpp | 193 +- lib/Analysis/ThreadSafety.cpp | 1641 ++++--- lib/Analysis/UninitializedValues.cpp | 793 ++-- lib/Basic/CMakeLists.txt | 33 +- lib/Basic/ConvertUTF.c | 3 +- lib/Basic/ConvertUTFWrapper.cpp | 70 + lib/Basic/Diagnostic.cpp | 129 +- lib/Basic/DiagnosticIDs.cpp | 32 +- lib/Basic/FileManager.cpp | 61 +- lib/Basic/IdentifierTable.cpp | 29 +- lib/Basic/ObjCRuntime.cpp | 86 + lib/Basic/SourceManager.cpp | 96 +- lib/Basic/TargetInfo.cpp | 1 + lib/Basic/Targets.cpp | 588 ++- lib/Basic/Version.cpp | 5 +- lib/Basic/VersionTuple.cpp | 52 + lib/CMakeLists.txt | 1 + lib/CodeGen/ABIInfo.h | 32 +- lib/CodeGen/BackendUtil.cpp | 32 +- lib/CodeGen/CGBlocks.cpp | 41 +- lib/CodeGen/CGBuilder.h | 2 +- lib/CodeGen/CGBuiltin.cpp | 2040 +-------- lib/CodeGen/CGCXX.cpp | 4 +- lib/CodeGen/CGCXXABI.cpp | 71 +- lib/CodeGen/CGCXXABI.h | 51 +- lib/CodeGen/CGCall.cpp | 198 +- lib/CodeGen/CGClass.cpp | 202 +- lib/CodeGen/CGCleanup.cpp | 8 +- lib/CodeGen/CGCleanup.h | 2 +- lib/CodeGen/CGDebugInfo.cpp | 228 +- lib/CodeGen/CGDebugInfo.h | 5 +- lib/CodeGen/CGDecl.cpp | 48 +- lib/CodeGen/CGDeclCXX.cpp | 80 +- lib/CodeGen/CGException.cpp | 80 +- lib/CodeGen/CGExpr.cpp | 239 +- lib/CodeGen/CGExprAgg.cpp | 253 +- lib/CodeGen/CGExprCXX.cpp | 136 +- lib/CodeGen/CGExprConstant.cpp | 18 +- lib/CodeGen/CGExprScalar.cpp | 30 +- lib/CodeGen/CGObjC.cpp | 192 +- lib/CodeGen/CGObjCGNU.cpp | 97 +- lib/CodeGen/CGObjCMac.cpp | 75 +- lib/CodeGen/CGObjCRuntime.cpp | 17 +- lib/CodeGen/CGObjCRuntime.h | 20 +- lib/CodeGen/CGRTTI.cpp | 3 +- lib/CodeGen/CGRecordLayout.h | 7 +- lib/CodeGen/CGRecordLayoutBuilder.cpp | 16 +- lib/CodeGen/CGStmt.cpp | 94 +- lib/CodeGen/CGVTables.cpp | 23 +- lib/CodeGen/CGValue.h | 9 +- lib/CodeGen/CMakeLists.txt | 20 +- lib/CodeGen/CodeGenFunction.cpp | 136 +- lib/CodeGen/CodeGenFunction.h | 47 +- lib/CodeGen/CodeGenModule.cpp | 146 +- lib/CodeGen/CodeGenModule.h | 15 +- lib/CodeGen/CodeGenTBAA.cpp | 8 +- lib/CodeGen/CodeGenTBAA.h | 6 +- lib/CodeGen/CodeGenTypes.cpp | 4 +- lib/CodeGen/CodeGenTypes.h | 36 +- lib/CodeGen/ItaniumCXXABI.cpp | 257 +- lib/CodeGen/MicrosoftCXXABI.cpp | 98 +- lib/CodeGen/TargetInfo.cpp | 383 +- lib/Driver/ArgList.cpp | 62 + lib/Driver/CC1Options.cpp | 38 - lib/Driver/CMakeLists.txt | 22 +- lib/Driver/Compilation.cpp | 2 +- lib/Driver/Driver.cpp | 189 +- lib/Driver/OptTable.cpp | 2 + lib/Driver/ToolChain.cpp | 27 +- lib/Driver/ToolChains.cpp | 338 +- lib/Driver/ToolChains.h | 109 +- lib/Driver/Tools.cpp | 989 +++-- lib/Driver/Tools.h | 38 + lib/Driver/Types.cpp | 4 +- lib/Edit/CMakeLists.txt | 17 +- lib/Edit/Commit.cpp | 1 + lib/Edit/EditedSource.cpp | 5 +- lib/Edit/RewriteObjCFoundationAPI.cpp | 506 ++- lib/Frontend/ASTConsumers.cpp | 99 +- lib/Frontend/ASTUnit.cpp | 224 +- lib/Frontend/CMakeLists.txt | 45 +- lib/Frontend/CompilerInstance.cpp | 23 +- lib/Frontend/CompilerInvocation.cpp | 326 +- lib/Frontend/CreateInvocationFromCommandLine.cpp | 8 +- lib/Frontend/DiagnosticRenderer.cpp | 127 +- lib/Frontend/FrontendAction.cpp | 62 +- lib/Frontend/FrontendActions.cpp | 11 +- lib/Frontend/InitHeaderSearch.cpp | 15 + lib/Frontend/InitPreprocessor.cpp | 72 +- lib/Frontend/LayoutOverrideSource.cpp | 1 + lib/Frontend/PrintPreprocessedOutput.cpp | 66 +- lib/Frontend/SerializedDiagnosticPrinter.cpp | 40 +- lib/Frontend/TextDiagnostic.cpp | 217 +- lib/Frontend/TextDiagnosticPrinter.cpp | 30 +- lib/Frontend/VerifyDiagnosticConsumer.cpp | 471 +- lib/Frontend/Warnings.cpp | 14 +- lib/FrontendTool/CMakeLists.txt | 21 +- lib/FrontendTool/ExecuteCompilerInvocation.cpp | 12 +- lib/Headers/CMakeLists.txt | 3 + lib/Headers/ammintrin.h | 68 + lib/Headers/avx2intrin.h | 240 ++ lib/Headers/bmiintrin.h | 6 +- lib/Headers/emmintrin.h | 5 +- lib/Headers/float.h | 2 +- lib/Headers/fmaintrin.h | 229 + lib/Headers/immintrin.h | 26 + lib/Headers/stddef.h | 16 +- lib/Headers/wmmintrin.h | 18 +- lib/Headers/x86intrin.h | 10 +- lib/Headers/xopintrin.h | 411 ++ lib/Lex/CMakeLists.txt | 12 +- lib/Lex/HeaderSearch.cpp | 42 +- lib/Lex/Lexer.cpp | 91 +- lib/Lex/LiteralSupport.cpp | 154 +- lib/Lex/PPDirectives.cpp | 183 +- lib/Lex/PPLexerChange.cpp | 2 +- lib/Lex/PPMacroExpansion.cpp | 46 +- lib/Lex/Pragma.cpp | 78 +- lib/Lex/PreprocessingRecord.cpp | 4 +- lib/Lex/Preprocessor.cpp | 127 +- lib/Lex/PreprocessorLexer.cpp | 2 +- lib/Lex/TokenConcatenation.cpp | 1 + lib/Lex/TokenLexer.cpp | 12 +- lib/Makefile | 2 +- lib/Parse/CMakeLists.txt | 21 +- lib/Parse/ParseAST.cpp | 45 +- lib/Parse/ParseCXXInlineMethods.cpp | 8 +- lib/Parse/ParseDecl.cpp | 838 ++-- lib/Parse/ParseDeclCXX.cpp | 327 +- lib/Parse/ParseExpr.cpp | 158 +- lib/Parse/ParseExprCXX.cpp | 77 +- lib/Parse/ParseObjc.cpp | 242 +- lib/Parse/ParsePragma.h | 21 +- lib/Parse/ParseStmt.cpp | 127 +- lib/Parse/ParseTemplate.cpp | 135 +- lib/Parse/ParseTentative.cpp | 93 +- lib/Parse/Parser.cpp | 182 +- lib/Parse/RAIIObjectsForParser.h | 298 +- lib/Rewrite/CMakeLists.txt | 17 +- lib/Rewrite/FrontendActions.cpp | 11 +- lib/Rewrite/HTMLRewrite.cpp | 11 +- lib/Rewrite/InclusionRewriter.cpp | 361 ++ lib/Rewrite/RewriteModernObjC.cpp | 759 +++- lib/Rewrite/RewriteObjC.cpp | 105 +- lib/Rewrite/Rewriter.cpp | 76 +- lib/Sema/AnalysisBasedWarnings.cpp | 502 ++- lib/Sema/AttributeList.cpp | 39 +- lib/Sema/CMakeLists.txt | 39 +- lib/Sema/CodeCompleteConsumer.cpp | 27 +- lib/Sema/DeclSpec.cpp | 39 +- lib/Sema/Sema.cpp | 177 +- lib/Sema/SemaAccess.cpp | 83 +- lib/Sema/SemaCXXScopeSpec.cpp | 12 +- lib/Sema/SemaCast.cpp | 30 +- lib/Sema/SemaChecking.cpp | 931 ++-- lib/Sema/SemaCodeComplete.cpp | 210 +- lib/Sema/SemaDecl.cpp | 911 ++-- lib/Sema/SemaDeclAttr.cpp | 1637 ++++--- lib/Sema/SemaDeclCXX.cpp | 1738 ++++---- lib/Sema/SemaDeclObjC.cpp | 311 +- lib/Sema/SemaExceptionSpec.cpp | 41 +- lib/Sema/SemaExpr.cpp | 1155 +++-- lib/Sema/SemaExprCXX.cpp | 410 +- lib/Sema/SemaExprMember.cpp | 95 +- lib/Sema/SemaExprObjC.cpp | 925 ++-- lib/Sema/SemaFixItUtils.cpp | 71 +- lib/Sema/SemaInit.cpp | 372 +- lib/Sema/SemaLambda.cpp | 316 +- lib/Sema/SemaLookup.cpp | 198 +- lib/Sema/SemaObjCProperty.cpp | 375 +- lib/Sema/SemaOverload.cpp | 456 +- lib/Sema/SemaPseudoObject.cpp | 60 +- lib/Sema/SemaStmt.cpp | 735 +++- lib/Sema/SemaStmtAttr.cpp | 36 +- lib/Sema/SemaTemplate.cpp | 238 +- lib/Sema/SemaTemplateDeduction.cpp | 124 +- lib/Sema/SemaTemplateInstantiate.cpp | 266 +- lib/Sema/SemaTemplateInstantiateDecl.cpp | 162 +- lib/Sema/SemaTemplateVariadic.cpp | 113 +- lib/Sema/SemaType.cpp | 568 ++- lib/Sema/TargetAttributesSema.cpp | 63 +- lib/Sema/TreeTransform.h | 1264 +++--- lib/Serialization/ASTCommon.h | 2 + lib/Serialization/ASTReader.cpp | 150 +- lib/Serialization/ASTReaderDecl.cpp | 51 +- lib/Serialization/ASTReaderStmt.cpp | 32 +- lib/Serialization/ASTWriter.cpp | 82 +- lib/Serialization/ASTWriterDecl.cpp | 26 +- lib/Serialization/ASTWriterStmt.cpp | 19 +- lib/Serialization/CMakeLists.txt | 14 +- lib/StaticAnalyzer/Checkers/AttrNonNullChecker.cpp | 46 +- .../Checkers/BasicObjCFoundationChecks.cpp | 228 +- lib/StaticAnalyzer/Checkers/CMakeLists.txt | 14 +- lib/StaticAnalyzer/Checkers/CStringChecker.cpp | 28 +- .../Checkers/CallAndMessageChecker.cpp | 304 +- lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp | 8 +- .../Checkers/CheckSecuritySyntaxOnly.cpp | 1 + .../Checkers/CheckerDocumentation.cpp | 63 +- lib/StaticAnalyzer/Checkers/Checkers.td | 40 +- lib/StaticAnalyzer/Checkers/DereferenceChecker.cpp | 265 +- lib/StaticAnalyzer/Checkers/DivZeroChecker.cpp | 8 +- .../Checkers/DynamicTypePropagation.cpp | 179 + .../Checkers/ExprInspectionChecker.cpp | 122 + .../Checkers/GenericTaintChecker.cpp | 15 +- .../Checkers/IdempotentOperationChecker.cpp | 5 +- lib/StaticAnalyzer/Checkers/IteratorsChecker.cpp | 603 --- .../Checkers/MacOSKeychainAPIChecker.cpp | 20 +- lib/StaticAnalyzer/Checkers/MallocChecker.cpp | 626 +-- .../Checkers/MallocSizeofChecker.cpp | 37 +- .../Checkers/NSAutoreleasePoolChecker.cpp | 23 +- .../Checkers/NoReturnFunctionChecker.cpp | 6 +- lib/StaticAnalyzer/Checkers/ObjCAtSyncChecker.cpp | 6 +- .../Checkers/ObjCContainersChecker.cpp | 1 - .../Checkers/ObjCSelfInitChecker.cpp | 102 +- .../Checkers/ObjCUnusedIVarsChecker.cpp | 9 + lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp | 739 ++-- lib/StaticAnalyzer/Checkers/ReturnUndefChecker.cpp | 4 +- lib/StaticAnalyzer/Checkers/StreamChecker.cpp | 2 +- lib/StaticAnalyzer/Checkers/TraversalChecker.cpp | 84 + lib/StaticAnalyzer/Checkers/UndefBranchChecker.cpp | 3 +- .../Checkers/UndefCapturedBlockVarChecker.cpp | 1 + lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp | 8 +- .../Checkers/UndefinedArraySubscriptChecker.cpp | 4 +- .../Checkers/UndefinedAssignmentChecker.cpp | 3 +- lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp | 13 +- lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp | 3 +- lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp | 2 +- lib/StaticAnalyzer/Core/APSIntType.cpp | 38 + lib/StaticAnalyzer/Core/AnalysisManager.cpp | 7 +- lib/StaticAnalyzer/Core/BasicConstraintManager.cpp | 241 +- lib/StaticAnalyzer/Core/BasicValueFactory.cpp | 1 + lib/StaticAnalyzer/Core/BugReporter.cpp | 179 +- lib/StaticAnalyzer/Core/BugReporterVisitors.cpp | 86 +- lib/StaticAnalyzer/Core/CMakeLists.txt | 23 +- lib/StaticAnalyzer/Core/CallEvent.cpp | 856 ++++ lib/StaticAnalyzer/Core/CheckerManager.cpp | 133 +- lib/StaticAnalyzer/Core/CoreEngine.cpp | 29 +- lib/StaticAnalyzer/Core/Environment.cpp | 17 +- lib/StaticAnalyzer/Core/ExplodedGraph.cpp | 18 +- lib/StaticAnalyzer/Core/ExprEngine.cpp | 538 +-- lib/StaticAnalyzer/Core/ExprEngineC.cpp | 270 +- lib/StaticAnalyzer/Core/ExprEngineCXX.cpp | 366 +- .../Core/ExprEngineCallAndReturn.cpp | 822 ++-- lib/StaticAnalyzer/Core/ExprEngineObjC.cpp | 211 +- lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp | 84 +- lib/StaticAnalyzer/Core/MemRegion.cpp | 274 +- lib/StaticAnalyzer/Core/ObjCMessage.cpp | 90 - lib/StaticAnalyzer/Core/PathDiagnostic.cpp | 204 +- lib/StaticAnalyzer/Core/PlistDiagnostics.cpp | 31 +- lib/StaticAnalyzer/Core/ProgramState.cpp | 99 +- lib/StaticAnalyzer/Core/RangeConstraintManager.cpp | 275 +- lib/StaticAnalyzer/Core/RegionStore.cpp | 949 +++-- lib/StaticAnalyzer/Core/SValBuilder.cpp | 76 +- lib/StaticAnalyzer/Core/SVals.cpp | 20 +- .../Core/SimpleConstraintManager.cpp | 103 +- lib/StaticAnalyzer/Core/SimpleConstraintManager.h | 6 +- lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp | 338 +- lib/StaticAnalyzer/Core/Store.cpp | 34 +- lib/StaticAnalyzer/Core/SymbolManager.cpp | 14 + lib/StaticAnalyzer/Core/TextPathDiagnostics.cpp | 5 +- lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp | 71 +- lib/StaticAnalyzer/Frontend/CMakeLists.txt | 15 +- .../Frontend/CheckerRegistration.cpp | 2 +- lib/Tooling/ArgumentsAdjusters.cpp | 34 + lib/Tooling/CMakeLists.txt | 22 +- lib/Tooling/CommandLineClangTool.cpp | 80 + lib/Tooling/CompilationDatabase.cpp | 106 +- lib/Tooling/CustomCompilationDatabase.h | 42 + lib/Tooling/Refactoring.cpp | 186 + lib/Tooling/RefactoringCallbacks.cpp | 81 + lib/Tooling/Tooling.cpp | 136 +- runtime/compiler-rt/Makefile | 6 +- test/ARCMT/Common.h | 36 +- test/ARCMT/autoreleases.m | 47 +- test/ARCMT/autoreleases.m.result | 43 +- test/ARCMT/checking.m | 33 +- test/ARCMT/cxx-rewrite.mm.result | 2 +- test/ARCMT/dispatch.m | 11 - test/ARCMT/dispatch.m.result | 11 - test/ARCMT/nonobjc-to-objc-cast-2.m | 31 +- test/ARCMT/nonobjc-to-objc-cast.m | 27 +- test/ARCMT/nonobjc-to-objc-cast.m.result | 57 +- test/ARCMT/objcmt-boxing.m | 102 + test/ARCMT/objcmt-boxing.m.result | 102 + test/ARCMT/objcmt-numeric-literals.m | 1 + test/ARCMT/objcmt-numeric-literals.m.result | 5 +- test/ARCMT/objcmt-subscripting-literals-in-arc.m | 106 + .../objcmt-subscripting-literals-in-arc.m.result | 106 + test/ARCMT/objcmt-subscripting-literals.m | 102 +- test/ARCMT/objcmt-subscripting-literals.m.result | 102 +- test/ARCMT/objcmt-subscripting-unavailable.m | 79 + .../ARCMT/objcmt-subscripting-unavailable.m.result | 79 + test/ARCMT/releases-driver.m | 3 +- test/ARCMT/releases-driver.m.result | 3 - test/ARCMT/releases.m | 3 +- test/ARCMT/releases.m.result | 3 - test/ARCMT/verify.m | 13 + test/ASTMerge/function.c | 6 + test/Analysis/MissingDealloc.m | 6 +- test/Analysis/NoReturn.m | 12 + test/Analysis/PR12905.c | 8 + test/Analysis/additive-folding-range-constraints.c | 191 +- test/Analysis/additive-folding.c | 203 - test/Analysis/additive-folding.cpp | 196 + test/Analysis/array-struct-region.c | 171 +- test/Analysis/auto-obj-dtors-cfg-output.cpp | 295 +- test/Analysis/base-init.cpp | 9 +- test/Analysis/blocks-no-inline.c | 13 + test/Analysis/blocks.m | 4 +- test/Analysis/bstring.c | 89 +- test/Analysis/casts.c | 8 + test/Analysis/comparison-implicit-casts.cpp | 98 + test/Analysis/constant-folding.c | 90 +- test/Analysis/coverage.c | 8 + test/Analysis/cstring-syntax.c | 2 +- test/Analysis/ctor-inlining.mm | 41 + test/Analysis/cxx-crashes.cpp | 23 +- test/Analysis/cxx-for-range-cfg.cpp | 16 + test/Analysis/cxx-method-names.cpp | 21 + test/Analysis/cxx11-crashes.cpp | 66 + test/Analysis/dead-stores.m | 20 + test/Analysis/delegates.m | 25 +- test/Analysis/derived-to-base.cpp | 124 +- test/Analysis/diagnostics/undef-value-callee.h | 4 + test/Analysis/diagnostics/undef-value-caller.c | 238 ++ test/Analysis/domtest.c | 45 +- test/Analysis/dtor.cpp | 164 +- test/Analysis/dynamic-cast.cpp | 25 +- test/Analysis/engine/replay-without-inlining.c | 57 + test/Analysis/global-region-invalidation.c | 13 +- test/Analysis/html-diags.c | 2 +- test/Analysis/initializer.cpp | 74 +- test/Analysis/initializers-cfg-output.cpp | 2 +- test/Analysis/inline-plist.c | 834 +++- test/Analysis/inline-unique-reports.c | 26 +- test/Analysis/inline.c | 22 +- test/Analysis/inline.cpp | 168 + test/Analysis/inlining/DynDispatchBifurcate.m | 181 + test/Analysis/inlining/InlineObjCClassMethod.m | 181 + test/Analysis/inlining/InlineObjCInstanceMethod.h | 46 + test/Analysis/inlining/InlineObjCInstanceMethod.m | 86 + test/Analysis/inlining/ObjCDynTypePopagation.m | 84 + .../ObjCImproperDynamictallyDetectableCast.m | 37 + test/Analysis/inlining/RetainCountExamples.m | 33 + test/Analysis/inlining/path-notes.c | 1291 ++++++ test/Analysis/iterators.cpp | 105 - test/Analysis/ivars.m | 132 + test/Analysis/malloc-annotations.c | 8 +- test/Analysis/malloc-plist.c | 1896 ++++++++- test/Analysis/malloc-sizeof.c | 27 +- test/Analysis/malloc.c | 278 +- test/Analysis/malloc.cpp | 21 + test/Analysis/malloc.m | 2 +- test/Analysis/malloc.mm | 80 +- test/Analysis/method-call-path-notes.cpp | 664 +++ test/Analysis/method-call.cpp | 28 +- test/Analysis/misc-ps-arm.m | 18 + test/Analysis/misc-ps-cxx0x.cpp | 14 + test/Analysis/misc-ps-region-store.cpp | 50 +- test/Analysis/misc-ps-region-store.m | 22 +- test/Analysis/misc-ps.c | 7 + test/Analysis/misc-ps.m | 36 +- test/Analysis/new.cpp | 99 +- test/Analysis/nonnull.m | 23 + test/Analysis/nullptr.cpp | 2 +- test/Analysis/objc-boxing.m | 44 + test/Analysis/objc-for.m | 58 + test/Analysis/objc-subscript.m | 89 + test/Analysis/operator-calls.cpp | 18 +- test/Analysis/out-of-bounds.c | 6 +- test/Analysis/outofbound-notwork.c | 2 +- test/Analysis/outofbound.c | 36 + test/Analysis/plist-output-alternate.m | 49 +- test/Analysis/plist-output.m | 647 ++- test/Analysis/ptr-arith.c | 217 +- test/Analysis/rdar-7168531.m | 2 +- test/Analysis/refcnt_naming.m | 2 +- test/Analysis/reference.cpp | 79 +- test/Analysis/region-store.c | 23 + test/Analysis/retain-release-path-notes-gc.m | 1339 +++++- test/Analysis/retain-release-path-notes.m | 4489 +++++++++++++++++++- test/Analysis/retain-release.m | 130 +- test/Analysis/self-init.m | 31 +- test/Analysis/stack-addr-ps.cpp | 6 + test/Analysis/string-fail.c | 40 +- test/Analysis/string.c | 397 +- test/Analysis/svalbuilder-logic.c | 7 + test/Analysis/system-header-simulator-objc.h | 16 + test/Analysis/system-header-simulator.h | 24 + test/Analysis/taint-generic.c | 29 + test/Analysis/taint-tester.c | 2 +- test/Analysis/temp-obj-dtors-cfg-output.cpp | 205 +- test/Analysis/templates.cpp | 44 + test/Analysis/test-variably-modified-types.c | 13 + test/Analysis/traversal-algorithm.mm | 213 + test/Analysis/uninit-sometimes.cpp | 387 ++ test/Analysis/unused-ivars.m | 21 + test/CMakeLists.txt | 172 +- .../basic.lookup.classref/p1-cxx11.cpp | 69 + .../basic.lookup.classref/p4-cxx11.cpp | 21 + test/CXX/basic/basic.types/p10.cpp | 6 +- test/CXX/class.access/class.friend/p1.cpp | 2 + test/CXX/class.access/class.friend/p9-cxx0x.cpp | 117 + test/CXX/class.derived/class.virtual/p3-0x.cpp | 49 + test/CXX/class/class.mem/p14.cpp | 5 +- test/CXX/class/class.union/p1.cpp | 5 +- test/CXX/class/p6-0x.cpp | 2 +- test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p4.cpp | 48 +- .../dcl.dcl/dcl.spec/dcl.type/dcl.spec.auto/p3.cpp | 37 + .../dcl.dcl/dcl.spec/dcl.type/dcl.spec.auto/p5.cpp | 3 +- .../dcl.spec/dcl.type/dcl.type.simple/p5-cxx0x.cpp | 12 +- test/CXX/dcl.dcl/dcl.spec/dcl.typedef/p2-0x.cpp | 4 +- .../dcl.fct.def/dcl.fct.def.default/p2.cpp | 76 +- .../dcl.decl/dcl.fct.def/dcl.fct.def.delete/p4.cpp | 8 + test/CXX/dcl.decl/dcl.init/dcl.init.aggr/p1-0x.cpp | 2 +- test/CXX/dcl.decl/dcl.init/dcl.init.list/p3-0x.cpp | 113 + test/CXX/dcl.decl/dcl.init/dcl.init.list/p7-0x.cpp | 14 + .../dcl.init/dcl.init.ref/p5-cxx03-extra-copy.cpp | 2 +- .../dcl.meaning/dcl.fct/dcl.fct.def.default/p1.cpp | 16 + .../dcl.meaning/dcl.fct/dcl.fct.def.default/p2.cpp | 27 +- test/CXX/dcl.decl/dcl.meaning/dcl.fct/p9-0x.cpp | 6 +- test/CXX/except/except.spec/p14.cpp | 24 + test/CXX/except/except.spec/p5-pointers.cpp | 6 +- test/CXX/expr/expr.const/p2-0x.cpp | 6 +- .../expr/expr.post/expr.reinterpret.cast/p1-0x.cpp | 7 +- .../expr.prim/expr.prim.lambda/blocks-irgen.mm | 29 + test/CXX/expr/expr.prim/expr.prim.lambda/blocks.mm | 38 + test/CXX/expr/expr.prim/expr.prim.lambda/p23.cpp | 4 +- test/CXX/expr/expr.prim/expr.prim.lambda/p4.cpp | 8 +- test/CXX/expr/expr.unary/expr.unary.op/p6.cpp | 2 +- test/CXX/expr/p10-0x.cpp | 46 + test/CXX/special/class.conv/class.conv.ctor/p1.cpp | 21 + test/CXX/special/class.copy/implicit-move.cpp | 7 + test/CXX/special/class.copy/p11.0x.copy.cpp | 16 +- test/CXX/special/class.copy/p13-0x.cpp | 56 + test/CXX/special/class.copy/p15-inclass.cpp | 2 +- test/CXX/special/class.copy/p23-cxx11.cpp | 148 + test/CXX/special/class.copy/p8-cxx11.cpp | 2 +- test/CXX/special/class.ctor/p5-0x.cpp | 6 +- test/CXX/special/class.ctor/p6-0x.cpp | 39 + test/CXX/special/class.dtor/p5-0x.cpp | 8 +- test/CXX/stmt.stmt/stmt.iter/stmt.ranged/p1.cpp | 9 + test/CXX/temp/temp.decls/temp.friend/p1.cpp | 3 + .../temp.variadic/multi-level-substitution.cpp | 43 + test/CXX/temp/temp.names/p3-0x.cpp | 12 + test/CXX/temp/temp.spec/p5.cpp | 2 +- test/CXX/temp/temp.spec/temp.expl.spec/p14.cpp | 2 +- test/CXX/temp/temp.spec/temp.expl.spec/p3.cpp | 8 +- test/CXX/temp/temp.spec/temp.explicit/p12.cpp | 49 +- .../temp/temp.spec/temp.explicit/p9-linkage.cpp | 2 +- test/CodeCompletion/auto.cpp | 2 + test/CodeCompletion/documentation.cpp | 33 + test/CodeCompletion/objc-expr.m | 17 + test/CodeGen/2002-05-24-Alloca.c | 11 - test/CodeGen/2005-07-20-SqrtNoErrno.c | 2 +- test/CodeGen/2007-02-25-C-DotDotDot.c | 2 +- test/CodeGen/2008-01-25-ByValReadNone.c | 2 +- test/CodeGen/2008-03-05-syncPtr.c | 2 +- test/CodeGen/2008-04-08-NoExceptions.c | 2 +- test/CodeGen/2009-02-13-zerosize-union-field-ppc.c | 1 + test/CodeGen/2009-09-24-SqrtErrno.c | 2 +- test/CodeGen/2009-10-20-GlobalDebug.c | 4 +- test/CodeGen/2010-02-10-PointerName.c | 2 +- test/CodeGen/2010-05-26-AsmSideEffect.c | 1 + test/CodeGen/Atomics.c | 2 +- test/CodeGen/address-safety-attr.cpp | 6 + test/CodeGen/address-space.c | 6 +- test/CodeGen/alloca.c | 11 + test/CodeGen/altivec.c | 1 + test/CodeGen/annotations-builtin.c | 14 +- test/CodeGen/arm-aapcs-vfp.c | 12 + test/CodeGen/arm-aapcs-zerolength-bitfield.c | 1 + test/CodeGen/arm-apcs-zerolength-bitfield.c | 1 + test/CodeGen/arm-arguments.c | 13 + test/CodeGen/arm-asm-variable.c | 1 + test/CodeGen/arm-asm.c | 1 + test/CodeGen/arm-cc.c | 1 + test/CodeGen/arm-clear.c | 1 + test/CodeGen/arm-homogenous.c | 3 +- test/CodeGen/arm-inline-asm.c | 1 + test/CodeGen/arm-pcs.c | 1 + test/CodeGen/arm-vaarg-align.c | 1 + test/CodeGen/arm-vector-align.c | 1 + test/CodeGen/arm-vector-arguments.c | 1 + test/CodeGen/asm.c | 10 + test/CodeGen/asm_arm.c | 1 + test/CodeGen/atomic_ops.c | 15 +- test/CodeGen/attr-coldhot.c | 9 + test/CodeGen/attributes.c | 8 + test/CodeGen/avx-builtins.c | 70 + test/CodeGen/avx2-builtins.c | 156 + test/CodeGen/block-3.c | 12 + test/CodeGen/block-byref-aggr.c | 71 +- test/CodeGen/blocks.c | 28 +- test/CodeGen/blocksignature.c | 2 +- test/CodeGen/blockwithlocalstatic.c | 6 +- test/CodeGen/bmi-builtins.c | 12 +- test/CodeGen/bool_test.c | 1 + test/CodeGen/bounds-checking.c | 26 + test/CodeGen/branch-target-layout.c | 40 + test/CodeGen/builtin-attributes.c | 1 + test/CodeGen/builtins-arm.c | 1 + test/CodeGen/builtins-mips-args.c | 14 + test/CodeGen/builtins-mips.c | 324 ++ test/CodeGen/builtins-nvptx.c | 98 + test/CodeGen/builtins-ppc-altivec.c | 1 + test/CodeGen/builtins-ptx.c | 99 - test/CodeGen/builtins-x86.c | 1 - test/CodeGen/builtins.c | 6 + test/CodeGen/capture-complex-expr-in-block.c | 2 +- test/CodeGen/catch-undef-behavior.c | 12 +- test/CodeGen/compound-literal.c | 2 +- test/CodeGen/debug-info-gline-tables-only.c | 33 + test/CodeGen/debug-info-gline-tables-only2.c | 13 + test/CodeGen/debug-info-line2.c | 5 +- test/CodeGen/debug-info-line3.c | 4 +- test/CodeGen/debug-info-vla.c | 12 + test/CodeGen/debug-line-1.c | 2 +- test/CodeGen/fma-builtins.c | 166 + test/CodeGen/fma4-builtins.c | 64 +- test/CodeGen/forceinline.c | 14 + test/CodeGen/fp-contract.c | 9 + test/CodeGen/fp16-ops.c | 1 + test/CodeGen/func-aligned.c | 2 +- test/CodeGen/func-in-block.c | 4 +- test/CodeGen/func-return-member.c | 2 +- test/CodeGen/incomplete-function-type.c | 2 +- test/CodeGen/integer-overflow.c | 8 +- test/CodeGen/libcalls.c | 45 + test/CodeGen/mips-byval-arg.c | 15 + test/CodeGen/mips-vector-arg.c | 28 + test/CodeGen/mips-vector-return.c | 31 + test/CodeGen/mips64-class-return.cpp | 2 +- test/CodeGen/ms-declspecs.c | 8 + test/CodeGen/ms-inline-asm.c | 40 + test/CodeGen/no-common.c | 2 +- test/CodeGen/nobuiltin.c | 8 + test/CodeGen/nvptx-cc.c | 9 + test/CodeGen/nvptx-inlineasm.c | 15 + test/CodeGen/object-size.c | 16 +- test/CodeGen/packed-nest-unpacked.c | 18 + test/CodeGen/pclmul-builtins.c | 11 + test/CodeGen/powerpc_types.c | 1 + test/CodeGen/pr12251.c | 2 +- test/CodeGen/pr13168.c | 7 + test/CodeGen/pr5406.c | 1 + test/CodeGen/pragma-visibility.c | 2 +- test/CodeGen/ptx-cc.c | 9 - test/CodeGen/rdrand-builtins.c | 27 + test/CodeGen/regparm-flag.c | 3 +- test/CodeGen/regparm-struct.c | 177 + test/CodeGen/sse-builtins.c | 6 + test/CodeGen/sse4a-builtins.c | 39 + test/CodeGen/struct-init.c | 1 + test/CodeGen/struct-matching-constraint.c | 1 + test/CodeGen/tbaa-for-vptr.cpp | 12 +- test/CodeGen/thread-specifier.c | 15 + test/CodeGen/tls-model.c | 28 + test/CodeGen/varargs.c | 8 +- test/CodeGen/vector-alignment.c | 38 + test/CodeGen/vla.c | 49 + test/CodeGen/vld_dup.c | 1 + test/CodeGen/x86_32-arguments-darwin.c | 13 + test/CodeGen/xop-builtins.c | 326 ++ test/CodeGenCUDA/address-spaces.cu | 24 + test/CodeGenCUDA/ptx-kernels.cu | 2 +- .../anonymous-union-member-initializer.cpp | 10 + test/CodeGenCXX/block-in-ctor-dtor.cpp | 10 +- test/CodeGenCXX/blocks.cpp | 6 +- test/CodeGenCXX/class-layout.cpp | 14 + test/CodeGenCXX/const-init-cxx11.cpp | 32 + test/CodeGenCXX/constructor-init.cpp | 20 + test/CodeGenCXX/cxx0x-delegating-ctors.cpp | 11 + test/CodeGenCXX/cxx0x-initializer-constructors.cpp | 37 + test/CodeGenCXX/cxx0x-initializer-references.cpp | 4 + test/CodeGenCXX/cxx11-initializer-aggregate.cpp | 25 + test/CodeGenCXX/cxx11-vtable-key-function.cpp | 38 + test/CodeGenCXX/debug-info-artificial-arg.cpp | 10 +- test/CodeGenCXX/debug-info-cxx0x.cpp | 10 + test/CodeGenCXX/debug-info-determinism.cpp | 16 + test/CodeGenCXX/debug-info-enum-class.cpp | 15 + test/CodeGenCXX/debug-info-flex-member.cpp | 9 + test/CodeGenCXX/debug-info-fwd-ref.cpp | 6 +- test/CodeGenCXX/debug-info-gline-tables-only.cpp | 21 + test/CodeGenCXX/debug-info-globalinit.cpp | 30 + test/CodeGenCXX/debug-info-nullptr.cpp | 2 +- test/CodeGenCXX/debug-info-rvalue-ref.cpp | 11 + test/CodeGenCXX/debug-info-static-fns.cpp | 2 +- test/CodeGenCXX/debug-info-template-array.cpp | 14 + test/CodeGenCXX/debug-info-template-limit.cpp | 5 +- test/CodeGenCXX/debug-info-template-member.cpp | 2 +- test/CodeGenCXX/debug-info-template-quals.cpp | 23 + test/CodeGenCXX/debug-info-union.cpp | 16 + test/CodeGenCXX/debug-info-user-def.cpp | 14 + test/CodeGenCXX/debug-lambda-expressions.cpp | 50 +- test/CodeGenCXX/derived-to-base-conv.cpp | 111 +- test/CodeGenCXX/destructor-debug-info.cpp | 7 +- test/CodeGenCXX/destructor-exception-spec.cpp | 12 + test/CodeGenCXX/destructors.cpp | 16 + .../devirtualize-virtual-function-calls-final.cpp | 139 +- .../devirtualize-virtual-function-calls.cpp | 30 + test/CodeGenCXX/dynamic-cast-always-null.cpp | 5 + test/CodeGenCXX/exceptions.cpp | 36 + test/CodeGenCXX/global-array-destruction.cpp | 33 +- test/CodeGenCXX/global-block-literal-helpers.cpp | 27 + test/CodeGenCXX/global-init.cpp | 107 +- test/CodeGenCXX/inline-functions.cpp | 14 + test/CodeGenCXX/lambda-expressions.cpp | 8 +- test/CodeGenCXX/mangle-lambdas.cpp | 35 +- test/CodeGenCXX/mangle-ms-abi-examples.cpp | 28 + .../mangle-ms-back-references-pr13207.cpp | 165 + test/CodeGenCXX/mangle-ms-back-references.cpp | 63 + test/CodeGenCXX/mangle-ms-cxx11.cpp | 11 + test/CodeGenCXX/mangle-ms-return-qualifiers.cpp | 173 + test/CodeGenCXX/mangle-ms-templates.cpp | 68 + test/CodeGenCXX/mangle-ms.cpp | 73 +- test/CodeGenCXX/mangle-ref-qualifiers.cpp | 8 +- test/CodeGenCXX/member-data-pointers.cpp | 13 + test/CodeGenCXX/member-function-pointers.cpp | 119 +- test/CodeGenCXX/member-init-anon-union.cpp | 6 +- test/CodeGenCXX/member-init-ctor.cpp | 14 - test/CodeGenCXX/member-pointer-type-convert.cpp | 11 - test/CodeGenCXX/microsoft-abi-array-cookies.cpp | 59 + test/CodeGenCXX/microsoft-abi-constructors.cpp | 21 + test/CodeGenCXX/microsoft-abi-methods.cpp | 89 + .../microsoft-abi-static-initializers.cpp | 52 + test/CodeGenCXX/ms_wide_predefined_expr.cpp | 20 + test/CodeGenCXX/pointers-to-data-members.cpp | 14 + test/CodeGenCXX/pr13396.cpp | 26 + test/CodeGenCXX/pragma-visibility.cpp | 28 +- test/CodeGenCXX/rvalue-references.cpp | 2 +- test/CodeGenCXX/template-instantiation.cpp | 4 +- test/CodeGenCXX/throw-expression-cleanup.cpp | 22 + test/CodeGenCXX/virt-call-offsets.cpp | 8 - test/CodeGenCXX/virt-template-vtable.cpp | 10 + test/CodeGenCXX/virtual-destructor-calls.cpp | 11 + test/CodeGenCXX/visibility-inlines-hidden.cpp | 18 + test/CodeGenCXX/visibility.cpp | 511 ++- test/CodeGenObjC/2008-11-12-Metadata.m | 2 +- test/CodeGenObjC/2008-11-24-ConstCFStrings.m | 2 +- test/CodeGenObjC/2010-03-17-StructRef.m | 2 +- test/CodeGenObjC/arc-blocks.m | 17 +- test/CodeGenObjC/arc.m | 3 + test/CodeGenObjC/assign.m | 2 +- test/CodeGenObjC/autorelease.m | 4 +- test/CodeGenObjC/bitfield-1.m | 6 +- test/CodeGenObjC/bitfield-access.m | 4 +- test/CodeGenObjC/bitfield-gnu.m | 2 +- test/CodeGenObjC/bitfield_encoding.m | 4 +- test/CodeGenObjC/block-6.m | 2 +- test/CodeGenObjC/block-var-layout.m | 2 +- test/CodeGenObjC/blocks-1.m | 4 +- test/CodeGenObjC/blocks-2.m | 6 +- test/CodeGenObjC/blocks-3.m | 2 +- test/CodeGenObjC/blocks-4.m | 2 +- test/CodeGenObjC/blocks-5.m | 2 +- test/CodeGenObjC/blocks.m | 6 +- test/CodeGenObjC/boxing.m | 95 + test/CodeGenObjC/builtins.m | 2 +- test/CodeGenObjC/category-class.m | 2 +- test/CodeGenObjC/class-type.m | 6 +- test/CodeGenObjC/constant-string-class.m | 2 +- test/CodeGenObjC/constant-strings.m | 4 +- test/CodeGenObjC/deadcode_strip_used_var.m | 4 +- test/CodeGenObjC/debug-info-block-helper.m | 4 +- test/CodeGenObjC/debug-info-crash.m | 2 +- test/CodeGenObjC/debug-info-static-var.m | 2 +- test/CodeGenObjC/debug-info-synthesis.m | 2 +- test/CodeGenObjC/encode-cstyle-method.m | 2 +- test/CodeGenObjC/encode-test-6.m | 19 + test/CodeGenObjC/encode-test.m | 2 +- test/CodeGenObjC/exceptions.m | 2 +- test/CodeGenObjC/fp2ret.m | 6 +- test/CodeGenObjC/fpret.m | 6 +- test/CodeGenObjC/getter-property-mismatch.m | 20 + test/CodeGenObjC/getter-property-type-mismatch.m | 35 + test/CodeGenObjC/gnu-exceptions.m | 2 +- test/CodeGenObjC/id-isa-codegen.m | 4 +- test/CodeGenObjC/image-info.m | 2 +- test/CodeGenObjC/implicit-objc_msgSend.m | 2 +- test/CodeGenObjC/interface-layout-64.m | 47 +- test/CodeGenObjC/interface.m | 2 +- test/CodeGenObjC/ivar-layout-64-bitfields.m | 4 +- test/CodeGenObjC/ivar-layout-array0-struct.m | 2 +- test/CodeGenObjC/ivar-layout-no-optimize.m | 4 +- test/CodeGenObjC/ivars.m | 4 +- test/CodeGenObjC/layout-bitfield-crash.m | 35 + test/CodeGenObjC/link-errors.m | 4 +- test/CodeGenObjC/local-static-block.m | 2 +- test/CodeGenObjC/messages-2.m | 2 +- test/CodeGenObjC/messages.m | 6 +- test/CodeGenObjC/metadata-symbols-32.m | 2 +- test/CodeGenObjC/misc-atomic-property.m | 2 +- test/CodeGenObjC/mrr-autorelease.m | 2 +- test/CodeGenObjC/nested-rethrow.m | 2 +- test/CodeGenObjC/next-objc-dispatch.m | 2 +- test/CodeGenObjC/no-category-class.m | 2 +- test/CodeGenObjC/nonlazy-msgSend.m | 2 +- test/CodeGenObjC/ns-constant-strings.m | 2 +- test/CodeGenObjC/objc-align.m | 2 +- test/CodeGenObjC/objc-assign-ivar.m | 2 +- test/CodeGenObjC/objc-gc-aggr-assign.m | 4 +- test/CodeGenObjC/objc-literal-debugger-test.m | 39 +- test/CodeGenObjC/objc-read-weak-byref.m | 4 +- test/CodeGenObjC/objc2-assign-global.m | 2 +- test/CodeGenObjC/objc2-new-gc-api-strongcast.m | 4 +- test/CodeGenObjC/objc2-no-write-barrier.m | 4 +- test/CodeGenObjC/objc2-retain-codegen.m | 4 +- test/CodeGenObjC/objc2-strong-cast-1.m | 4 +- test/CodeGenObjC/objc2-weak-assign.m | 4 +- test/CodeGenObjC/objc2-weak-block-call.m | 4 +- test/CodeGenObjC/objc2-weak-compare.m | 4 +- test/CodeGenObjC/objc2-weak-ivar-debug.m | 8 +- test/CodeGenObjC/objc2-weak-ivar.m | 4 +- test/CodeGenObjC/objc2-write-barrier-2.m | 4 +- test/CodeGenObjC/objc2-write-barrier-4.m | 4 +- test/CodeGenObjC/objc2-write-barrier-5.m | 4 +- test/CodeGenObjC/objc2-write-barrier.m | 4 +- test/CodeGenObjC/object-incr-decr-1.m | 2 +- test/CodeGenObjC/objfw.m | 15 + test/CodeGenObjC/predefined-expr.m | 2 +- test/CodeGenObjC/property-complex.m | 4 +- test/CodeGenObjC/property-ref-cast-to-void.m | 4 +- test/CodeGenObjC/protocol-in-extended-class.m | 2 +- test/CodeGenObjC/protocols-lazy.m | 2 +- .../rdr-6732143-dangling-block-reference.m | 2 +- test/CodeGenObjC/super-message-fragileabi.m | 2 +- test/CodeGenObjC/synchronized.m | 2 +- test/CodeGenObjC/terminate.m | 4 +- test/CodeGenObjC/undefined-protocol.m | 2 +- test/CodeGenObjC/variadic-sends.m | 4 +- test/CodeGenObjC/x86_64-struct-return-gc.m | 2 +- test/CodeGenObjCXX/arc.mm | 16 + test/CodeGenObjCXX/block-in-template-inst.mm | 2 +- test/CodeGenObjCXX/block-var-layout.mm | 2 +- test/CodeGenObjCXX/blocks.mm | 21 +- test/CodeGenObjCXX/catch-id-type.mm | 2 +- test/CodeGenObjCXX/copy.mm | 2 +- test/CodeGenObjCXX/copyable-property-object.mm | 2 +- test/CodeGenObjCXX/encode.mm | 58 +- test/CodeGenObjCXX/gc.mm | 2 +- .../CodeGenObjCXX/implicit-copy-assign-operator.mm | 2 +- test/CodeGenObjCXX/implicit-copy-constructor.mm | 2 +- test/CodeGenObjCXX/lambda-expressions.mm | 10 +- test/CodeGenObjCXX/mangle-blocks.mm | 18 +- test/CodeGenObjCXX/message-reference.mm | 2 +- test/CodeGenObjCXX/nrvo.mm | 4 +- .../CodeGenObjCXX/property-derived-to-base-conv.mm | 2 +- .../property-object-conditional-exp.mm | 2 +- test/CodeGenObjCXX/property-object-reference-2.mm | 2 +- test/CodeGenObjCXX/property-object-reference.mm | 2 +- test/CodeGenObjCXX/property-reference.mm | 2 +- test/CodeGenObjCXX/refence-assign-write-barrier.mm | 2 +- test/CodeGenObjCXX/selector-expr-lvalue.mm | 2 +- test/CodeGenObjCXX/write-barrier-global-assign.mm | 2 +- test/CodeGenOpenCL/kernel-arg-info.cl | 7 + test/CodeGenOpenCL/kernel-attributes.cl | 12 + test/CodeGenOpenCL/ptx-calls.cl | 2 +- test/CodeGenOpenCL/ptx-kernels.cl | 2 +- test/Coverage/codegen-gnu.m | 2 +- .../basic_android_tree/usr/lib/crtbegin_dynamic.o | 0 .../basic_android_tree/usr/lib/crtbegin_so.o | 0 .../basic_android_tree/usr/lib/crtbegin_static.o | 0 .../basic_android_tree/usr/lib/crtend_android.o | 0 .../Inputs/basic_android_tree/usr/lib/crtend_so.o | 0 .../debian_multiarch_tree/lib/mips-linux-gnu/.keep | 0 .../lib/mipsel-linux-gnu/.keep | 0 .../usr/include/c++/4.5/mips-linux-gnu/.keep | 0 .../usr/include/c++/4.5/mipsel-linux-gnu/.keep | 0 .../usr/include/mips-linux-gnu/.keep | 0 .../usr/include/mipsel-linux-gnu/.keep | 0 .../usr/lib/gcc/mips-linux-gnu/4.5/64/crtbegin.o | 0 .../usr/lib/gcc/mips-linux-gnu/4.5/crtbegin.o | 0 .../usr/lib/gcc/mips-linux-gnu/4.5/n32/crtbegin.o | 0 .../usr/lib/gcc/mipsel-linux-gnu/4.5/64/crtbegin.o | 0 .../usr/lib/gcc/mipsel-linux-gnu/4.5/crtbegin.o | 0 .../lib/gcc/mipsel-linux-gnu/4.5/n32/crtbegin.o | 0 .../usr/lib/mips-linux-gnu/.keep | 0 .../usr/lib/mipsel-linux-gnu/.keep | 0 .../lib/gcc/i686-montavista-linux/4.2.0/crtbegin.o | 1 + .../lib/gcc/i686-montavista-linux/4.2.0/libgcc.a | 1 + .../ubuntu_12.04_LTS_multiarch_tree/lib/.keep | 0 .../lib/arm-linux-gnueabi/.keep | 0 .../lib/arm-linux-gnueabihf/.keep | 0 .../usr/include/.keep | 0 .../usr/include/arm-linux-gnueabi/.keep | 0 .../usr/include/arm-linux-gnueabihf/.keep | 0 .../ubuntu_12.04_LTS_multiarch_tree/usr/lib/.keep | 0 .../usr/lib/arm-linux-gnueabi/crt1.o | 0 .../usr/lib/arm-linux-gnueabi/crti.o | 0 .../usr/lib/arm-linux-gnueabi/crtn.o | 0 .../usr/lib/arm-linux-gnueabihf/crt1.o | 0 .../usr/lib/arm-linux-gnueabihf/crti.o | 0 .../usr/lib/arm-linux-gnueabihf/crtn.o | 0 .../usr/lib/gcc/arm-linux-gnueabi/4.6.1/crtbegin.o | 0 .../usr/lib/gcc/arm-linux-gnueabi/4.6.1/crtend.o | 0 .../lib/gcc/arm-linux-gnueabihf/4.6.3/crtbegin.o | 0 .../usr/lib/gcc/arm-linux-gnueabihf/4.6.3/crtend.o | 0 test/Driver/altivec.cpp | 3 +- test/Driver/apple-kext-i386.cpp | 5 + test/Driver/arc.c | 4 +- test/Driver/arclite-link.c | 11 +- test/Driver/asan-ld.c | 31 + test/Driver/bounds-checking.c | 7 + test/Driver/ccc-as-cpp.c | 6 + test/Driver/clang-translation.c | 30 + test/Driver/clang_f_opts.c | 9 + test/Driver/clang_f_opts.h | 2 + test/Driver/constructors.c | 14 + test/Driver/crash-report.c | 27 + test/Driver/darwin-ld.c | 5 + test/Driver/darwin-objc-defaults.m | 18 +- test/Driver/darwin-objc-options.m | 15 +- test/Driver/debug-options-as.c | 6 +- test/Driver/debug-options.c | 49 +- test/Driver/debug-unsupported.c | 13 + test/Driver/fast-math.c | 24 +- test/Driver/flags.c | 2 + test/Driver/fpack-struct.c | 10 + test/Driver/freebsd.c | 16 + test/Driver/gnu-runtime.m | 5 +- test/Driver/ios-simulator-arcruntime.c | 8 +- test/Driver/linker-opts.c | 2 +- test/Driver/linux-as.c | 37 +- test/Driver/linux-ld.c | 130 + test/Driver/mips-as.c | 19 +- test/Driver/mips-features.c | 39 + test/Driver/mips-float.c | 1 + test/Driver/montavista-gcc-toolchain.c | 9 + test/Driver/msvc_forward.c | 5 + test/Driver/nodefaultlib.c | 8 + test/Driver/rewrite-legacy-objc.m | 2 +- test/Driver/rewrite-objc.m | 2 +- test/Driver/target-triple-deployment.c | 33 + test/Driver/warning-options.cpp | 10 + test/Driver/warning-options_pedantic.cpp | 7 + test/FixIt/fixit-autoreleasepool.m | 9 + test/FixIt/fixit-cxx0x.cpp | 14 + test/FixIt/fixit-include.c | 13 + test/FixIt/fixit-include.h | 1 + test/FixIt/fixit-interface-as-param.m | 11 + test/FixIt/fixit-objc-message-comma-separator.m | 17 + test/FixIt/fixit-unicode.c | 33 + test/FixIt/fixit-vexing-parse.cpp | 51 +- test/FixIt/fixit.c | 8 + test/FixIt/fixit.cpp | 90 +- test/FixIt/format-no-fixit.m | 30 + test/FixIt/format.m | 95 + test/FixIt/messages.cpp | 13 + test/FixIt/objc-literals.m | 16 +- .../Inputs/SystemHeaderPrefix/libs/boost/all.h | 1 + .../Inputs/SystemHeaderPrefix/libs/boost/warn.h | 2 + .../Inputs/SystemHeaderPrefix/libs/mylib/all.h | 1 + .../Inputs/SystemHeaderPrefix/libs/mylib/warn.h | 2 + test/Frontend/Inputs/SystemHeaderPrefix/src/all.h | 6 + test/Frontend/Inputs/SystemHeaderPrefix/src/warn.h | 2 + test/Frontend/Inputs/rewrite-includes1.h | 3 + test/Frontend/Inputs/rewrite-includes2.h | 1 + test/Frontend/Inputs/rewrite-includes3.h | 1 + test/Frontend/Inputs/rewrite-includes4.h | 1 + test/Frontend/Inputs/rewrite-includes5.h | 1 + test/Frontend/Inputs/rewrite-includes6.h | 2 + test/Frontend/Inputs/rewrite-includes7.h | 4 + test/Frontend/rewrite-includes-missing.c | 7 + test/Frontend/rewrite-includes.c | 145 + test/Frontend/system-header-prefix.c | 11 + test/Frontend/verify-directive.h | 2 + test/Frontend/verify-fatal.c | 12 + test/Frontend/verify.c | 125 + test/Frontend/verify2.c | 19 + test/Frontend/verify2.h | 5 + test/Headers/ms-null-ms-header-vs-stddef.cpp | 16 + .../Inputs/CommentXML/invalid-function-01.xml | 7 + .../Inputs/CommentXML/invalid-function-02.xml | 9 + .../Inputs/CommentXML/invalid-function-03.xml | 11 + .../Inputs/CommentXML/invalid-function-04.xml | 11 + .../Inputs/CommentXML/invalid-function-05.xml | 10 + .../Inputs/CommentXML/invalid-function-06.xml | 5 + .../Inputs/CommentXML/invalid-function-07.xml | 13 + .../Inputs/CommentXML/invalid-function-08.xml | 13 + .../Inputs/CommentXML/invalid-function-09.xml | 13 + .../Inputs/CommentXML/invalid-function-10.xml | 11 + .../Inputs/CommentXML/invalid-function-11.xml | 13 + .../Inputs/CommentXML/invalid-function-12.xml | 6 + test/Index/Inputs/CommentXML/valid-class-01.xml | 5 + test/Index/Inputs/CommentXML/valid-class-02.xml | 5 + test/Index/Inputs/CommentXML/valid-class-03.xml | 5 + test/Index/Inputs/CommentXML/valid-class-04.xml | 5 + test/Index/Inputs/CommentXML/valid-enum-01.xml | 6 + test/Index/Inputs/CommentXML/valid-function-01.xml | 5 + test/Index/Inputs/CommentXML/valid-function-02.xml | 5 + test/Index/Inputs/CommentXML/valid-function-03.xml | 12 + test/Index/Inputs/CommentXML/valid-function-04.xml | 13 + test/Index/Inputs/CommentXML/valid-function-05.xml | 8 + test/Index/Inputs/CommentXML/valid-function-06.xml | 6 + test/Index/Inputs/CommentXML/valid-function-07.xml | 30 + test/Index/Inputs/CommentXML/valid-function-08.xml | 17 + test/Index/Inputs/CommentXML/valid-function-09.xml | 6 + test/Index/Inputs/CommentXML/valid-function-10.xml | 6 + .../Index/Inputs/CommentXML/valid-namespace-01.xml | 6 + test/Index/Inputs/CommentXML/valid-other-01.xml | 5 + test/Index/Inputs/CommentXML/valid-typedef-01.xml | 6 + test/Index/Inputs/CommentXML/valid-typedef-02.xml | 25 + test/Index/Inputs/CommentXML/valid-variable-01.xml | 6 + test/Index/Inputs/annotate-comments-preprocessor.h | 2 + test/Index/annotate-comments-preprocessor.c | 45 + test/Index/annotate-comments-unterminated.c | 13 + test/Index/annotate-comments.cpp | 926 ++++ test/Index/availability.c | 10 + test/Index/boxed-exprs.h | 10 + test/Index/boxed-exprs.m | 19 + test/Index/c-index-api-loadTU-test.m | 2 +- test/Index/comment-xml-schema.c | 43 + test/Index/compile_commands.json | 27 + test/Index/complete-documentation.cpp | 51 + test/Index/complete-exprs.m | 10 +- test/Index/complete-lambdas.mm | 51 + test/Index/complete-method-decls.m | 2 +- test/Index/complete-properties.m | 14 + test/Index/create-tu-fail.c | 10 + test/Index/cursor-dynamic-call.mm | 59 + test/Index/get-cursor.c | 6 + test/Index/get-cursor.cpp | 10 + test/Index/get-cursor.m | 33 + test/Index/index-decls.m | 17 +- test/Index/index-kernel-invocation.cpp | 4 + test/Index/index-many-call-ops.cpp | 47 + test/Index/index-refs.m | 18 + test/Index/overrides.m | 58 + test/Index/pch-with-errors.c | 4 +- test/Index/print-typekind.m | 6 +- test/Index/recursive-cxx-member-calls.cpp | 5 +- test/Lexer/bcpl-escaped-newline.c | 3 +- test/Lexer/c90.c | 7 + test/Lexer/char-literal.cpp | 3 + test/Lexer/hexfloat.cpp | 8 + test/Lexer/newline-eof.c | 4 + test/Lexer/pragma-operators.cpp | 1 - test/Lexer/wchar-signedness.c | 8 + test/Misc/ast-dump-wchar.cpp | 13 + test/Misc/diag-aka-types.cpp | 23 +- test/Misc/diag-template-diffing-color.cpp | 19 + test/Misc/diag-template-diffing.cpp | 433 ++ test/Misc/diag-trailing-null-bytes.cpp | 10 + test/Misc/emit-html.c | 8 + test/Misc/integer-literal-printing.cpp | 4 +- test/Misc/serialized-diags-frontend.c | 8 + test/Misc/show-diag-options.c | 2 +- test/Misc/tabstop.c | 9 + test/Misc/warning-flags-enabled.c | 27 + test/Misc/warning-flags-tree.c | 56 + test/Misc/warning-flags.c | 103 +- test/Misc/wnull-character.cpp | Bin 143 -> 0 bytes .../Inputs/Module.framework/Headers/Module.h | 6 +- test/Modules/Inputs/category_right.h | 2 +- test/Modules/Inputs/import-decl.h | 1 + test/Modules/Inputs/module.map | 3 + test/Modules/cstd.m | 2 +- test/Modules/import-decl.cpp | 10 + test/Modules/lookup.cpp | 2 + test/Modules/objc-categories.m | 1 + test/Modules/on-demand-build.m | 5 +- test/PCH/Inputs/__va_list_tag.h | 5 + test/PCH/__va_list_tag.c | 12 + test/PCH/attrs.c | 3 +- test/PCH/badpch-dir.h.gch/.keep | 0 test/PCH/badpch-empty.h.gch | 0 test/PCH/badpch.c | 13 + test/PCH/chain-staticvar-instantiation.cpp | 45 + test/PCH/chain-trivial.c | 2 - test/PCH/cxx-friends.cpp | 8 + test/PCH/cxx-friends.h | 12 + test/PCH/cxx-member-init.cpp | 4 + test/PCH/cxx-static_assert.cpp | 3 +- test/PCH/cxx-trailing-return.cpp | 6 +- test/PCH/cxx0x-default-delete.cpp | 12 +- test/PCH/cxx0x-delegating-ctors.cpp | 12 +- test/PCH/cxx11-constexpr.cpp | 6 +- test/PCH/cxx11-enum-template.cpp | 4 +- test/PCH/cxx11-user-defined-literals.cpp | 3 +- test/PCH/empty-with-headers.c | 27 + test/PCH/exprs.h | 2 +- test/PCH/format-strings.c | 18 + test/PCH/ms-if-exists.cpp | 3 +- test/PCH/objc_methods.h | 30 + test/PCH/objc_methods.m | 2 +- test/PCH/objc_stmts.m | 4 +- test/PCH/pch__VA_ARGS__.c | 6 + test/PCH/pch__VA_ARGS__.h | 2 + test/PCH/remap-file-from-pch.cpp | 10 + test/PCH/remap-file-from-pch.cpp.h | 2 + test/PCH/remap-file-from-pch.cpp.remap.h | 4 + test/PCH/replaced-decl.m | 3 +- test/PCH/typo2.cpp | 3 +- test/PCH/variables.c | 12 +- test/Parser/DelayedTemplateParsing.cpp | 13 +- test/Parser/MicrosoftExtensions.c | 43 +- test/Parser/MicrosoftExtensions.cpp | 60 +- test/Parser/altivec.c | 10 + test/Parser/c1x-alignas.c | 8 +- test/Parser/completely-empty-header-file.h | 0 test/Parser/cuda-kernel-call.cu | 7 + test/Parser/cxx-class.cpp | 8 +- test/Parser/cxx-decl.cpp | 6 +- test/Parser/cxx-extra-semi.cpp | 41 + test/Parser/cxx-template-argument.cpp | 15 + test/Parser/cxx-throw.cpp | 2 + test/Parser/cxx-undeclared-identifier.cpp | 12 + test/Parser/cxx-using-declaration.cpp | 16 + test/Parser/cxx-using-directive.cpp | 5 +- test/Parser/cxx0x-ambig.cpp | 6 +- test/Parser/cxx0x-attributes.cpp | 135 +- test/Parser/cxx0x-decl.cpp | 16 +- test/Parser/cxx0x-lambda-expressions.cpp | 7 + test/Parser/cxx11-type-specifier.cpp | 4 + test/Parser/declarators.c | 12 + test/Parser/empty-translation-unit.c | 10 + test/Parser/missing-selector-name.mm | 52 + test/Parser/ms-inline-asm.c | 33 +- test/Parser/objc-boxing.m | 26 + test/Parser/objc-diag-width.mm | 8 + test/Parser/objc-forcollection-neg.m | 4 +- test/Parser/objc-init.m | 4 +- test/Parser/objc-recover.mm | 64 + test/Parser/objcxx11-attributes.mm | 3 +- test/Parser/opencl-pragma.cl | 2 +- test/Parser/recovery.c | 5 +- test/Parser/recovery.cpp | 12 +- test/Preprocessor/_Pragma-location.c | 49 +- test/Preprocessor/comment_save.c | 14 + test/Preprocessor/disabled-cond-diags2.c | 27 + test/Preprocessor/has_attribute.c | 10 + test/Preprocessor/has_include.c | 48 +- test/Preprocessor/init.c | 440 +- test/Preprocessor/line-directive.c | 14 +- test/Preprocessor/macro_fn.c | 18 +- test/Preprocessor/macro_paste_c_block_comment.c | 4 + test/Preprocessor/macro_paste_identifier_error.c | 7 + test/Preprocessor/mmx.c | 3 + test/Preprocessor/non_fragile_feature1.m | 2 +- test/Preprocessor/pp-record.c | 11 + test/Preprocessor/predefined-arch-macros.c | 205 +- test/Preprocessor/predefined-macros.c | 13 + test/Preprocessor/undef-error.c | 2 +- test/Preprocessor/warning_tests.c | 8 +- test/Rewriter/blockcast3.mm | 2 +- test/Rewriter/blockstruct.m | 2 +- test/Rewriter/crash.m | 2 +- test/Rewriter/finally.m | 2 +- test/Rewriter/func-in-impl.m | 2 +- test/Rewriter/id-test-3.m | 2 +- test/Rewriter/inner-block-helper-funcs.mm | 2 +- test/Rewriter/instancetype-test.mm | 2 +- test/Rewriter/ivar-encoding-1.m | 2 +- test/Rewriter/ivar-encoding-2.m | 2 +- test/Rewriter/metadata-test-1.m | 2 +- test/Rewriter/metadata-test-2.m | 2 +- test/Rewriter/method-encoding-1.m | 2 +- test/Rewriter/objc-bool-literal-modern-1.mm | 3 + test/Rewriter/objc-encoding-bug-1.m | 2 +- test/Rewriter/objc-ivar-receiver-1.m | 4 +- test/Rewriter/objc-modern-StretAPI.mm | 45 + test/Rewriter/objc-modern-boxing.mm | 72 + test/Rewriter/objc-modern-container-subscript.mm | 3 +- test/Rewriter/objc-modern-getclass-proto.mm | 10 + test/Rewriter/objc-modern-property-attributes.mm | 10 + test/Rewriter/objc-string-concat-1.m | 2 +- test/Rewriter/objc-super-test.m | 2 +- test/Rewriter/objc-synchronized-1.m | 2 +- test/Rewriter/properties.m | 2 +- test/Rewriter/property-dot-syntax.mm | 2 +- test/Rewriter/protocol-rewrite-1.m | 2 +- test/Rewriter/protocol-rewrite-2.m | 2 +- test/Rewriter/rewrite-anonymous-union.m | 2 +- test/Rewriter/rewrite-api-bug.m | 2 +- test/Rewriter/rewrite-block-argument.m | 2 +- test/Rewriter/rewrite-block-consts.mm | 2 +- test/Rewriter/rewrite-block-ivar-call.mm | 2 +- test/Rewriter/rewrite-block-literal-1.mm | 5 +- test/Rewriter/rewrite-block-literal.mm | 5 +- test/Rewriter/rewrite-block-pointer.mm | 5 +- test/Rewriter/rewrite-block-property.m | 2 +- test/Rewriter/rewrite-byref-in-nested-blocks.mm | 9 +- test/Rewriter/rewrite-byref-vars.mm | 4 +- test/Rewriter/rewrite-cast-ivar-access.mm | 2 +- test/Rewriter/rewrite-cast-to-bool.mm | 2 +- test/Rewriter/rewrite-category-property.mm | 2 +- test/Rewriter/rewrite-constructor-init.mm | 2 +- test/Rewriter/rewrite-eh.m | 2 +- test/Rewriter/rewrite-elaborated-type.mm | 2 +- test/Rewriter/rewrite-extern-c.mm | 2 +- test/Rewriter/rewrite-foreach-1.m | 2 +- test/Rewriter/rewrite-foreach-2.m | 2 +- test/Rewriter/rewrite-foreach-3.m | 2 +- test/Rewriter/rewrite-foreach-4.m | 2 +- test/Rewriter/rewrite-foreach-5.m | 2 +- test/Rewriter/rewrite-foreach-6.m | 2 +- test/Rewriter/rewrite-foreach-7.m | 2 +- test/Rewriter/rewrite-foreach-in-block.mm | 4 +- test/Rewriter/rewrite-foreach-protocol-id.m | 2 +- test/Rewriter/rewrite-forward-class.m | 2 +- test/Rewriter/rewrite-forward-class.mm | 2 +- test/Rewriter/rewrite-function-decl.mm | 2 +- test/Rewriter/rewrite-implementation.mm | 2 +- test/Rewriter/rewrite-ivar-use.m | 2 +- test/Rewriter/rewrite-local-externs-in-block.mm | 2 +- test/Rewriter/rewrite-local-static-id.mm | 2 +- test/Rewriter/rewrite-message-expr.mm | 2 +- test/Rewriter/rewrite-modern-atautoreleasepool.mm | 32 + test/Rewriter/rewrite-modern-block-consts.mm | 22 + test/Rewriter/rewrite-modern-block.mm | 44 +- .../rewrite-modern-captured-nested-bvar.mm | 35 + .../rewrite-modern-default-property-synthesis.mm | 80 + test/Rewriter/rewrite-modern-extern-c-func-decl.mm | 49 + test/Rewriter/rewrite-modern-ivar-access.mm | 98 + test/Rewriter/rewrite-modern-ivars-1.mm | 37 +- test/Rewriter/rewrite-modern-private-ivars.mm | 53 + test/Rewriter/rewrite-modern-struct-ivar-1.mm | 48 + test/Rewriter/rewrite-modern-struct-ivar.mm | 32 +- test/Rewriter/rewrite-modern-typeof.mm | 1 + test/Rewriter/rewrite-nest.m | 2 +- test/Rewriter/rewrite-nested-blocks-1.mm | 3 +- test/Rewriter/rewrite-nested-blocks-2.mm | 3 +- test/Rewriter/rewrite-nested-blocks.mm | 3 +- test/Rewriter/rewrite-nested-ivar.mm | 2 +- test/Rewriter/rewrite-nested-property-in-blocks.mm | 3 +- test/Rewriter/rewrite-no-nextline.mm | 2 +- test/Rewriter/rewrite-property-attributes.mm | 2 +- test/Rewriter/rewrite-property-set-cfstring.mm | 2 +- test/Rewriter/rewrite-protocol-property.mm | 2 +- test/Rewriter/rewrite-protocol-qualified.mm | 2 +- test/Rewriter/rewrite-protocol-type-1.m | 2 +- test/Rewriter/rewrite-qualified-id.mm | 2 +- test/Rewriter/rewrite-rewritten-initializer.mm | 7 +- test/Rewriter/rewrite-static-block.mm | 2 +- test/Rewriter/rewrite-super-message.mm | 2 +- test/Rewriter/rewrite-trivial-constructor.mm | 2 +- test/Rewriter/rewrite-try-catch.m | 2 +- test/Rewriter/rewrite-typeof.mm | 2 +- test/Rewriter/rewrite-unique-block-api.mm | 3 +- test/Rewriter/rewrite-user-defined-accessors.mm | 2 +- test/Rewriter/rewrite-vararg.m | 2 +- test/Rewriter/rewrite-weak-attr.m | 2 +- test/Rewriter/static-type-protocol-1.m | 2 +- test/Rewriter/undecl-objc-h.m | 2 +- test/Rewriter/undeclared-method-1.m | 2 +- test/Rewriter/undef-field-reference-1.m | 2 +- test/Rewriter/va-method.m | 2 +- test/Rewriter/weak_byref_objects.m | 2 +- test/Sema/128bitint.c | 9 +- test/Sema/Inputs/format-unused-system-args.h | 8 + test/Sema/MicrosoftCompatibility.c | 7 +- test/Sema/MicrosoftExtensions.c | 8 +- test/Sema/alignas.c | 13 +- test/Sema/alloc_size.c | 26 + test/Sema/annotate.c | 5 +- test/Sema/array-bounds-ptr-arith.c | 18 + test/Sema/array-init.c | 2 +- test/Sema/attr-aligned.c | 2 +- test/Sema/attr-availability-ios.c | 8 +- test/Sema/attr-availability-macosx.c | 2 +- test/Sema/attr-availability.c | 21 +- test/Sema/attr-coldhot.c | 10 + test/Sema/attr-decl-after-definition.c | 22 +- test/Sema/attr-deprecated-message.c | 8 +- test/Sema/attr-deprecated.c | 29 +- test/Sema/attr-nodebug.c | 7 +- test/Sema/attr-section.c | 4 + test/Sema/attr-tls_model.c | 14 + test/Sema/attr-unavailable-message.c | 4 +- test/Sema/attr-visibility.c | 15 + test/Sema/c89-2.c | 2 +- test/Sema/compare.c | 7 + test/Sema/conditional-expr.c | 2 +- test/Sema/const-eval.c | 3 + test/Sema/dllimport-dllexport.c | 6 + test/Sema/exprs.c | 15 +- test/Sema/format-strings-enum-fixed-type.cpp | 92 + test/Sema/format-strings-enum.c | 36 + test/Sema/format-strings-fixit.c | 34 + test/Sema/format-strings-scanf.c | 55 + test/Sema/format-strings-size_t.c | 13 + test/Sema/format-strings.c | 117 +- test/Sema/fpack-struct.c | 4 +- test/Sema/implicit-builtin-decl.c | 2 + test/Sema/inline.c | 72 + test/Sema/invalid-decl.c | 9 + test/Sema/knr-def-call.c | 4 +- test/Sema/ms_class_layout.cpp | 173 + test/Sema/ms_wide_predefined_expr.cpp | 25 + test/Sema/pragma-pack-6.c | 16 + test/Sema/switch.c | 31 +- test/Sema/thread-specifier.c | 12 +- test/Sema/tls.c | 20 + test/Sema/typeof-use-deprecated.c | 12 +- test/Sema/uninit-variables.c | 104 +- test/Sema/unused-expr.c | 3 +- test/Sema/vector-ops.c | 2 +- test/Sema/warn-documentation-almost-trailing.c | 14 + test/Sema/warn-documentation-fixits.cpp | 27 + test/Sema/warn-documentation.cpp | 670 +++ test/Sema/warn-documentation.m | 93 + test/Sema/warn-outof-range-assign-enum.c | 32 + test/Sema/warn-self-assign-field.mm | 66 + test/Sema/warn-strncat-size.c | 7 +- test/SemaCXX/MicrosoftCompatibility.cpp | 4 + .../SemaCXX/MicrosoftCompatibilityNoExceptions.cpp | 8 + test/SemaCXX/PR10243.cpp | 4 +- test/SemaCXX/abstract.cpp | 14 + test/SemaCXX/address-of-temporary.cpp | 40 +- test/SemaCXX/alias-template.cpp | 27 + test/SemaCXX/altivec.cpp | 7 +- test/SemaCXX/anonymous-union-cxx11.cpp | 13 + test/SemaCXX/array-bound-merge.cpp | 2 + test/SemaCXX/arrow-operator.cpp | 28 + test/SemaCXX/attr-deprecated.cpp | 42 +- test/SemaCXX/attr-visibility.cpp | 20 + test/SemaCXX/bool.cpp | 2 +- test/SemaCXX/condition.cpp | 2 +- test/SemaCXX/conditional-expr.cpp | 26 +- test/SemaCXX/constant-expression-cxx11.cpp | 130 +- test/SemaCXX/constant-expression.cpp | 9 +- test/SemaCXX/constexpr-many-arguments.cpp | 42 + test/SemaCXX/constructor-initializer.cpp | 13 +- test/SemaCXX/conversion-function.cpp | 11 + test/SemaCXX/conversion.cpp | 60 +- test/SemaCXX/crashes.cpp | 32 + test/SemaCXX/cxx0x-cursory-default-delete.cpp | 21 +- test/SemaCXX/cxx0x-defaulted-functions.cpp | 110 +- test/SemaCXX/cxx0x-initializer-aggregates.cpp | 29 + test/SemaCXX/cxx0x-initializer-constructor.cpp | 23 + .../cxx0x-initializer-stdinitializerlist.cpp | 12 + test/SemaCXX/cxx98-compat-pedantic.cpp | 2 +- test/SemaCXX/cxx98-compat.cpp | 61 +- test/SemaCXX/dcl_ambig_res.cpp | 6 +- test/SemaCXX/dcl_init_aggr.cpp | 2 +- test/SemaCXX/decl-expr-ambiguity.cpp | 33 +- test/SemaCXX/default1.cpp | 9 +- test/SemaCXX/deleted-function.cpp | 10 + test/SemaCXX/deleted-operator.cpp | 4 +- test/SemaCXX/elaborated-type-specifier.cpp | 7 +- test/SemaCXX/enum-scoped.cpp | 7 + test/SemaCXX/expressions.cpp | 2 +- test/SemaCXX/format-strings-0x.cpp | 12 + test/SemaCXX/function-extern-c.cpp | 2 + test/SemaCXX/function-redecl.cpp | 28 +- test/SemaCXX/implicit-exception-spec.cpp | 17 +- test/SemaCXX/invalid-member-expr.cpp | 31 + test/SemaCXX/lambda-expressions.cpp | 141 +- test/SemaCXX/literal-operators.cpp | 1 + test/SemaCXX/long-virtual-inheritance-chain.cpp | 53 + test/SemaCXX/member-expr.cpp | 10 + test/SemaCXX/member-init.cpp | 4 +- test/SemaCXX/member-operator-expr.cpp | 5 + test/SemaCXX/microsoft-cxx0x.cpp | 14 + test/SemaCXX/neon-vector-types.cpp | 19 +- test/SemaCXX/nested-name-spec.cpp | 14 +- test/SemaCXX/no-rtti.cpp | 10 + test/SemaCXX/nullptr.cpp | 4 +- test/SemaCXX/offsetof-0x.cpp | 20 + test/SemaCXX/overload-call.cpp | 34 +- test/SemaCXX/overload-member-call.cpp | 13 +- test/SemaCXX/overloaded-builtin-operators.cpp | 33 +- test/SemaCXX/pr13353.cpp | 13 + test/SemaCXX/pr13394-crash-on-invalid.cpp | 16 + test/SemaCXX/printf-block.cpp | 18 + test/SemaCXX/printf-cstr.cpp | 53 + test/SemaCXX/qualified-id-lookup.cpp | 5 +- test/SemaCXX/reinterpret-cast.cpp | 2 +- test/SemaCXX/static-assert.cpp | 14 + test/SemaCXX/switch-implicit-fallthrough-cxx98.cpp | 119 + .../switch-implicit-fallthrough-per-method.cpp | 51 + test/SemaCXX/switch-implicit-fallthrough.cpp | 197 + test/SemaCXX/type-traits.cpp | 35 +- test/SemaCXX/typo-correction.cpp | 44 + test/SemaCXX/uninit-variables.cpp | 6 + test/SemaCXX/uninitialized.cpp | 165 +- test/SemaCXX/unknown-type-name.cpp | 56 + test/SemaCXX/unused.cpp | 48 +- test/SemaCXX/user-defined-conversions.cpp | 2 +- test/SemaCXX/virtuals.cpp | 2 +- test/SemaCXX/warn-deprecated-header.cpp | 3 +- test/SemaCXX/warn-literal-conversion.cpp | 28 +- test/SemaCXX/warn-loop-analysis.cpp | 154 + test/SemaCXX/warn-memset-bad-sizeof.cpp | 24 +- test/SemaCXX/warn-static-function-inheader.cpp | 12 + test/SemaCXX/warn-static-function-inheader.h | 3 + test/SemaCXX/warn-thread-safety-analysis.cpp | 1008 ++++- test/SemaCXX/warn-thread-safety-parsing.cpp | 857 ++-- test/SemaCXX/warn-unique-enum.cpp | 27 + test/SemaCXX/warn-unused-private-field.cpp | 246 ++ test/SemaCXX/warn-unused-value.cpp | 2 +- test/SemaObjC/arc-bridged-cast.m | 26 +- test/SemaObjC/arc-cf.m | 10 +- test/SemaObjC/arc-dict-bridged-cast.m | 46 + test/SemaObjC/arc-no-runtime.m | 2 +- test/SemaObjC/arc-property-lifetime.m | 5 + test/SemaObjC/arc-property.m | 10 +- test/SemaObjC/arc-retain-block-property.m | 30 - test/SemaObjC/arc-unbridged-cast.m | 8 +- test/SemaObjC/arc.m | 23 +- test/SemaObjC/assign-rvalue-message.m | 2 +- test/SemaObjC/at-defs.m | 2 +- test/SemaObjC/attr-availability.m | 16 +- test/SemaObjC/attr-deprecated.m | 27 +- test/SemaObjC/blocks.m | 121 + test/SemaObjC/boxing-illegal-types.m | 58 + test/SemaObjC/category-1.m | 9 + test/SemaObjC/class-bitfield.m | 2 +- test/SemaObjC/cocoa-api-usage.m | 8 +- test/SemaObjC/cocoa-api-usage.m.fixed | 8 +- test/SemaObjC/conflicting-ivar-test-1.m | 2 +- test/SemaObjC/continuation-class-err.m | 10 +- test/SemaObjC/continuation-class-property.m | 4 +- test/SemaObjC/dealloc.m | 25 + test/SemaObjC/default-synthesize-1.m | 30 +- test/SemaObjC/default-synthesize-2.m | 19 +- test/SemaObjC/delay-parsing-cfunctions.m | 43 + test/SemaObjC/direct-synthesized-ivar-access.m | 2 +- test/SemaObjC/duplicate-property-class-extension.m | 2 +- test/SemaObjC/error-implicit-property.m | 2 +- test/SemaObjC/format-strings-objc.m | 57 +- test/SemaObjC/format-strings-system.h | 10 + .../getter-setter-defined-in-category-of-parent.m | 26 + test/SemaObjC/iboutlet.m | 23 + test/SemaObjC/id-isa-ref.m | 35 - test/SemaObjC/id.m | 12 +- test/SemaObjC/interface-1.m | 2 +- test/SemaObjC/interface-layout.m | 2 +- test/SemaObjC/ivar-in-class-extension-error.m | 2 +- test/SemaObjC/method-bad-param.m | 2 +- test/SemaObjC/method-prototype-scope.m | 4 +- test/SemaObjC/mismatched-undefined-method.m | 13 + test/SemaObjC/narrow-property-type-in-cont-class.m | 2 +- test/SemaObjC/no-ivar-in-interface-block.m | 32 + test/SemaObjC/nowarn-superclass-method-mismatch.m | 20 + test/SemaObjC/nsobject-attribute.m | 12 +- test/SemaObjC/objc-container-subscripting-2.m | 4 +- test/SemaObjC/objc-container-subscripting-3.m | 2 +- test/SemaObjC/objc-container-subscripting.m | 8 +- test/SemaObjC/objc-cstyle-args-in-methods.m | 2 +- test/SemaObjC/objc-dictionary-literal.m | 2 +- test/SemaObjC/objc-literal-comparison.m | 96 + test/SemaObjC/objc-literal-nsnumber.m | 4 + test/SemaObjC/objc-literal-sig.m | 17 +- test/SemaObjC/property-10.m | 2 +- test/SemaObjC/property-12.m | 37 +- test/SemaObjC/property-impl-misuse.m | 17 +- test/SemaObjC/property-ivar-mismatch.m | 12 + test/SemaObjC/property-typecheck-1.m | 8 +- test/SemaObjC/property-user-setter.m | 52 + test/SemaObjC/property.m | 4 +- test/SemaObjC/protocol-attribute.m | 2 +- test/SemaObjC/protocols.m | 2 +- test/SemaObjC/provisional-ivar-lookup.m | 2 +- test/SemaObjC/related-result-type-inference.m | 8 +- test/SemaObjC/sizeof-interface.m | 18 +- test/SemaObjC/special-dep-unavail-warning.m | 2 +- test/SemaObjC/tentative-property-decl.m | 47 + test/SemaObjC/unused.m | 2 + test/SemaObjC/warn-deprecated-implementations.m | 2 +- test/SemaObjC/warn-direct-ivar-access.m | 56 + test/SemaObjC/warn-isa-ref.m | 83 + test/SemaObjC/warn-protocol-method-deprecated.m | 32 + test/SemaObjC/warn-retain-block-property.m | 32 + test/SemaObjC/weak-receiver-warn.m | 65 +- test/SemaObjCXX/arc-0x.mm | 32 +- test/SemaObjCXX/arc-templates.mm | 17 + test/SemaObjCXX/arc-type-traits.mm | 126 +- test/SemaObjCXX/arc-unbridged-cast.mm | 8 +- test/SemaObjCXX/boxing-illegal-types.mm | 58 + test/SemaObjCXX/crash.mm | 23 + test/SemaObjCXX/delay-parsing-cfunctions.mm | 48 + test/SemaObjCXX/delay-parsing-cplusfuncs.mm | 52 + test/SemaObjCXX/delay-parsing-func-tryblock.mm | 66 + test/SemaObjCXX/exceptions-fragile.mm | 2 +- test/SemaObjCXX/foreach.mm | 61 + test/SemaObjCXX/fragile-abi-object-assign.m | 2 +- test/SemaObjCXX/instantiate-stmt.mm | 8 +- test/SemaObjCXX/message.mm | 2 +- test/SemaObjCXX/objc-container-subscripting.mm | 4 +- test/SemaObjCXX/property-synthesis-error.mm | 13 +- test/SemaObjCXX/protocol-lookup.mm | 2 +- test/SemaObjCXX/warn-missing-super.mm | 19 + test/SemaOpenCL/storageclass.cl | 12 + test/SemaOpenCL/warn-missing-prototypes.cl | 6 + test/SemaTemplate/alias-templates.cpp | 76 +- test/SemaTemplate/class-template-decl.cpp | 42 + test/SemaTemplate/delegating-constructors.cpp | 18 + test/SemaTemplate/dependent-base-classes.cpp | 3 +- test/SemaTemplate/explicit-instantiation.cpp | 4 +- test/SemaTemplate/friend-template.cpp | 59 + .../instantiate-exception-spec-cxx11.cpp | 14 + test/SemaTemplate/instantiate-expr-1.cpp | 2 +- test/SemaTemplate/instantiate-init.cpp | 15 +- test/SemaTemplate/instantiate-member-class.cpp | 7 +- test/SemaTemplate/instantiate-method.cpp | 7 + test/SemaTemplate/instantiate-objc-1.mm | 21 + test/SemaTemplate/instantiation-backtrace.cpp | 19 + test/SemaTemplate/instantiation-depth-defarg.cpp | 36 + test/SemaTemplate/instantiation-depth-subst-2.cpp | 9 + test/SemaTemplate/instantiation-depth-subst.cpp | 9 + test/SemaTemplate/instantiation-depth.cpp | 20 +- test/SemaTemplate/member-template-access-expr.cpp | 2 +- .../ms-function-specialization-class-scope.cpp | 21 + .../ms-lookup-template-base-classes.cpp | 29 + test/SemaTemplate/overload-candidates.cpp | 26 +- test/SemaTemplate/recovery-crash.cpp | 3 +- test/SemaTemplate/typename-specifier.cpp | 41 +- test/Tooling/Inputs/lit.local.cfg | 1 + test/Tooling/Inputs/pch-fail.h | 0 test/Tooling/Inputs/pch.cpp | 0 test/Tooling/Inputs/pch.h | 0 .../auto-detect-from-source-parent-of-cwd.cpp | 10 + test/Tooling/auto-detect-from-source-parent.cpp | 10 + test/Tooling/auto-detect-from-source.cpp | 10 + test/Tooling/clang-check-args.cpp | 7 +- test/Tooling/clang-check-ast-dump.cpp | 35 + test/Tooling/clang-check-autodetect-dir.cpp | 11 + test/Tooling/clang-check-builtin-headers.cpp | 15 + test/Tooling/clang-check-chdir.cpp | 17 + test/Tooling/clang-check-pwd.cpp | 8 +- test/Tooling/clang-check.cpp | 9 +- test/Tooling/multi-jobs.cpp | 7 + test/Tooling/pch.cpp | 17 + test/lit.cfg | 8 + tools/CMakeLists.txt | 9 + tools/Makefile | 6 +- tools/arcmt-test/CMakeLists.txt | 16 +- tools/arcmt-test/Makefile | 6 +- tools/c-arcmt-test/CMakeLists.txt | 6 +- tools/c-arcmt-test/Makefile | 7 +- tools/c-index-test/CMakeLists.txt | 13 +- tools/c-index-test/Makefile | 17 +- tools/c-index-test/c-index-test.c | 606 ++- tools/clang-check/CMakeLists.txt | 15 +- tools/clang-check/ClangCheck.cpp | 104 +- tools/clang-check/Makefile | 4 +- tools/diag-build/diag-build.sh | 115 + tools/diagtool/CMakeLists.txt | 28 +- tools/diagtool/DiagnosticNames.cpp | 78 + tools/diagtool/DiagnosticNames.h | 128 + tools/diagtool/ListWarnings.cpp | 37 +- tools/diagtool/Makefile | 10 +- tools/diagtool/ShowEnabledWarnings.cpp | 148 + tools/diagtool/TreeView.cpp | 135 + tools/diagtool/diagtool_main.cpp | 2 +- tools/driver/CMakeLists.txt | 40 +- tools/driver/cc1_main.cpp | 4 +- tools/driver/cc1as_main.cpp | 4 +- tools/driver/driver.cpp | 16 +- tools/libclang/CIndex.cpp | 221 +- tools/libclang/CIndexCodeCompletion.cpp | 25 +- tools/libclang/CIndexDiagnostic.cpp | 30 +- tools/libclang/CIndexUSRs.cpp | 2 +- tools/libclang/CMakeLists.txt | 76 +- tools/libclang/CXComment.cpp | 1230 ++++++ tools/libclang/CXComment.h | 47 + tools/libclang/CXCompilationDatabase.cpp | 129 + tools/libclang/CXCursor.cpp | 244 +- tools/libclang/CXCursor.h | 11 +- tools/libclang/CXStoredDiagnostic.cpp | 7 +- tools/libclang/CXTranslationUnit.h | 1 + tools/libclang/CXType.cpp | 18 +- tools/libclang/IndexBody.cpp | 16 +- tools/libclang/IndexDecl.cpp | 15 +- tools/libclang/IndexTypeSourceInfo.cpp | 4 +- tools/libclang/Indexing.cpp | 10 +- tools/libclang/IndexingContext.h | 6 +- tools/libclang/Makefile | 7 +- tools/libclang/RecursiveASTVisitor.h | 2185 ++++++++++ tools/libclang/libclang.exports | 50 + tools/scan-build/ccc-analyzer | 21 +- tools/scan-build/scan-build | 213 +- tools/scan-build/scan-build.1 | 348 ++ tools/scan-build/set-xcode-analyzer | 6 +- unittests/AST/CMakeLists.txt | 8 + unittests/AST/CommentLexer.cpp | 1636 +++++++ unittests/AST/CommentParser.cpp | 1383 ++++++ unittests/AST/Makefile | 15 + unittests/ASTMatchers/ASTMatchersTest.cpp | 2312 ++++++++++ unittests/ASTMatchers/ASTMatchersTest.h | 128 + unittests/ASTMatchers/CMakeLists.txt | 12 + unittests/ASTMatchers/Makefile | 19 + unittests/Basic/CMakeLists.txt | 9 + unittests/Basic/SourceManagerTest.cpp | 48 + unittests/CMakeLists.txt | 80 +- unittests/Frontend/CMakeLists.txt | 13 + unittests/Frontend/FrontendActionTest.cpp | 1 + unittests/Frontend/Makefile | 3 +- unittests/Lex/CMakeLists.txt | 8 + unittests/Makefile | 2 +- unittests/Tooling/CMakeLists.txt | 22 + unittests/Tooling/CommentHandlerTest.cpp | 221 + unittests/Tooling/CompilationDatabaseTest.cpp | 58 + unittests/Tooling/Makefile | 7 +- unittests/Tooling/RecursiveASTVisitorTest.cpp | 388 ++ unittests/Tooling/RefactoringCallbacksTest.cpp | 100 + unittests/Tooling/RefactoringTest.cpp | 305 ++ unittests/Tooling/RewriterTest.cpp | 37 + unittests/Tooling/RewriterTestContext.h | 125 + unittests/Tooling/TestVisitor.h | 144 + unittests/Tooling/ToolingTest.cpp | 25 +- utils/TableGen/ClangASTNodesEmitter.cpp | 61 +- utils/TableGen/ClangASTNodesEmitter.h | 84 - utils/TableGen/ClangAttrEmitter.cpp | 175 +- utils/TableGen/ClangAttrEmitter.h | 153 - utils/TableGen/ClangDiagnosticsEmitter.cpp | 294 +- utils/TableGen/ClangDiagnosticsEmitter.h | 54 - utils/TableGen/ClangSACheckersEmitter.cpp | 8 +- utils/TableGen/ClangSACheckersEmitter.h | 31 - utils/TableGen/NeonEmitter.cpp | 233 +- utils/TableGen/NeonEmitter.h | 210 - utils/TableGen/OptParserEmitter.cpp | 13 +- utils/TableGen/OptParserEmitter.h | 34 - utils/TableGen/TableGen.cpp | 58 +- utils/TableGen/TableGenBackends.h | 56 + utils/analyzer/CmpRuns.py | 135 +- utils/analyzer/SATestAdd.py | 2 +- utils/analyzer/SATestBuild.py | 33 +- utils/analyzer/SumTimerInfo.py | 75 + utils/analyzer/reducer.pl | 65 + utils/clang-completion-mode.el | 40 +- utils/clangVisualizers.txt | 313 +- www/analyzer/annotations.html | 3 +- www/analyzer/available_checks.html | 48 + www/analyzer/content.css | 1 + www/analyzer/faq.html | 120 + www/analyzer/images/example_custom_assert.png | Bin 0 -> 23686 bytes www/analyzer/images/example_null_pointer.png | Bin 0 -> 23580 bytes www/analyzer/images/example_use_assert.png | Bin 0 -> 25513 bytes www/analyzer/installation.html | 2 +- www/analyzer/latest_checker.html.incl | 2 +- www/analyzer/menu.html.incl | 5 +- www/analyzer/release_notes.html | 38 +- www/builtins.py | 5 +- www/comparison.html | 2 - www/content.css | 3 + www/cxx_status.html | 28 +- www/diagnostics.html | 33 + www/features.html | 16 +- www/get_started.html | 33 +- www/menu.html.incl | 1 + 1881 files changed, 112376 insertions(+), 30866 deletions(-) create mode 100644 bindings/python/clang/enumerations.py create mode 100644 bindings/python/tests/cindex/INPUTS/compile_commands.json create mode 100644 bindings/python/tests/cindex/test_cdb.py create mode 100644 bindings/python/tests/cindex/test_token_kind.py create mode 100644 bindings/python/tests/cindex/test_tokens.py create mode 100644 bindings/xml/comment-xml-schema.rng create mode 100644 docs/ClangPlugins.html create mode 100644 docs/ClangTools.html create mode 100644 docs/HowToSetupToolingForLLVM.html create mode 100644 docs/IntroductionToTheClangAST.html create mode 100644 docs/JSONCompilationDatabase.html create mode 100644 docs/LibTooling.html create mode 100644 docs/RAVFrontendAction.html create mode 100644 docs/ThreadSanitizer.html create mode 100644 docs/Tooling.html create mode 100644 include/clang-c/CXCompilationDatabase.h create mode 100644 include/clang-c/CXString.h create mode 100644 include/clang-c/Platform.h create mode 100644 include/clang/AST/Comment.h create mode 100644 include/clang/AST/CommentBriefParser.h create mode 100644 include/clang/AST/CommentCommandTraits.h create mode 100644 include/clang/AST/CommentDiagnostic.h create mode 100644 include/clang/AST/CommentLexer.h create mode 100644 include/clang/AST/CommentParser.h create mode 100644 include/clang/AST/CommentSema.h create mode 100644 include/clang/AST/CommentVisitor.h create mode 100644 include/clang/AST/RawCommentList.h create mode 100644 include/clang/ASTMatchers/ASTMatchFinder.h create mode 100644 include/clang/ASTMatchers/ASTMatchers.h create mode 100644 include/clang/ASTMatchers/ASTMatchersInternal.h create mode 100644 include/clang/ASTMatchers/ASTMatchersMacros.h create mode 100644 include/clang/Basic/BuiltinsMips.def create mode 100644 include/clang/Basic/BuiltinsNVPTX.def delete mode 100644 include/clang/Basic/BuiltinsPTX.def create mode 100644 include/clang/Basic/CommentNodes.td create mode 100644 include/clang/Basic/DiagnosticCommentKinds.td create mode 100644 include/clang/Basic/ObjCRuntime.h delete mode 100644 include/clang/Driver/ObjCRuntime.h create mode 100644 include/clang/Sema/CodeCompleteOptions.h create mode 100644 include/clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h create mode 100644 include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h delete mode 100644 include/clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h create mode 100644 include/clang/Tooling/ArgumentsAdjusters.h create mode 100644 include/clang/Tooling/CommandLineClangTool.h create mode 100644 include/clang/Tooling/Refactoring.h create mode 100644 include/clang/Tooling/RefactoringCallbacks.h create mode 100644 lib/AST/Comment.cpp create mode 100644 lib/AST/CommentBriefParser.cpp create mode 100644 lib/AST/CommentCommandTraits.cpp create mode 100644 lib/AST/CommentDumper.cpp create mode 100644 lib/AST/CommentLexer.cpp create mode 100644 lib/AST/CommentParser.cpp create mode 100644 lib/AST/CommentSema.cpp create mode 100644 lib/AST/RawCommentList.cpp create mode 100644 lib/ASTMatchers/ASTMatchFinder.cpp create mode 100644 lib/ASTMatchers/ASTMatchersInternal.cpp create mode 100644 lib/ASTMatchers/CMakeLists.txt create mode 100644 lib/ASTMatchers/Makefile create mode 100644 lib/Basic/ConvertUTFWrapper.cpp create mode 100644 lib/Basic/ObjCRuntime.cpp delete mode 100644 lib/Driver/CC1Options.cpp create mode 100644 lib/Headers/ammintrin.h create mode 100644 lib/Headers/fmaintrin.h create mode 100644 lib/Headers/xopintrin.h create mode 100644 lib/Rewrite/InclusionRewriter.cpp create mode 100644 lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp create mode 100644 lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp delete mode 100644 lib/StaticAnalyzer/Checkers/IteratorsChecker.cpp create mode 100644 lib/StaticAnalyzer/Checkers/TraversalChecker.cpp create mode 100644 lib/StaticAnalyzer/Core/APSIntType.cpp create mode 100644 lib/StaticAnalyzer/Core/CallEvent.cpp delete mode 100644 lib/StaticAnalyzer/Core/ObjCMessage.cpp create mode 100644 lib/Tooling/ArgumentsAdjusters.cpp create mode 100644 lib/Tooling/CommandLineClangTool.cpp create mode 100644 lib/Tooling/CustomCompilationDatabase.h create mode 100644 lib/Tooling/Refactoring.cpp create mode 100644 lib/Tooling/RefactoringCallbacks.cpp create mode 100644 test/ARCMT/objcmt-boxing.m create mode 100644 test/ARCMT/objcmt-boxing.m.result create mode 100644 test/ARCMT/objcmt-subscripting-literals-in-arc.m create mode 100644 test/ARCMT/objcmt-subscripting-literals-in-arc.m.result create mode 100644 test/ARCMT/objcmt-subscripting-unavailable.m create mode 100644 test/ARCMT/objcmt-subscripting-unavailable.m.result create mode 100644 test/ARCMT/verify.m create mode 100644 test/Analysis/PR12905.c delete mode 100644 test/Analysis/additive-folding.c create mode 100644 test/Analysis/additive-folding.cpp create mode 100644 test/Analysis/blocks-no-inline.c create mode 100644 test/Analysis/comparison-implicit-casts.cpp create mode 100644 test/Analysis/ctor-inlining.mm create mode 100644 test/Analysis/cxx-for-range-cfg.cpp create mode 100644 test/Analysis/cxx-method-names.cpp create mode 100644 test/Analysis/cxx11-crashes.cpp create mode 100644 test/Analysis/diagnostics/undef-value-callee.h create mode 100644 test/Analysis/diagnostics/undef-value-caller.c create mode 100644 test/Analysis/engine/replay-without-inlining.c create mode 100644 test/Analysis/inline.cpp create mode 100644 test/Analysis/inlining/DynDispatchBifurcate.m create mode 100644 test/Analysis/inlining/InlineObjCClassMethod.m create mode 100644 test/Analysis/inlining/InlineObjCInstanceMethod.h create mode 100644 test/Analysis/inlining/InlineObjCInstanceMethod.m create mode 100644 test/Analysis/inlining/ObjCDynTypePopagation.m create mode 100644 test/Analysis/inlining/ObjCImproperDynamictallyDetectableCast.m create mode 100644 test/Analysis/inlining/RetainCountExamples.m create mode 100644 test/Analysis/inlining/path-notes.c delete mode 100644 test/Analysis/iterators.cpp create mode 100644 test/Analysis/ivars.m create mode 100644 test/Analysis/method-call-path-notes.cpp create mode 100644 test/Analysis/misc-ps-arm.m create mode 100644 test/Analysis/nonnull.m create mode 100644 test/Analysis/objc-boxing.m create mode 100644 test/Analysis/objc-for.m create mode 100644 test/Analysis/objc-subscript.m create mode 100644 test/Analysis/region-store.c create mode 100644 test/Analysis/svalbuilder-logic.c create mode 100644 test/Analysis/templates.cpp create mode 100644 test/Analysis/test-variably-modified-types.c create mode 100644 test/Analysis/traversal-algorithm.mm create mode 100644 test/Analysis/uninit-sometimes.cpp create mode 100644 test/CXX/basic/basic.lookup/basic.lookup.classref/p1-cxx11.cpp create mode 100644 test/CXX/basic/basic.lookup/basic.lookup.classref/p4-cxx11.cpp create mode 100644 test/CXX/class.access/class.friend/p9-cxx0x.cpp create mode 100644 test/CXX/dcl.decl/dcl.fct.def/dcl.fct.def.delete/p4.cpp create mode 100644 test/CXX/dcl.decl/dcl.init/dcl.init.list/p3-0x.cpp create mode 100644 test/CXX/dcl.decl/dcl.meaning/dcl.fct/dcl.fct.def.default/p1.cpp create mode 100644 test/CXX/expr/expr.prim/expr.prim.lambda/blocks-irgen.mm create mode 100644 test/CXX/expr/p10-0x.cpp create mode 100644 test/CXX/special/class.conv/class.conv.ctor/p1.cpp create mode 100644 test/CXX/special/class.copy/p23-cxx11.cpp create mode 100644 test/CXX/temp/temp.names/p3-0x.cpp create mode 100644 test/CodeCompletion/auto.cpp create mode 100644 test/CodeCompletion/documentation.cpp create mode 100644 test/CodeCompletion/objc-expr.m delete mode 100644 test/CodeGen/2002-05-24-Alloca.c create mode 100644 test/CodeGen/alloca.c create mode 100644 test/CodeGen/attr-coldhot.c create mode 100644 test/CodeGen/bounds-checking.c create mode 100644 test/CodeGen/branch-target-layout.c create mode 100644 test/CodeGen/builtins-mips-args.c create mode 100644 test/CodeGen/builtins-mips.c create mode 100644 test/CodeGen/builtins-nvptx.c delete mode 100644 test/CodeGen/builtins-ptx.c create mode 100644 test/CodeGen/debug-info-gline-tables-only.c create mode 100644 test/CodeGen/debug-info-gline-tables-only2.c create mode 100644 test/CodeGen/debug-info-vla.c create mode 100644 test/CodeGen/fma-builtins.c create mode 100644 test/CodeGen/forceinline.c create mode 100644 test/CodeGen/fp-contract.c create mode 100644 test/CodeGen/mips-byval-arg.c create mode 100644 test/CodeGen/mips-vector-arg.c create mode 100644 test/CodeGen/mips-vector-return.c create mode 100644 test/CodeGen/ms-inline-asm.c create mode 100644 test/CodeGen/nobuiltin.c create mode 100644 test/CodeGen/nvptx-cc.c create mode 100644 test/CodeGen/nvptx-inlineasm.c create mode 100644 test/CodeGen/pclmul-builtins.c create mode 100644 test/CodeGen/pr13168.c delete mode 100644 test/CodeGen/ptx-cc.c create mode 100644 test/CodeGen/rdrand-builtins.c create mode 100644 test/CodeGen/regparm-struct.c create mode 100644 test/CodeGen/sse4a-builtins.c create mode 100644 test/CodeGen/tls-model.c create mode 100644 test/CodeGen/vector-alignment.c create mode 100644 test/CodeGen/xop-builtins.c create mode 100644 test/CodeGenCUDA/address-spaces.cu create mode 100644 test/CodeGenCXX/cxx0x-initializer-constructors.cpp create mode 100644 test/CodeGenCXX/cxx11-initializer-aggregate.cpp create mode 100644 test/CodeGenCXX/cxx11-vtable-key-function.cpp create mode 100644 test/CodeGenCXX/debug-info-determinism.cpp create mode 100644 test/CodeGenCXX/debug-info-enum-class.cpp create mode 100644 test/CodeGenCXX/debug-info-flex-member.cpp create mode 100644 test/CodeGenCXX/debug-info-gline-tables-only.cpp create mode 100644 test/CodeGenCXX/debug-info-globalinit.cpp create mode 100644 test/CodeGenCXX/debug-info-rvalue-ref.cpp create mode 100644 test/CodeGenCXX/debug-info-template-array.cpp create mode 100644 test/CodeGenCXX/debug-info-template-quals.cpp create mode 100644 test/CodeGenCXX/debug-info-union.cpp create mode 100644 test/CodeGenCXX/debug-info-user-def.cpp create mode 100644 test/CodeGenCXX/destructor-exception-spec.cpp create mode 100644 test/CodeGenCXX/global-block-literal-helpers.cpp create mode 100644 test/CodeGenCXX/mangle-ms-abi-examples.cpp create mode 100644 test/CodeGenCXX/mangle-ms-back-references-pr13207.cpp create mode 100644 test/CodeGenCXX/mangle-ms-back-references.cpp create mode 100644 test/CodeGenCXX/mangle-ms-cxx11.cpp create mode 100644 test/CodeGenCXX/mangle-ms-return-qualifiers.cpp create mode 100644 test/CodeGenCXX/mangle-ms-templates.cpp create mode 100644 test/CodeGenCXX/member-data-pointers.cpp delete mode 100644 test/CodeGenCXX/member-init-ctor.cpp delete mode 100644 test/CodeGenCXX/member-pointer-type-convert.cpp create mode 100644 test/CodeGenCXX/microsoft-abi-array-cookies.cpp create mode 100644 test/CodeGenCXX/microsoft-abi-constructors.cpp create mode 100644 test/CodeGenCXX/microsoft-abi-methods.cpp create mode 100644 test/CodeGenCXX/microsoft-abi-static-initializers.cpp create mode 100644 test/CodeGenCXX/ms_wide_predefined_expr.cpp create mode 100644 test/CodeGenCXX/pr13396.cpp create mode 100644 test/CodeGenCXX/throw-expression-cleanup.cpp delete mode 100644 test/CodeGenCXX/virt-call-offsets.cpp create mode 100644 test/CodeGenObjC/boxing.m create mode 100644 test/CodeGenObjC/encode-test-6.m create mode 100644 test/CodeGenObjC/getter-property-mismatch.m create mode 100644 test/CodeGenObjC/getter-property-type-mismatch.m create mode 100644 test/CodeGenObjC/layout-bitfield-crash.m create mode 100644 test/CodeGenObjC/objfw.m create mode 100644 test/CodeGenOpenCL/kernel-arg-info.cl create mode 100644 test/CodeGenOpenCL/kernel-attributes.cl create mode 100644 test/Driver/Inputs/basic_android_tree/usr/lib/crtbegin_dynamic.o create mode 100644 test/Driver/Inputs/basic_android_tree/usr/lib/crtbegin_so.o create mode 100644 test/Driver/Inputs/basic_android_tree/usr/lib/crtbegin_static.o create mode 100644 test/Driver/Inputs/basic_android_tree/usr/lib/crtend_android.o create mode 100644 test/Driver/Inputs/basic_android_tree/usr/lib/crtend_so.o create mode 100644 test/Driver/Inputs/debian_multiarch_tree/lib/mips-linux-gnu/.keep create mode 100644 test/Driver/Inputs/debian_multiarch_tree/lib/mipsel-linux-gnu/.keep create mode 100644 test/Driver/Inputs/debian_multiarch_tree/usr/include/c++/4.5/mips-linux-gnu/.keep create mode 100644 test/Driver/Inputs/debian_multiarch_tree/usr/include/c++/4.5/mipsel-linux-gnu/.keep create mode 100644 test/Driver/Inputs/debian_multiarch_tree/usr/include/mips-linux-gnu/.keep create mode 100644 test/Driver/Inputs/debian_multiarch_tree/usr/include/mipsel-linux-gnu/.keep create mode 100644 test/Driver/Inputs/debian_multiarch_tree/usr/lib/gcc/mips-linux-gnu/4.5/64/crtbegin.o create mode 100644 test/Driver/Inputs/debian_multiarch_tree/usr/lib/gcc/mips-linux-gnu/4.5/crtbegin.o create mode 100644 test/Driver/Inputs/debian_multiarch_tree/usr/lib/gcc/mips-linux-gnu/4.5/n32/crtbegin.o create mode 100644 test/Driver/Inputs/debian_multiarch_tree/usr/lib/gcc/mipsel-linux-gnu/4.5/64/crtbegin.o create mode 100644 test/Driver/Inputs/debian_multiarch_tree/usr/lib/gcc/mipsel-linux-gnu/4.5/crtbegin.o create mode 100644 test/Driver/Inputs/debian_multiarch_tree/usr/lib/gcc/mipsel-linux-gnu/4.5/n32/crtbegin.o create mode 100644 test/Driver/Inputs/debian_multiarch_tree/usr/lib/mips-linux-gnu/.keep create mode 100644 test/Driver/Inputs/debian_multiarch_tree/usr/lib/mipsel-linux-gnu/.keep create mode 100644 test/Driver/Inputs/montavista_i686_tree/usr/lib/gcc/i686-montavista-linux/4.2.0/crtbegin.o create mode 100644 test/Driver/Inputs/montavista_i686_tree/usr/lib/gcc/i686-montavista-linux/4.2.0/libgcc.a create mode 100644 test/Driver/Inputs/ubuntu_12.04_LTS_multiarch_tree/lib/.keep create mode 100644 test/Driver/Inputs/ubuntu_12.04_LTS_multiarch_tree/lib/arm-linux-gnueabi/.keep create mode 100644 test/Driver/Inputs/ubuntu_12.04_LTS_multiarch_tree/lib/arm-linux-gnueabihf/.keep create mode 100644 test/Driver/Inputs/ubuntu_12.04_LTS_multiarch_tree/usr/include/.keep create mode 100644 test/Driver/Inputs/ubuntu_12.04_LTS_multiarch_tree/usr/include/arm-linux-gnueabi/.keep create mode 100644 test/Driver/Inputs/ubuntu_12.04_LTS_multiarch_tree/usr/include/arm-linux-gnueabihf/.keep create mode 100644 test/Driver/Inputs/ubuntu_12.04_LTS_multiarch_tree/usr/lib/.keep create mode 100644 test/Driver/Inputs/ubuntu_12.04_LTS_multiarch_tree/usr/lib/arm-linux-gnueabi/crt1.o create mode 100644 test/Driver/Inputs/ubuntu_12.04_LTS_multiarch_tree/usr/lib/arm-linux-gnueabi/crti.o create mode 100644 test/Driver/Inputs/ubuntu_12.04_LTS_multiarch_tree/usr/lib/arm-linux-gnueabi/crtn.o create mode 100644 test/Driver/Inputs/ubuntu_12.04_LTS_multiarch_tree/usr/lib/arm-linux-gnueabihf/crt1.o create mode 100644 test/Driver/Inputs/ubuntu_12.04_LTS_multiarch_tree/usr/lib/arm-linux-gnueabihf/crti.o create mode 100644 test/Driver/Inputs/ubuntu_12.04_LTS_multiarch_tree/usr/lib/arm-linux-gnueabihf/crtn.o create mode 100644 test/Driver/Inputs/ubuntu_12.04_LTS_multiarch_tree/usr/lib/gcc/arm-linux-gnueabi/4.6.1/crtbegin.o create mode 100644 test/Driver/Inputs/ubuntu_12.04_LTS_multiarch_tree/usr/lib/gcc/arm-linux-gnueabi/4.6.1/crtend.o create mode 100644 test/Driver/Inputs/ubuntu_12.04_LTS_multiarch_tree/usr/lib/gcc/arm-linux-gnueabihf/4.6.3/crtbegin.o create mode 100644 test/Driver/Inputs/ubuntu_12.04_LTS_multiarch_tree/usr/lib/gcc/arm-linux-gnueabihf/4.6.3/crtend.o create mode 100644 test/Driver/asan-ld.c create mode 100644 test/Driver/bounds-checking.c create mode 100644 test/Driver/ccc-as-cpp.c create mode 100644 test/Driver/clang_f_opts.h create mode 100644 test/Driver/constructors.c create mode 100644 test/Driver/crash-report.c create mode 100644 test/Driver/debug-unsupported.c create mode 100644 test/Driver/fpack-struct.c create mode 100644 test/Driver/mips-features.c create mode 100644 test/Driver/montavista-gcc-toolchain.c create mode 100644 test/Driver/msvc_forward.c create mode 100644 test/Driver/nodefaultlib.c create mode 100644 test/Driver/target-triple-deployment.c create mode 100644 test/Driver/warning-options.cpp create mode 100644 test/Driver/warning-options_pedantic.cpp create mode 100644 test/FixIt/fixit-autoreleasepool.m create mode 100644 test/FixIt/fixit-include.c create mode 100644 test/FixIt/fixit-include.h create mode 100644 test/FixIt/fixit-interface-as-param.m create mode 100644 test/FixIt/fixit-objc-message-comma-separator.m create mode 100644 test/FixIt/fixit-unicode.c create mode 100644 test/FixIt/format-no-fixit.m create mode 100644 test/FixIt/format.m create mode 100644 test/FixIt/messages.cpp create mode 100644 test/Frontend/Inputs/SystemHeaderPrefix/libs/boost/all.h create mode 100644 test/Frontend/Inputs/SystemHeaderPrefix/libs/boost/warn.h create mode 100644 test/Frontend/Inputs/SystemHeaderPrefix/libs/mylib/all.h create mode 100644 test/Frontend/Inputs/SystemHeaderPrefix/libs/mylib/warn.h create mode 100644 test/Frontend/Inputs/SystemHeaderPrefix/src/all.h create mode 100644 test/Frontend/Inputs/SystemHeaderPrefix/src/warn.h create mode 100644 test/Frontend/Inputs/rewrite-includes1.h create mode 100644 test/Frontend/Inputs/rewrite-includes2.h create mode 100644 test/Frontend/Inputs/rewrite-includes3.h create mode 100644 test/Frontend/Inputs/rewrite-includes4.h create mode 100644 test/Frontend/Inputs/rewrite-includes5.h create mode 100644 test/Frontend/Inputs/rewrite-includes6.h create mode 100644 test/Frontend/Inputs/rewrite-includes7.h create mode 100644 test/Frontend/rewrite-includes-missing.c create mode 100644 test/Frontend/rewrite-includes.c create mode 100644 test/Frontend/system-header-prefix.c create mode 100644 test/Frontend/verify-directive.h create mode 100644 test/Frontend/verify-fatal.c create mode 100644 test/Frontend/verify.c create mode 100644 test/Frontend/verify2.c create mode 100644 test/Frontend/verify2.h create mode 100644 test/Headers/ms-null-ms-header-vs-stddef.cpp create mode 100644 test/Index/Inputs/CommentXML/invalid-function-01.xml create mode 100644 test/Index/Inputs/CommentXML/invalid-function-02.xml create mode 100644 test/Index/Inputs/CommentXML/invalid-function-03.xml create mode 100644 test/Index/Inputs/CommentXML/invalid-function-04.xml create mode 100644 test/Index/Inputs/CommentXML/invalid-function-05.xml create mode 100644 test/Index/Inputs/CommentXML/invalid-function-06.xml create mode 100644 test/Index/Inputs/CommentXML/invalid-function-07.xml create mode 100644 test/Index/Inputs/CommentXML/invalid-function-08.xml create mode 100644 test/Index/Inputs/CommentXML/invalid-function-09.xml create mode 100644 test/Index/Inputs/CommentXML/invalid-function-10.xml create mode 100644 test/Index/Inputs/CommentXML/invalid-function-11.xml create mode 100644 test/Index/Inputs/CommentXML/invalid-function-12.xml create mode 100644 test/Index/Inputs/CommentXML/valid-class-01.xml create mode 100644 test/Index/Inputs/CommentXML/valid-class-02.xml create mode 100644 test/Index/Inputs/CommentXML/valid-class-03.xml create mode 100644 test/Index/Inputs/CommentXML/valid-class-04.xml create mode 100644 test/Index/Inputs/CommentXML/valid-enum-01.xml create mode 100644 test/Index/Inputs/CommentXML/valid-function-01.xml create mode 100644 test/Index/Inputs/CommentXML/valid-function-02.xml create mode 100644 test/Index/Inputs/CommentXML/valid-function-03.xml create mode 100644 test/Index/Inputs/CommentXML/valid-function-04.xml create mode 100644 test/Index/Inputs/CommentXML/valid-function-05.xml create mode 100644 test/Index/Inputs/CommentXML/valid-function-06.xml create mode 100644 test/Index/Inputs/CommentXML/valid-function-07.xml create mode 100644 test/Index/Inputs/CommentXML/valid-function-08.xml create mode 100644 test/Index/Inputs/CommentXML/valid-function-09.xml create mode 100644 test/Index/Inputs/CommentXML/valid-function-10.xml create mode 100644 test/Index/Inputs/CommentXML/valid-namespace-01.xml create mode 100644 test/Index/Inputs/CommentXML/valid-other-01.xml create mode 100644 test/Index/Inputs/CommentXML/valid-typedef-01.xml create mode 100644 test/Index/Inputs/CommentXML/valid-typedef-02.xml create mode 100644 test/Index/Inputs/CommentXML/valid-variable-01.xml create mode 100644 test/Index/Inputs/annotate-comments-preprocessor.h create mode 100644 test/Index/annotate-comments-preprocessor.c create mode 100644 test/Index/annotate-comments-unterminated.c create mode 100644 test/Index/annotate-comments.cpp create mode 100644 test/Index/availability.c create mode 100644 test/Index/boxed-exprs.h create mode 100644 test/Index/boxed-exprs.m create mode 100644 test/Index/comment-xml-schema.c create mode 100644 test/Index/compile_commands.json create mode 100644 test/Index/complete-documentation.cpp create mode 100644 test/Index/complete-lambdas.mm create mode 100644 test/Index/create-tu-fail.c create mode 100644 test/Index/cursor-dynamic-call.mm create mode 100644 test/Index/index-kernel-invocation.cpp create mode 100644 test/Index/index-many-call-ops.cpp create mode 100644 test/Index/index-refs.m create mode 100644 test/Lexer/wchar-signedness.c create mode 100644 test/Misc/ast-dump-wchar.cpp create mode 100644 test/Misc/diag-template-diffing-color.cpp create mode 100644 test/Misc/diag-template-diffing.cpp create mode 100644 test/Misc/diag-trailing-null-bytes.cpp create mode 100644 test/Misc/serialized-diags-frontend.c create mode 100644 test/Misc/warning-flags-enabled.c create mode 100644 test/Misc/warning-flags-tree.c delete mode 100644 test/Misc/wnull-character.cpp create mode 100644 test/Modules/Inputs/import-decl.h create mode 100644 test/Modules/import-decl.cpp create mode 100644 test/PCH/Inputs/__va_list_tag.h create mode 100644 test/PCH/__va_list_tag.c create mode 100644 test/PCH/badpch-dir.h.gch/.keep create mode 100644 test/PCH/badpch-empty.h.gch create mode 100644 test/PCH/badpch.c create mode 100644 test/PCH/chain-staticvar-instantiation.cpp create mode 100644 test/PCH/empty-with-headers.c create mode 100644 test/PCH/format-strings.c create mode 100644 test/PCH/pch__VA_ARGS__.c create mode 100644 test/PCH/pch__VA_ARGS__.h create mode 100644 test/PCH/remap-file-from-pch.cpp create mode 100644 test/PCH/remap-file-from-pch.cpp.h create mode 100644 test/PCH/remap-file-from-pch.cpp.remap.h create mode 100644 test/Parser/completely-empty-header-file.h create mode 100644 test/Parser/cxx-extra-semi.cpp create mode 100644 test/Parser/empty-translation-unit.c create mode 100644 test/Parser/missing-selector-name.mm create mode 100644 test/Parser/objc-boxing.m create mode 100644 test/Parser/objc-diag-width.mm create mode 100644 test/Parser/objc-recover.mm create mode 100644 test/Preprocessor/disabled-cond-diags2.c create mode 100644 test/Preprocessor/macro_paste_identifier_error.c create mode 100644 test/Rewriter/objc-modern-StretAPI.mm create mode 100644 test/Rewriter/objc-modern-boxing.mm create mode 100644 test/Rewriter/objc-modern-getclass-proto.mm create mode 100644 test/Rewriter/rewrite-modern-atautoreleasepool.mm create mode 100644 test/Rewriter/rewrite-modern-block-consts.mm create mode 100644 test/Rewriter/rewrite-modern-captured-nested-bvar.mm create mode 100644 test/Rewriter/rewrite-modern-default-property-synthesis.mm create mode 100644 test/Rewriter/rewrite-modern-ivar-access.mm create mode 100644 test/Rewriter/rewrite-modern-private-ivars.mm create mode 100644 test/Rewriter/rewrite-modern-struct-ivar-1.mm create mode 100644 test/Sema/Inputs/format-unused-system-args.h create mode 100644 test/Sema/alloc_size.c create mode 100644 test/Sema/attr-coldhot.c create mode 100644 test/Sema/attr-tls_model.c create mode 100644 test/Sema/format-strings-enum-fixed-type.cpp create mode 100644 test/Sema/format-strings-enum.c create mode 100644 test/Sema/ms_wide_predefined_expr.cpp create mode 100644 test/Sema/pragma-pack-6.c create mode 100644 test/Sema/tls.c create mode 100644 test/Sema/warn-documentation-almost-trailing.c create mode 100644 test/Sema/warn-documentation-fixits.cpp create mode 100644 test/Sema/warn-documentation.cpp create mode 100644 test/Sema/warn-documentation.m create mode 100644 test/Sema/warn-outof-range-assign-enum.c create mode 100644 test/Sema/warn-self-assign-field.mm create mode 100644 test/SemaCXX/MicrosoftCompatibilityNoExceptions.cpp create mode 100644 test/SemaCXX/anonymous-union-cxx11.cpp create mode 100644 test/SemaCXX/attr-visibility.cpp create mode 100644 test/SemaCXX/constexpr-many-arguments.cpp create mode 100644 test/SemaCXX/long-virtual-inheritance-chain.cpp create mode 100644 test/SemaCXX/no-rtti.cpp create mode 100644 test/SemaCXX/offsetof-0x.cpp create mode 100644 test/SemaCXX/pr13353.cpp create mode 100644 test/SemaCXX/pr13394-crash-on-invalid.cpp create mode 100644 test/SemaCXX/printf-block.cpp create mode 100644 test/SemaCXX/printf-cstr.cpp create mode 100644 test/SemaCXX/switch-implicit-fallthrough-cxx98.cpp create mode 100644 test/SemaCXX/switch-implicit-fallthrough-per-method.cpp create mode 100644 test/SemaCXX/switch-implicit-fallthrough.cpp create mode 100644 test/SemaCXX/warn-loop-analysis.cpp create mode 100644 test/SemaCXX/warn-static-function-inheader.cpp create mode 100644 test/SemaCXX/warn-static-function-inheader.h create mode 100644 test/SemaCXX/warn-unique-enum.cpp create mode 100644 test/SemaCXX/warn-unused-private-field.cpp create mode 100644 test/SemaObjC/arc-dict-bridged-cast.m delete mode 100644 test/SemaObjC/arc-retain-block-property.m create mode 100644 test/SemaObjC/boxing-illegal-types.m create mode 100644 test/SemaObjC/dealloc.m create mode 100644 test/SemaObjC/delay-parsing-cfunctions.m create mode 100644 test/SemaObjC/format-strings-system.h create mode 100644 test/SemaObjC/getter-setter-defined-in-category-of-parent.m create mode 100644 test/SemaObjC/iboutlet.m delete mode 100644 test/SemaObjC/id-isa-ref.m create mode 100644 test/SemaObjC/mismatched-undefined-method.m create mode 100644 test/SemaObjC/no-ivar-in-interface-block.m create mode 100644 test/SemaObjC/nowarn-superclass-method-mismatch.m create mode 100644 test/SemaObjC/objc-literal-comparison.m create mode 100644 test/SemaObjC/tentative-property-decl.m create mode 100644 test/SemaObjC/warn-direct-ivar-access.m create mode 100644 test/SemaObjC/warn-isa-ref.m create mode 100644 test/SemaObjC/warn-protocol-method-deprecated.m create mode 100644 test/SemaObjC/warn-retain-block-property.m create mode 100644 test/SemaObjCXX/boxing-illegal-types.mm create mode 100644 test/SemaObjCXX/crash.mm create mode 100644 test/SemaObjCXX/delay-parsing-cfunctions.mm create mode 100644 test/SemaObjCXX/delay-parsing-cplusfuncs.mm create mode 100644 test/SemaObjCXX/delay-parsing-func-tryblock.mm create mode 100644 test/SemaObjCXX/foreach.mm create mode 100644 test/SemaObjCXX/warn-missing-super.mm create mode 100644 test/SemaOpenCL/storageclass.cl create mode 100644 test/SemaOpenCL/warn-missing-prototypes.cl create mode 100644 test/SemaTemplate/instantiation-depth-defarg.cpp create mode 100644 test/SemaTemplate/instantiation-depth-subst-2.cpp create mode 100644 test/SemaTemplate/instantiation-depth-subst.cpp create mode 100644 test/Tooling/Inputs/lit.local.cfg create mode 100644 test/Tooling/Inputs/pch-fail.h create mode 100644 test/Tooling/Inputs/pch.cpp create mode 100644 test/Tooling/Inputs/pch.h create mode 100644 test/Tooling/auto-detect-from-source-parent-of-cwd.cpp create mode 100644 test/Tooling/auto-detect-from-source-parent.cpp create mode 100644 test/Tooling/auto-detect-from-source.cpp create mode 100644 test/Tooling/clang-check-ast-dump.cpp create mode 100644 test/Tooling/clang-check-autodetect-dir.cpp create mode 100644 test/Tooling/clang-check-builtin-headers.cpp create mode 100644 test/Tooling/clang-check-chdir.cpp create mode 100644 test/Tooling/multi-jobs.cpp create mode 100644 test/Tooling/pch.cpp create mode 100755 tools/diag-build/diag-build.sh create mode 100644 tools/diagtool/DiagnosticNames.cpp create mode 100644 tools/diagtool/DiagnosticNames.h create mode 100644 tools/diagtool/ShowEnabledWarnings.cpp create mode 100644 tools/diagtool/TreeView.cpp create mode 100644 tools/libclang/CXComment.cpp create mode 100644 tools/libclang/CXComment.h create mode 100644 tools/libclang/CXCompilationDatabase.cpp create mode 100644 tools/libclang/RecursiveASTVisitor.h create mode 100644 tools/scan-build/scan-build.1 create mode 100644 unittests/AST/CMakeLists.txt create mode 100644 unittests/AST/CommentLexer.cpp create mode 100644 unittests/AST/CommentParser.cpp create mode 100644 unittests/AST/Makefile create mode 100644 unittests/ASTMatchers/ASTMatchersTest.cpp create mode 100644 unittests/ASTMatchers/ASTMatchersTest.h create mode 100644 unittests/ASTMatchers/CMakeLists.txt create mode 100644 unittests/ASTMatchers/Makefile create mode 100644 unittests/Basic/CMakeLists.txt create mode 100644 unittests/Frontend/CMakeLists.txt create mode 100644 unittests/Lex/CMakeLists.txt create mode 100644 unittests/Tooling/CMakeLists.txt create mode 100644 unittests/Tooling/CommentHandlerTest.cpp create mode 100644 unittests/Tooling/RecursiveASTVisitorTest.cpp create mode 100644 unittests/Tooling/RefactoringCallbacksTest.cpp create mode 100644 unittests/Tooling/RefactoringTest.cpp create mode 100644 unittests/Tooling/RewriterTest.cpp create mode 100644 unittests/Tooling/RewriterTestContext.h create mode 100644 unittests/Tooling/TestVisitor.h delete mode 100644 utils/TableGen/ClangASTNodesEmitter.h delete mode 100644 utils/TableGen/ClangAttrEmitter.h delete mode 100644 utils/TableGen/ClangDiagnosticsEmitter.h delete mode 100644 utils/TableGen/ClangSACheckersEmitter.h delete mode 100644 utils/TableGen/NeonEmitter.h delete mode 100644 utils/TableGen/OptParserEmitter.h create mode 100644 utils/TableGen/TableGenBackends.h create mode 100644 utils/analyzer/SumTimerInfo.py create mode 100755 utils/analyzer/reducer.pl create mode 100644 www/analyzer/faq.html create mode 100644 www/analyzer/images/example_custom_assert.png create mode 100644 www/analyzer/images/example_null_pointer.png create mode 100644 www/analyzer/images/example_use_assert.png diff --git a/.gitignore b/.gitignore index ddd66380adf8..b906ab919cbe 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,9 @@ #==============================================================================# cscope.files cscope.out + +#==============================================================================# +# Directories to ignore (do not add trailing '/'s, they skip symlinks). +#==============================================================================# +# Clang extra user tools, which is tracked independently (clang-tools-extra). +tools/extra diff --git a/CMakeLists.txt b/CMakeLists.txt index c828482ac702..2f4fa1cb5d7a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -53,6 +53,14 @@ if( CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR ) set(LLVM_TABLEGEN_EXE "${PATH_TO_LLVM_BUILD}/bin/Debug/llvm-tblgen${CMAKE_EXECUTABLE_SUFFIX}") endif() + # Define the default arguments to use with 'lit', and an option for the user + # to override. + set(LIT_ARGS_DEFAULT "-sv") + if (MSVC OR XCODE) + set(LIT_ARGS_DEFAULT "${LIT_ARGS_DEFAULT} --no-progress-bar") + endif() + set(LLVM_LIT_ARGS "${LIT_ARGS_DEFAULT}" CACHE STRING "Default options for lit") + set( CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin ) set( CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib ) set( CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib ) @@ -131,6 +139,10 @@ if (APPLE) set(CMAKE_MODULE_LINKER_FLAGS "-Wl,-flat_namespace -Wl,-undefined -Wl,suppress") endif () +# libxml2 is an optional dependency, required only to run validation +# tests on XML output. +find_package(LibXml2) + configure_file( ${CLANG_SOURCE_DIR}/include/clang/Config/config.h.cmake ${CLANG_BINARY_DIR}/include/clang/Config/config.h) @@ -192,20 +204,10 @@ macro(add_clang_library name) add_dependencies( ${name} ${LLVM_COMMON_DEPENDS} ) endif( LLVM_COMMON_DEPENDS ) - target_link_libraries( ${name} ${LLVM_USED_LIBS} ) llvm_config( ${name} ${LLVM_LINK_COMPONENTS} ) target_link_libraries( ${name} ${LLVM_COMMON_LIBS} ) link_system_libs( ${name} ) - add_dependencies(${name} ClangDiagnosticCommon) - if(MSVC) - get_target_property(cflag ${name} COMPILE_FLAGS) - if(NOT cflag) - set(cflag "") - endif(NOT cflag) - set(cflag "${cflag} /Za") - set_target_properties(${name} PROPERTIES COMPILE_FLAGS ${cflag}) - endif(MSVC) install(TARGETS ${name} LIBRARY DESTINATION lib${LLVM_LIBDIR_SUFFIX} ARCHIVE DESTINATION lib${LLVM_LIBDIR_SUFFIX} @@ -252,14 +254,14 @@ mark_as_advanced(CLANG_EXECUTABLE_VERSION LIBCLANG_LIBRARY_VERSION) add_subdirectory(utils/TableGen) -option(CLANG_BUILD_EXAMPLES "Build CLANG example programs by default." OFF) -add_subdirectory(examples) - add_subdirectory(include) add_subdirectory(lib) add_subdirectory(tools) add_subdirectory(runtime) +option(CLANG_BUILD_EXAMPLES "Build CLANG example programs by default." OFF) +add_subdirectory(examples) + # TODO: docs. add_subdirectory(test) @@ -280,3 +282,4 @@ endif() set(BUG_REPORT_URL "http://llvm.org/bugs/" CACHE STRING "Default URL where bug reports are to be submitted.") + diff --git a/bindings/python/clang/cindex.py b/bindings/python/clang/cindex.py index 6f0d25f1a8f5..fc0a2a18bb40 100644 --- a/bindings/python/clang/cindex.py +++ b/bindings/python/clang/cindex.py @@ -65,6 +65,8 @@ call is efficient. from ctypes import * import collections +import clang.enumerations + def get_cindex_library(): # FIXME: It's probably not the case that the library is actually found in # this location. We need a better system of identifying and loading the @@ -85,6 +87,49 @@ def get_cindex_library(): c_object_p = POINTER(c_void_p) lib = get_cindex_library() +callbacks = {} + +### Exception Classes ### + +class TranslationUnitLoadError(Exception): + """Represents an error that occurred when loading a TranslationUnit. + + This is raised in the case where a TranslationUnit could not be + instantiated due to failure in the libclang library. + + FIXME: Make libclang expose additional error information in this scenario. + """ + pass + +class TranslationUnitSaveError(Exception): + """Represents an error that occurred when saving a TranslationUnit. + + Each error has associated with it an enumerated value, accessible under + e.save_error. Consumers can compare the value with one of the ERROR_ + constants in this class. + """ + + # Indicates that an unknown error occurred. This typically indicates that + # I/O failed during save. + ERROR_UNKNOWN = 1 + + # Indicates that errors during translation prevented saving. The errors + # should be available via the TranslationUnit's diagnostics. + ERROR_TRANSLATION_ERRORS = 2 + + # Indicates that the translation unit was somehow invalid. + ERROR_INVALID_TU = 3 + + def __init__(self, enumeration, message): + assert isinstance(enumeration, int) + + if enumeration < 1 or enumeration > 3: + raise Exception("Encountered undefined TranslationUnit save error " + "constant: %d. Please file a bug to have this " + "value supported." % enumeration) + + self.save_error = enumeration + Exception.__init__(self, 'Error %d: %s' % (enumeration, message)) ### Structures and Utility Classes ### @@ -94,12 +139,12 @@ class _CXString(Structure): _fields_ = [("spelling", c_char_p), ("free", c_int)] def __del__(self): - _CXString_dispose(self) + lib.clang_disposeString(self) @staticmethod def from_result(res, fn, args): assert isinstance(res, _CXString) - return _CXString_getCString(res) + return lib.clang_getCString(res) class SourceLocation(Structure): """ @@ -111,7 +156,8 @@ class SourceLocation(Structure): def _get_instantiation(self): if self._data is None: f, l, c, o = c_object_p(), c_uint(), c_uint(), c_uint() - SourceLocation_loc(self, byref(f), byref(l), byref(c), byref(o)) + lib.clang_getInstantiationLocation(self, byref(f), byref(l), + byref(c), byref(o)) if f: f = File(f) else: @@ -125,7 +171,17 @@ class SourceLocation(Structure): Retrieve the source location associated with a given file/line/column in a particular translation unit. """ - return SourceLocation_getLocation(tu, file, line, column) + return lib.clang_getLocation(tu, file, line, column) + + @staticmethod + def from_offset(tu, file, offset): + """Retrieve a SourceLocation from a given character offset. + + tu -- TranslationUnit file belongs to + file -- File instance to obtain offset from + offset -- Integer character offset within file + """ + return lib.clang_getLocationForOffset(tu, file, offset) @property def file(self): @@ -148,7 +204,7 @@ class SourceLocation(Structure): return self._get_instantiation()[3] def __eq__(self, other): - return SourceLocation_equalLocations(self, other) + return lib.clang_equalLocations(self, other) def __ne__(self, other): return not self.__eq__(other) @@ -175,7 +231,7 @@ class SourceRange(Structure): # object. @staticmethod def from_locations(start, end): - return SourceRange_getRange(start, end) + return lib.clang_getRange(start, end) @property def start(self): @@ -183,7 +239,7 @@ class SourceRange(Structure): Return a SourceLocation representing the first character within a source range. """ - return SourceRange_start(self) + return lib.clang_getRangeStart(self) @property def end(self): @@ -191,10 +247,10 @@ class SourceRange(Structure): Return a SourceLocation representing the last character within a source range. """ - return SourceRange_end(self) + return lib.clang_getRangeEnd(self) def __eq__(self, other): - return SourceRange_equalRanges(self, other) + return lib.clang_equalRanges(self, other) def __ne__(self, other): return not self.__eq__(other) @@ -219,19 +275,19 @@ class Diagnostic(object): self.ptr = ptr def __del__(self): - _clang_disposeDiagnostic(self) + lib.clang_disposeDiagnostic(self) @property def severity(self): - return _clang_getDiagnosticSeverity(self) + return lib.clang_getDiagnosticSeverity(self) @property def location(self): - return _clang_getDiagnosticLocation(self) + return lib.clang_getDiagnosticLocation(self) @property def spelling(self): - return _clang_getDiagnosticSpelling(self) + return lib.clang_getDiagnosticSpelling(self) @property def ranges(self): @@ -240,12 +296,12 @@ class Diagnostic(object): self.diag = diag def __len__(self): - return int(_clang_getDiagnosticNumRanges(self.diag)) + return int(lib.clang_getDiagnosticNumRanges(self.diag)) def __getitem__(self, key): if (key >= len(self)): raise IndexError - return _clang_getDiagnosticRange(self.diag, key) + return lib.clang_getDiagnosticRange(self.diag, key) return RangeIterator(self) @@ -256,11 +312,12 @@ class Diagnostic(object): self.diag = diag def __len__(self): - return int(_clang_getDiagnosticNumFixIts(self.diag)) + return int(lib.clang_getDiagnosticNumFixIts(self.diag)) def __getitem__(self, key): range = SourceRange() - value = _clang_getDiagnosticFixIt(self.diag, key, byref(range)) + value = lib.clang_getDiagnosticFixIt(self.diag, key, + byref(range)) if len(value) == 0: raise IndexError @@ -271,25 +328,25 @@ class Diagnostic(object): @property def category_number(self): """The category number for this diagnostic.""" - return _clang_getDiagnosticCategory(self) + return lib.clang_getDiagnosticCategory(self) @property def category_name(self): """The string name of the category for this diagnostic.""" - return _clang_getDiagnosticCategoryName(self.category_number) + return lib.clang_getDiagnosticCategoryName(self.category_number) @property def option(self): """The command-line option that enables this diagnostic.""" - return _clang_getDiagnosticOption(self, None) + return lib.clang_getDiagnosticOption(self, None) @property def disable_option(self): """The command-line option that disables this diagnostic.""" disable = _CXString() - _clang_getDiagnosticOption(self, byref(disable)) + lib.clang_getDiagnosticOption(self, byref(disable)) - return _CXString_getCString(disable) + return lib.clang_getCString(disable) def __repr__(self): return "" % ( @@ -312,6 +369,98 @@ class FixIt(object): def __repr__(self): return "" % (self.range, self.value) +class TokenGroup(object): + """Helper class to facilitate token management. + + Tokens are allocated from libclang in chunks. They must be disposed of as a + collective group. + + One purpose of this class is for instances to represent groups of allocated + tokens. Each token in a group contains a reference back to an instance of + this class. When all tokens from a group are garbage collected, it allows + this class to be garbage collected. When this class is garbage collected, + it calls the libclang destructor which invalidates all tokens in the group. + + You should not instantiate this class outside of this module. + """ + def __init__(self, tu, memory, count): + self._tu = tu + self._memory = memory + self._count = count + + def __del__(self): + lib.clang_disposeTokens(self._tu, self._memory, self._count) + + @staticmethod + def get_tokens(tu, extent): + """Helper method to return all tokens in an extent. + + This functionality is needed multiple places in this module. We define + it here because it seems like a logical place. + """ + tokens_memory = POINTER(Token)() + tokens_count = c_uint() + + lib.clang_tokenize(tu, extent, byref(tokens_memory), + byref(tokens_count)) + + count = int(tokens_count.value) + + # If we get no tokens, no memory was allocated. Be sure not to return + # anything and potentially call a destructor on nothing. + if count < 1: + return + + tokens_array = cast(tokens_memory, POINTER(Token * count)).contents + + token_group = TokenGroup(tu, tokens_memory, tokens_count) + + for i in xrange(0, count): + token = Token() + token.int_data = tokens_array[i].int_data + token.ptr_data = tokens_array[i].ptr_data + token._tu = tu + token._group = token_group + + yield token + +class TokenKind(object): + """Describes a specific type of a Token.""" + + _value_map = {} # int -> TokenKind + + def __init__(self, value, name): + """Create a new TokenKind instance from a numeric value and a name.""" + self.value = value + self.name = name + + def __repr__(self): + return 'TokenKind.%s' % (self.name,) + + @staticmethod + def from_value(value): + """Obtain a registered TokenKind instance from its value.""" + result = TokenKind._value_map.get(value, None) + + if result is None: + raise ValueError('Unknown TokenKind: %d' % value) + + return result + + @staticmethod + def register(value, name): + """Register a new TokenKind enumeration. + + This should only be called at module load time by code within this + package. + """ + if value in TokenKind._value_map: + raise ValueError('TokenKind already registered: %d' % value) + + kind = TokenKind(value, name) + TokenKind._value_map[value] = kind + setattr(TokenKind, name, kind) + ### Cursor Kinds ### class CursorKind(object): @@ -358,39 +507,39 @@ class CursorKind(object): def is_declaration(self): """Test if this is a declaration kind.""" - return CursorKind_is_decl(self) + return lib.clang_isDeclaration(self) def is_reference(self): """Test if this is a reference kind.""" - return CursorKind_is_ref(self) + return lib.clang_isReference(self) def is_expression(self): """Test if this is an expression kind.""" - return CursorKind_is_expr(self) + return lib.clang_isExpression(self) def is_statement(self): """Test if this is a statement kind.""" - return CursorKind_is_stmt(self) + return lib.clang_isStatement(self) def is_attribute(self): """Test if this is an attribute kind.""" - return CursorKind_is_attribute(self) + return lib.clang_isAttribute(self) def is_invalid(self): """Test if this is an invalid kind.""" - return CursorKind_is_inv(self) + return lib.clang_isInvalid(self) def is_translation_unit(self): """Test if this is a translation unit kind.""" - return CursorKind_is_translation_unit(self) + return lib.clang_isTranslationUnit(self) def is_preprocessing(self): """Test if this is a preprocessing kind.""" - return CursorKind_is_preprocessing(self) + return lib.clang_isPreprocessing(self) def is_unexposed(self): """Test if this is an unexposed kind.""" - return CursorKind_is_unexposed(self) + return lib.clang_isUnexposed(self) def __repr__(self): return 'CursorKind.%s' % (self.name,) @@ -635,7 +784,7 @@ CursorKind.BINARY_OPERATOR = CursorKind(114) CursorKind.COMPOUND_ASSIGNMENT_OPERATOR = CursorKind(115) # The ?: ternary operator. -CursorKind.CONDITONAL_OPERATOR = CursorKind(116) +CursorKind.CONDITIONAL_OPERATOR = CursorKind(116) # An explicit cast in C (C99 6.5.4) or a C-style cast in C++ # (C++ [expr.cast]), which uses the syntax (Type)expr. @@ -887,10 +1036,15 @@ class Cursor(Structure): @staticmethod def from_location(tu, location): - return Cursor_get(tu, location) + # We store a reference to the TU in the instance so the TU won't get + # collected before the cursor. + cursor = lib.clang_getCursor(tu, location) + cursor._tu = tu + + return cursor def __eq__(self, other): - return Cursor_eq(self, other) + return lib.clang_equalCursors(self, other) def __ne__(self, other): return not self.__eq__(other) @@ -900,7 +1054,13 @@ class Cursor(Structure): Returns true if the declaration pointed at by the cursor is also a definition of that entity. """ - return Cursor_is_def(self) + return lib.clang_isCursorDefinition(self) + + def is_static_method(self): + """Returns True if the cursor refers to a C++ member function or member + function template that is declared 'static'. + """ + return lib.clang_CXXMethod_isStatic(self) def get_definition(self): """ @@ -910,7 +1070,7 @@ class Cursor(Structure): """ # TODO: Should probably check that this is either a reference or # declaration prior to issuing the lookup. - return Cursor_def(self) + return lib.clang_getCursorDefinition(self) def get_usr(self): """Return the Unified Symbol Resultion (USR) for the entity referenced @@ -921,7 +1081,7 @@ class Cursor(Structure): program. USRs can be compared across translation units to determine, e.g., when references in one translation refer to an entity defined in another translation unit.""" - return Cursor_usr(self) + return lib.clang_getCursorUSR(self) @property def kind(self): @@ -936,7 +1096,8 @@ class Cursor(Structure): # this, for consistency with clang_getCursorUSR. return None if not hasattr(self, '_spelling'): - self._spelling = Cursor_spelling(self) + self._spelling = lib.clang_getCursorSpelling(self) + return self._spelling @property @@ -949,7 +1110,8 @@ class Cursor(Structure): class template specialization. """ if not hasattr(self, '_displayname'): - self._displayname = Cursor_displayname(self) + self._displayname = lib.clang_getCursorDisplayName(self) + return self._displayname @property @@ -959,7 +1121,8 @@ class Cursor(Structure): pointed at by the cursor. """ if not hasattr(self, '_loc'): - self._loc = Cursor_loc(self) + self._loc = lib.clang_getCursorLocation(self) + return self._loc @property @@ -969,7 +1132,8 @@ class Cursor(Structure): pointed at by the cursor. """ if not hasattr(self, '_extent'): - self._extent = Cursor_extent(self) + self._extent = lib.clang_getCursorExtent(self) + return self._extent @property @@ -978,9 +1142,32 @@ class Cursor(Structure): Retrieve the Type (if any) of the entity pointed at by the cursor. """ if not hasattr(self, '_type'): - self._type = Cursor_type(self) + self._type = lib.clang_getCursorType(self) + return self._type + @property + def canonical(self): + """Return the canonical Cursor corresponding to this Cursor. + + The canonical cursor is the cursor which is representative for the + underlying entity. For example, if you have multiple forward + declarations for the same class, the canonical cursor for the forward + declarations will be identical. + """ + if not hasattr(self, '_canonical'): + self._canonical = lib.clang_getCanonicalCursor(self) + + return self._canonical + + @property + def result_type(self): + """Retrieve the Type of the result for this Cursor.""" + if not hasattr(self, '_result_type'): + self._result_type = lib.clang_getResultType(self.type) + + return self._result_type + @property def underlying_typedef_type(self): """Return the underlying type of a typedef declaration. @@ -990,7 +1177,7 @@ class Cursor(Structure): """ if not hasattr(self, '_underlying_type'): assert self.kind.is_declaration() - self._underlying_type = Cursor_underlying_type(self) + self._underlying_type = lib.clang_getTypedefDeclUnderlyingType(self) return self._underlying_type @@ -1003,15 +1190,39 @@ class Cursor(Structure): """ if not hasattr(self, '_enum_type'): assert self.kind == CursorKind.ENUM_DECL - self._enum_type = Cursor_enum_type(self) + self._enum_type = lib.clang_getEnumDeclIntegerType(self) return self._enum_type + @property + def enum_value(self): + """Return the value of an enum constant.""" + if not hasattr(self, '_enum_value'): + assert self.kind == CursorKind.ENUM_CONSTANT_DECL + # Figure out the underlying type of the enum to know if it + # is a signed or unsigned quantity. + underlying_type = self.type + if underlying_type.kind == TypeKind.ENUM: + underlying_type = underlying_type.get_declaration().enum_type + if underlying_type.kind in (TypeKind.CHAR_U, + TypeKind.UCHAR, + TypeKind.CHAR16, + TypeKind.CHAR32, + TypeKind.USHORT, + TypeKind.UINT, + TypeKind.ULONG, + TypeKind.ULONGLONG, + TypeKind.UINT128): + self._enum_value = lib.clang_getEnumConstantDeclUnsignedValue(self) + else: + self._enum_value = lib.clang_getEnumConstantDeclValue(self) + return self._enum_value + @property def objc_type_encoding(self): """Return the Objective-C type encoding as a str.""" if not hasattr(self, '_objc_type_encoding'): - self._objc_type_encoding = Cursor_objc_type_encoding(self) + self._objc_type_encoding = lib.clang_getDeclObjCTypeEncoding(self) return self._objc_type_encoding @@ -1019,10 +1230,33 @@ class Cursor(Structure): def hash(self): """Returns a hash of the cursor as an int.""" if not hasattr(self, '_hash'): - self._hash = Cursor_hash(self) + self._hash = lib.clang_hashCursor(self) return self._hash + @property + def semantic_parent(self): + """Return the semantic parent for this cursor.""" + if not hasattr(self, '_semantic_parent'): + self._semantic_parent = lib.clang_getCursorSemanticParent(self) + + return self._semantic_parent + + @property + def lexical_parent(self): + """Return the lexical parent for this cursor.""" + if not hasattr(self, '_lexical_parent'): + self._lexical_parent = lib.clang_getCursorLexicalParent(self) + + return self._lexical_parent + + @property + def translation_unit(self): + """Returns the TranslationUnit to which this Cursor belongs.""" + # If this triggers an AttributeError, the instance was not properly + # created. + return self._tu + def get_children(self): """Return an iterator for accessing the children of this cursor.""" @@ -1030,21 +1264,57 @@ class Cursor(Structure): def visitor(child, parent, children): # FIXME: Document this assertion in API. # FIXME: There should just be an isNull method. - assert child != Cursor_null() + assert child != lib.clang_getNullCursor() + + # Create reference to TU so it isn't GC'd before Cursor. + child._tu = self._tu children.append(child) return 1 # continue children = [] - Cursor_visit(self, Cursor_visit_callback(visitor), children) + lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor), + children) return iter(children) + def get_tokens(self): + """Obtain Token instances formulating that compose this Cursor. + + This is a generator for Token instances. It returns all tokens which + occupy the extent this cursor occupies. + """ + return TokenGroup.get_tokens(self._tu, self.extent) + @staticmethod def from_result(res, fn, args): assert isinstance(res, Cursor) # FIXME: There should just be an isNull method. - if res == Cursor_null(): + if res == lib.clang_getNullCursor(): return None + + # Store a reference to the TU in the Python object so it won't get GC'd + # before the Cursor. + tu = None + for arg in args: + if isinstance(arg, TranslationUnit): + tu = arg + break + + if hasattr(arg, 'translation_unit'): + tu = arg.translation_unit + break + + assert tu is not None + + res._tu = tu return res + @staticmethod + def from_cursor_result(res, fn, args): + assert isinstance(res, Cursor) + if res == lib.clang_getNullCursor(): + return None + + res._tu = args[0]._tu + return res ### Type Kinds ### @@ -1082,7 +1352,7 @@ class TypeKind(object): @property def spelling(self): """Retrieve the spelling of this TypeKind.""" - return TypeKind_spelling(self.value) + return lib.clang_getTypeKindSpelling(self.value) @staticmethod def from_id(id): @@ -1093,12 +1363,6 @@ class TypeKind(object): def __repr__(self): return 'TypeKind.%s' % (self.name,) -TypeKind_spelling = lib.clang_getTypeKindSpelling -TypeKind_spelling.argtypes = [c_uint] -TypeKind_spelling.restype = _CXString -TypeKind_spelling.errcheck = _CXString.from_result - - TypeKind.INVALID = TypeKind(0) TypeKind.UNEXPOSED = TypeKind(1) TypeKind.VOID = TypeKind(2) @@ -1168,7 +1432,7 @@ class Type(Structure): def __len__(self): if self.length is None: - self.length = Type_get_num_arg_types(self.parent) + self.length = lib.clang_getNumArgTypes(self.parent) return self.length @@ -1184,7 +1448,7 @@ class Type(Structure): raise IndexError("Index greater than container length: " "%d > %d" % ( key, len(self) )) - result = Type_get_arg_type(self.parent, key) + result = lib.clang_getArgType(self.parent, key) if result.kind == TypeKind.INVALID: raise IndexError("Argument could not be retrieved.") @@ -1200,7 +1464,7 @@ class Type(Structure): If accessed on a type that is not an array, complex, or vector type, an exception will be raised. """ - result = Type_get_element_type(self) + result = lib.clang_getElementType(self) if result.kind == TypeKind.INVALID: raise Exception('Element type not available on this type.') @@ -1214,15 +1478,32 @@ class Type(Structure): If the Type is not an array or vector, this raises. """ - result = Type_get_num_elements(self) + result = lib.clang_getNumElements(self) if result < 0: raise Exception('Type does not have elements.') return result + @property + def translation_unit(self): + """The TranslationUnit to which this Type is associated.""" + # If this triggers an AttributeError, the instance was not properly + # instantiated. + return self._tu + @staticmethod def from_result(res, fn, args): assert isinstance(res, Type) + + tu = None + for arg in args: + if hasattr(arg, 'translation_unit'): + tu = arg.translation_unit + break + + assert tu is not None + res._tu = tu + return res def get_canonical(self): @@ -1235,7 +1516,7 @@ class Type(Structure): example, if 'T' is a typedef for 'int', the canonical type for 'T' would be 'int'. """ - return Type_get_canonical(self) + return lib.clang_getCanonicalType(self) def is_const_qualified(self): """Determine whether a Type has the "const" qualifier set. @@ -1243,7 +1524,7 @@ class Type(Structure): This does not look through typedefs that may have added "const" at a different level. """ - return Type_is_const_qualified(self) + return lib.clang_isConstQualifiedType(self) def is_volatile_qualified(self): """Determine whether a Type has the "volatile" qualifier set. @@ -1251,7 +1532,7 @@ class Type(Structure): This does not look through typedefs that may have added "volatile" at a different level. """ - return Type_is_volatile_qualified(self) + return lib.clang_isVolatileQualifiedType(self) def is_restrict_qualified(self): """Determine whether a Type has the "restrict" qualifier set. @@ -1259,53 +1540,53 @@ class Type(Structure): This does not look through typedefs that may have added "restrict" at a different level. """ - return Type_is_restrict_qualified(self) + return lib.clang_isRestrictQualifiedType(self) def is_function_variadic(self): """Determine whether this function Type is a variadic function type.""" assert self.kind == TypeKind.FUNCTIONPROTO - return Type_is_variadic(self) + return lib.clang_isFunctionTypeVariadic(self) def is_pod(self): """Determine whether this Type represents plain old data (POD).""" - return Type_is_pod(self) + return lib.clang_isPODType(self) def get_pointee(self): """ For pointer types, returns the type of the pointee. """ - return Type_get_pointee(self) + return lib.clang_getPointeeType(self) def get_declaration(self): """ Return the cursor for the declaration of the given type. """ - return Type_get_declaration(self) + return lib.clang_getTypeDeclaration(self) def get_result(self): """ Retrieve the result type associated with a function type. """ - return Type_get_result(self) + return lib.clang_getResultType(self) def get_array_element_type(self): """ Retrieve the type of the elements of the array type. """ - return Type_get_array_element(self) + return lib.clang_getArrayElementType(self) def get_array_size(self): """ Retrieve the size of the constant array. """ - return Type_get_array_size(self) + return lib.clang_getArraySize(self) def __eq__(self, other): if type(other) != type(self): return False - return Type_equal(self, other) + return lib.clang_equalTypes(self, other) def __ne__(self, other): return not self.__eq__(other) @@ -1333,65 +1614,6 @@ class _CXUnsavedFile(Structure): """Helper for passing unsaved file arguments.""" _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)] -## Diagnostic Conversion ## - -_clang_getNumDiagnostics = lib.clang_getNumDiagnostics -_clang_getNumDiagnostics.argtypes = [c_object_p] -_clang_getNumDiagnostics.restype = c_uint - -_clang_getDiagnostic = lib.clang_getDiagnostic -_clang_getDiagnostic.argtypes = [c_object_p, c_uint] -_clang_getDiagnostic.restype = c_object_p - -_clang_disposeDiagnostic = lib.clang_disposeDiagnostic -_clang_disposeDiagnostic.argtypes = [Diagnostic] - -_clang_getDiagnosticSeverity = lib.clang_getDiagnosticSeverity -_clang_getDiagnosticSeverity.argtypes = [Diagnostic] -_clang_getDiagnosticSeverity.restype = c_int - -_clang_getDiagnosticLocation = lib.clang_getDiagnosticLocation -_clang_getDiagnosticLocation.argtypes = [Diagnostic] -_clang_getDiagnosticLocation.restype = SourceLocation - -_clang_getDiagnosticSpelling = lib.clang_getDiagnosticSpelling -_clang_getDiagnosticSpelling.argtypes = [Diagnostic] -_clang_getDiagnosticSpelling.restype = _CXString -_clang_getDiagnosticSpelling.errcheck = _CXString.from_result - -_clang_getDiagnosticNumRanges = lib.clang_getDiagnosticNumRanges -_clang_getDiagnosticNumRanges.argtypes = [Diagnostic] -_clang_getDiagnosticNumRanges.restype = c_uint - -_clang_getDiagnosticRange = lib.clang_getDiagnosticRange -_clang_getDiagnosticRange.argtypes = [Diagnostic, c_uint] -_clang_getDiagnosticRange.restype = SourceRange - -_clang_getDiagnosticNumFixIts = lib.clang_getDiagnosticNumFixIts -_clang_getDiagnosticNumFixIts.argtypes = [Diagnostic] -_clang_getDiagnosticNumFixIts.restype = c_uint - -_clang_getDiagnosticFixIt = lib.clang_getDiagnosticFixIt -_clang_getDiagnosticFixIt.argtypes = [Diagnostic, c_uint, POINTER(SourceRange)] -_clang_getDiagnosticFixIt.restype = _CXString -_clang_getDiagnosticFixIt.errcheck = _CXString.from_result - -_clang_getDiagnosticCategory = lib.clang_getDiagnosticCategory -_clang_getDiagnosticCategory.argtypes = [Diagnostic] -_clang_getDiagnosticCategory.restype = c_uint - -_clang_getDiagnosticCategoryName = lib.clang_getDiagnosticCategoryName -_clang_getDiagnosticCategoryName.argtypes = [c_uint] -_clang_getDiagnosticCategoryName.restype = _CXString -_clang_getDiagnosticCategoryName.errcheck = _CXString.from_result - -_clang_getDiagnosticOption = lib.clang_getDiagnosticOption -_clang_getDiagnosticOption.argtypes = [Diagnostic, POINTER(_CXString)] -_clang_getDiagnosticOption.restype = _CXString -_clang_getDiagnosticOption.errcheck = _CXString.from_result - -### - class CompletionChunk: class Kind: def __init__(self, name): @@ -1412,16 +1634,16 @@ class CompletionChunk: @property def spelling(self): - return _clang_getCompletionChunkText(self.cs, self.key).spelling + return lib.clang_getCompletionChunkText(self.cs, self.key).spelling @property def kind(self): - res = _clang_getCompletionChunkKind(self.cs, self.key) + res = lib.clang_getCompletionChunkKind(self.cs, self.key) return completionChunkKindMap[res] @property def string(self): - res = _clang_getCompletionChunkCompletionString(self.cs, self.key) + res = lib.clang_getCompletionChunkCompletionString(self.cs, self.key) if (res): return CompletionString(res) @@ -1478,7 +1700,7 @@ class CompletionString(ClangObject): return "" % self def __len__(self): - return _clang_getNumCompletionChunks(self.obj) + return lib.clang_getNumCompletionChunks(self.obj) def __getitem__(self, key): if len(self) <= key: @@ -1487,11 +1709,11 @@ class CompletionString(ClangObject): @property def priority(self): - return _clang_getCompletionPriority(self.obj) + return lib.clang_getCompletionPriority(self.obj) @property def availability(self): - res = _clang_getCompletionAvailability(self.obj) + res = lib.clang_getCompletionAvailability(self.obj) return availabilityKinds[res] def __repr__(self): @@ -1553,10 +1775,10 @@ class CodeCompletionResults(ClangObject): self.ccr= ccr def __len__(self): - return int(_clang_codeCompleteGetNumDiagnostics(self.ccr)) + return int(lib.clang_codeCompleteGetNumDiagnostics(self.ccr)) def __getitem__(self, key): - return _clang_codeCompleteGetDiagnostic(self.ccr, key) + return lib.clang_codeCompleteGetDiagnostic(self.ccr, key) return DiagnosticsItr(self) @@ -1575,21 +1797,17 @@ class Index(ClangObject): Parameters: excludeDecls -- Exclude local declarations from translation units. """ - return Index(Index_create(excludeDecls, 0)) + return Index(lib.clang_createIndex(excludeDecls, 0)) def __del__(self): - Index_dispose(self) + lib.clang_disposeIndex(self) def read(self, path): - """Load the translation unit from the given AST file.""" - ptr = TranslationUnit_read(self, path) - if ptr: - return TranslationUnit(ptr) - return None + """Load a TranslationUnit from the given AST file.""" + return TranslationUnit.from_ast(path, self) - def parse(self, path, args = [], unsaved_files = [], options = 0): - """ - Load the translation unit from the given source code file by running + def parse(self, path, args=None, unsaved_files=None, options = 0): + """Load the translation unit from the given source code file by running clang and generating the AST before loading. Additional command line parameters can be passed to clang via the args parameter. @@ -1597,53 +1815,167 @@ class Index(ClangObject): to as unsaved_files, the first item should be the filenames to be mapped and the second should be the contents to be substituted for the file. The contents may be passed as strings or file objects. - """ - arg_array = 0 - if len(args): - arg_array = (c_char_p * len(args))(* args) - unsaved_files_array = 0 - if len(unsaved_files): - unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() - for i,(name,value) in enumerate(unsaved_files): - if not isinstance(value, str): - # FIXME: It would be great to support an efficient version - # of this, one day. - value = value.read() - print value - if not isinstance(value, str): - raise TypeError,'Unexpected unsaved file contents.' - unsaved_files_array[i].name = name - unsaved_files_array[i].contents = value - unsaved_files_array[i].length = len(value) - ptr = TranslationUnit_parse(self, path, arg_array, len(args), - unsaved_files_array, len(unsaved_files), - options) - if ptr: - return TranslationUnit(ptr) - return None + If an error was encountered during parsing, a TranslationUnitLoadError + will be raised. + """ + return TranslationUnit.from_source(path, args, unsaved_files, options, + self) class TranslationUnit(ClangObject): - """ - The TranslationUnit class represents a source code translation unit and - provides read-only access to its top-level declarations. + """Represents a source code translation unit. + + This is one of the main types in the API. Any time you wish to interact + with Clang's representation of a source file, you typically start with a + translation unit. """ - def __init__(self, ptr): + # Default parsing mode. + PARSE_NONE = 0 + + # Instruct the parser to create a detailed processing record containing + # metadata not normally retained. + PARSE_DETAILED_PROCESSING_RECORD = 1 + + # Indicates that the translation unit is incomplete. This is typically used + # when parsing headers. + PARSE_INCOMPLETE = 2 + + # Instruct the parser to create a pre-compiled preamble for the translation + # unit. This caches the preamble (included files at top of source file). + # This is useful if the translation unit will be reparsed and you don't + # want to incur the overhead of reparsing the preamble. + PARSE_PRECOMPILED_PREAMBLE = 4 + + # Cache code completion information on parse. This adds time to parsing but + # speeds up code completion. + PARSE_CACHE_COMPLETION_RESULTS = 8 + + # Flags with values 16 and 32 are deprecated and intentionally omitted. + + # Do not parse function bodies. This is useful if you only care about + # searching for declarations/definitions. + PARSE_SKIP_FUNCTION_BODIES = 64 + + @classmethod + def from_source(cls, filename, args=None, unsaved_files=None, options=0, + index=None): + """Create a TranslationUnit by parsing source. + + This is capable of processing source code both from files on the + filesystem as well as in-memory contents. + + Command-line arguments that would be passed to clang are specified as + a list via args. These can be used to specify include paths, warnings, + etc. e.g. ["-Wall", "-I/path/to/include"]. + + In-memory file content can be provided via unsaved_files. This is an + iterable of 2-tuples. The first element is the str filename. The + second element defines the content. Content can be provided as str + source code or as file objects (anything with a read() method). If + a file object is being used, content will be read until EOF and the + read cursor will not be reset to its original position. + + options is a bitwise or of TranslationUnit.PARSE_XXX flags which will + control parsing behavior. + + index is an Index instance to utilize. If not provided, a new Index + will be created for this TranslationUnit. + + To parse source from the filesystem, the filename of the file to parse + is specified by the filename argument. Or, filename could be None and + the args list would contain the filename(s) to parse. + + To parse source from an in-memory buffer, set filename to the virtual + filename you wish to associate with this source (e.g. "test.c"). The + contents of that file are then provided in unsaved_files. + + If an error occurs, a TranslationUnitLoadError is raised. + + Please note that a TranslationUnit with parser errors may be returned. + It is the caller's responsibility to check tu.diagnostics for errors. + + Also note that Clang infers the source language from the extension of + the input filename. If you pass in source code containing a C++ class + declaration with the filename "test.c" parsing will fail. + """ + if args is None: + args = [] + + if unsaved_files is None: + unsaved_files = [] + + if index is None: + index = Index.create() + + args_array = None + if len(args) > 0: + args_array = (c_char_p * len(args))(* args) + + unsaved_array = None + if len(unsaved_files) > 0: + unsaved_array = (_CXUnsavedFile * len(unsaved_files))() + for i, (name, contents) in enumerate(unsaved_files): + if hasattr(contents, "read"): + contents = contents.read() + + unsaved_array[i].name = name + unsaved_array[i].contents = contents + unsaved_array[i].length = len(contents) + + ptr = lib.clang_parseTranslationUnit(index, filename, args_array, + len(args), unsaved_array, + len(unsaved_files), options) + + if ptr is None: + raise TranslationUnitLoadError("Error parsing translation unit.") + + return cls(ptr, index=index) + + @classmethod + def from_ast_file(cls, filename, index=None): + """Create a TranslationUnit instance from a saved AST file. + + A previously-saved AST file (provided with -emit-ast or + TranslationUnit.save()) is loaded from the filename specified. + + If the file cannot be loaded, a TranslationUnitLoadError will be + raised. + + index is optional and is the Index instance to use. If not provided, + a default Index will be created. + """ + if index is None: + index = Index.create() + + ptr = lib.clang_createTranslationUnit(index, filename) + if ptr is None: + raise TranslationUnitLoadError(filename) + + return cls(ptr=ptr, index=index) + + def __init__(self, ptr, index): + """Create a TranslationUnit instance. + + TranslationUnits should be created using one of the from_* @classmethod + functions above. __init__ is only called internally. + """ + assert isinstance(index, Index) + ClangObject.__init__(self, ptr) def __del__(self): - TranslationUnit_dispose(self) + lib.clang_disposeTranslationUnit(self) @property def cursor(self): """Retrieve the cursor that represents the given translation unit.""" - return TranslationUnit_cursor(self) + return lib.clang_getTranslationUnitCursor(self) @property def spelling(self): """Get the original translation unit source file name.""" - return TranslationUnit_spelling(self) + return lib.clang_getTranslationUnitSpelling(self) def get_includes(self): """ @@ -1660,11 +1992,72 @@ class TranslationUnit(ClangObject): # Automatically adapt CIndex/ctype pointers to python objects includes = [] - TranslationUnit_includes(self, - TranslationUnit_includes_callback(visitor), - includes) + lib.clang_getInclusions(self, + callbacks['translation_unit_includes'](visitor), includes) + return iter(includes) + def get_file(self, filename): + """Obtain a File from this translation unit.""" + + return File.from_name(self, filename) + + def get_location(self, filename, position): + """Obtain a SourceLocation for a file in this translation unit. + + The position can be specified by passing: + + - Integer file offset. Initial file offset is 0. + - 2-tuple of (line number, column number). Initial file position is + (0, 0) + """ + f = self.get_file(filename) + + if isinstance(position, int): + return SourceLocation.from_offset(self, f, position) + + return SourceLocation.from_position(self, f, position[0], position[1]) + + def get_extent(self, filename, locations): + """Obtain a SourceRange from this translation unit. + + The bounds of the SourceRange must ultimately be defined by a start and + end SourceLocation. For the locations argument, you can pass: + + - 2 SourceLocation instances in a 2-tuple or list. + - 2 int file offsets via a 2-tuple or list. + - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list. + + e.g. + + get_extent('foo.c', (5, 10)) + get_extent('foo.c', ((1, 1), (1, 15))) + """ + f = self.get_file(filename) + + if len(locations) < 2: + raise Exception('Must pass object with at least 2 elements') + + start_location, end_location = locations + + if hasattr(start_location, '__len__'): + start_location = SourceLocation.from_position(self, f, + start_location[0], start_location[1]) + elif isinstance(start_location, int): + start_location = SourceLocation.from_offset(self, f, + start_location) + + if hasattr(end_location, '__len__'): + end_location = SourceLocation.from_position(self, f, + end_location[0], end_location[1]) + elif isinstance(end_location, int): + end_location = SourceLocation.from_offset(self, f, end_location) + + assert isinstance(start_location, SourceLocation) + assert isinstance(end_location, SourceLocation) + + return SourceRange.from_locations(start_location, end_location) + @property def diagnostics(self): """ @@ -1675,17 +2068,17 @@ class TranslationUnit(ClangObject): self.tu = tu def __len__(self): - return int(_clang_getNumDiagnostics(self.tu)) + return int(lib.clang_getNumDiagnostics(self.tu)) def __getitem__(self, key): - diag = _clang_getDiagnostic(self.tu, key) + diag = lib.clang_getDiagnostic(self.tu, key) if not diag: raise IndexError return Diagnostic(diag) return DiagIterator(self) - def reparse(self, unsaved_files = [], options = 0): + def reparse(self, unsaved_files=None, options=0): """ Reparse an already parsed translation unit. @@ -1694,6 +2087,9 @@ class TranslationUnit(ClangObject): and the second should be the contents to be substituted for the file. The contents may be passed as strings or file objects. """ + if unsaved_files is None: + unsaved_files = [] + unsaved_files_array = 0 if len(unsaved_files): unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() @@ -1708,10 +2104,31 @@ class TranslationUnit(ClangObject): unsaved_files_array[i].name = name unsaved_files_array[i].contents = value unsaved_files_array[i].length = len(value) - ptr = TranslationUnit_reparse(self, len(unsaved_files), - unsaved_files_array, - options) - def codeComplete(self, path, line, column, unsaved_files = [], options = 0): + ptr = lib.clang_reparseTranslationUnit(self, len(unsaved_files), + unsaved_files_array, options) + + def save(self, filename): + """Saves the TranslationUnit to a file. + + This is equivalent to passing -emit-ast to the clang frontend. The + saved file can be loaded back into a TranslationUnit. Or, if it + corresponds to a header, it can be used as a pre-compiled header file. + + If an error occurs while saving, a TranslationUnitSaveError is raised. + If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means + the constructed TranslationUnit was not valid at time of save. In this + case, the reason(s) why should be available via + TranslationUnit.diagnostics(). + + filename -- The path to save the translation unit to. + """ + options = lib.clang_defaultSaveOptions(self) + result = int(lib.clang_saveTranslationUnit(self, filename, options)) + if result != 0: + raise TranslationUnitSaveError(result, + 'Error saving TranslationUnit.') + + def codeComplete(self, path, line, column, unsaved_files=None, options=0): """ Code complete in this translation unit. @@ -1720,6 +2137,9 @@ class TranslationUnit(ClangObject): and the second should be the contents to be substituted for the file. The contents may be passed as strings or file objects. """ + if unsaved_files is None: + unsaved_files = [] + unsaved_files_array = 0 if len(unsaved_files): unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() @@ -1734,15 +2154,25 @@ class TranslationUnit(ClangObject): unsaved_files_array[i].name = name unsaved_files_array[i].contents = value unsaved_files_array[i].length = len(value) - ptr = TranslationUnit_codeComplete(self, path, - line, column, - unsaved_files_array, - len(unsaved_files), - options) + ptr = lib.clang_codeCompleteAt(self, path, line, column, + unsaved_files_array, len(unsaved_files), options) if ptr: return CodeCompletionResults(ptr) return None + def get_tokens(self, locations=None, extent=None): + """Obtain tokens in this translation unit. + + This is a generator for Token instances. The caller specifies a range + of source code to obtain tokens for. The range can be specified as a + 2-tuple of SourceLocation or as a SourceRange. If both are defined, + behavior is undefined. + """ + if locations is not None: + extent = SourceRange(start=locations[0], end=locations[1]) + + return TokenGroup.get_tokens(self, extent) + class File(ClangObject): """ The File class represents a particular source file that is part of a @@ -1752,17 +2182,17 @@ class File(ClangObject): @staticmethod def from_name(translation_unit, file_name): """Retrieve a file handle within the given translation unit.""" - return File(File_getFile(translation_unit, file_name)) + return File(lib.clang_getFile(translation_unit, file_name)) @property def name(self): """Return the complete file and path name of the file.""" - return _CXString_getCString(File_name(self)) + return lib.clang_getCString(lib.clang_getFileName(self)) @property def time(self): """Return the last modification time of the file.""" - return File_time(self) + return lib.clang_getFileTime(self) def __str__(self): return self.name @@ -1770,6 +2200,14 @@ class File(ClangObject): def __repr__(self): return "" % (self.name) + @staticmethod + def from_cursor_result(res, fn, args): + assert isinstance(res, File) + + # Copy a reference to the TranslationUnit to prevent premature GC. + res._tu = args[0]._tu + return res + class FileInclusion(object): """ The FileInclusion class represents the inclusion of one source file by @@ -1790,337 +2228,616 @@ class FileInclusion(object): """True if the included file is the input file.""" return self.depth == 0 -# Additional Functions and Types +class CompilationDatabaseError(Exception): + """Represents an error that occurred when working with a CompilationDatabase -# String Functions -_CXString_dispose = lib.clang_disposeString -_CXString_dispose.argtypes = [_CXString] + Each error is associated to an enumerated value, accessible under + e.cdb_error. Consumers can compare the value with one of the ERROR_ + constants in this class. + """ -_CXString_getCString = lib.clang_getCString -_CXString_getCString.argtypes = [_CXString] -_CXString_getCString.restype = c_char_p + # An unknown error occured + ERROR_UNKNOWN = 0 -# Source Location Functions -SourceLocation_loc = lib.clang_getInstantiationLocation -SourceLocation_loc.argtypes = [SourceLocation, POINTER(c_object_p), - POINTER(c_uint), POINTER(c_uint), - POINTER(c_uint)] - -SourceLocation_getLocation = lib.clang_getLocation -SourceLocation_getLocation.argtypes = [TranslationUnit, File, c_uint, c_uint] -SourceLocation_getLocation.restype = SourceLocation - -SourceLocation_equalLocations = lib.clang_equalLocations -SourceLocation_equalLocations.argtypes = [SourceLocation, SourceLocation] -SourceLocation_equalLocations.restype = bool - -# Source Range Functions -SourceRange_getRange = lib.clang_getRange -SourceRange_getRange.argtypes = [SourceLocation, SourceLocation] -SourceRange_getRange.restype = SourceRange - -SourceRange_start = lib.clang_getRangeStart -SourceRange_start.argtypes = [SourceRange] -SourceRange_start.restype = SourceLocation - -SourceRange_end = lib.clang_getRangeEnd -SourceRange_end.argtypes = [SourceRange] -SourceRange_end.restype = SourceLocation - -SourceRange_equalRanges = lib.clang_equalRanges -SourceRange_equalRanges.argtypes = [SourceRange, SourceRange] -SourceRange_equalRanges.restype = bool - -# CursorKind Functions -CursorKind_is_decl = lib.clang_isDeclaration -CursorKind_is_decl.argtypes = [CursorKind] -CursorKind_is_decl.restype = bool - -CursorKind_is_ref = lib.clang_isReference -CursorKind_is_ref.argtypes = [CursorKind] -CursorKind_is_ref.restype = bool - -CursorKind_is_expr = lib.clang_isExpression -CursorKind_is_expr.argtypes = [CursorKind] -CursorKind_is_expr.restype = bool - -CursorKind_is_stmt = lib.clang_isStatement -CursorKind_is_stmt.argtypes = [CursorKind] -CursorKind_is_stmt.restype = bool - -CursorKind_is_attribute = lib.clang_isAttribute -CursorKind_is_attribute.argtypes = [CursorKind] -CursorKind_is_attribute.restype = bool - -CursorKind_is_inv = lib.clang_isInvalid -CursorKind_is_inv.argtypes = [CursorKind] -CursorKind_is_inv.restype = bool - -CursorKind_is_translation_unit = lib.clang_isTranslationUnit -CursorKind_is_translation_unit.argtypes = [CursorKind] -CursorKind_is_translation_unit.restype = bool - -CursorKind_is_preprocessing = lib.clang_isPreprocessing -CursorKind_is_preprocessing.argtypes = [CursorKind] -CursorKind_is_preprocessing.restype = bool - -CursorKind_is_unexposed = lib.clang_isUnexposed -CursorKind_is_unexposed.argtypes = [CursorKind] -CursorKind_is_unexposed.restype = bool - -# Cursor Functions -# TODO: Implement this function -Cursor_get = lib.clang_getCursor -Cursor_get.argtypes = [TranslationUnit, SourceLocation] -Cursor_get.restype = Cursor - -Cursor_null = lib.clang_getNullCursor -Cursor_null.restype = Cursor - -Cursor_usr = lib.clang_getCursorUSR -Cursor_usr.argtypes = [Cursor] -Cursor_usr.restype = _CXString -Cursor_usr.errcheck = _CXString.from_result - -Cursor_is_def = lib.clang_isCursorDefinition -Cursor_is_def.argtypes = [Cursor] -Cursor_is_def.restype = bool - -Cursor_def = lib.clang_getCursorDefinition -Cursor_def.argtypes = [Cursor] -Cursor_def.restype = Cursor -Cursor_def.errcheck = Cursor.from_result - -Cursor_eq = lib.clang_equalCursors -Cursor_eq.argtypes = [Cursor, Cursor] -Cursor_eq.restype = bool - -Cursor_hash = lib.clang_hashCursor -Cursor_hash.argtypes = [Cursor] -Cursor_hash.restype = c_uint - -Cursor_spelling = lib.clang_getCursorSpelling -Cursor_spelling.argtypes = [Cursor] -Cursor_spelling.restype = _CXString -Cursor_spelling.errcheck = _CXString.from_result - -Cursor_displayname = lib.clang_getCursorDisplayName -Cursor_displayname.argtypes = [Cursor] -Cursor_displayname.restype = _CXString -Cursor_displayname.errcheck = _CXString.from_result - -Cursor_loc = lib.clang_getCursorLocation -Cursor_loc.argtypes = [Cursor] -Cursor_loc.restype = SourceLocation - -Cursor_extent = lib.clang_getCursorExtent -Cursor_extent.argtypes = [Cursor] -Cursor_extent.restype = SourceRange - -Cursor_ref = lib.clang_getCursorReferenced -Cursor_ref.argtypes = [Cursor] -Cursor_ref.restype = Cursor -Cursor_ref.errcheck = Cursor.from_result - -Cursor_type = lib.clang_getCursorType -Cursor_type.argtypes = [Cursor] -Cursor_type.restype = Type -Cursor_type.errcheck = Type.from_result - -Cursor_underlying_type = lib.clang_getTypedefDeclUnderlyingType -Cursor_underlying_type.argtypes = [Cursor] -Cursor_underlying_type.restype = Type -Cursor_underlying_type.errcheck = Type.from_result - -Cursor_enum_type = lib.clang_getEnumDeclIntegerType -Cursor_enum_type.argtypes = [Cursor] -Cursor_enum_type.restype = Type -Cursor_enum_type.errcheck = Type.from_result - -Cursor_objc_type_encoding = lib.clang_getDeclObjCTypeEncoding -Cursor_objc_type_encoding.argtypes = [Cursor] -Cursor_objc_type_encoding.restype = _CXString -Cursor_objc_type_encoding.errcheck = _CXString.from_result - -Cursor_visit_callback = CFUNCTYPE(c_int, Cursor, Cursor, py_object) -Cursor_visit = lib.clang_visitChildren -Cursor_visit.argtypes = [Cursor, Cursor_visit_callback, py_object] -Cursor_visit.restype = c_uint - -# Type Functions -Type_get_canonical = lib.clang_getCanonicalType -Type_get_canonical.argtypes = [Type] -Type_get_canonical.restype = Type -Type_get_canonical.errcheck = Type.from_result - -Type_is_const_qualified = lib.clang_isConstQualifiedType -Type_is_const_qualified.argtypes = [Type] -Type_is_const_qualified.restype = bool - -Type_is_volatile_qualified = lib.clang_isVolatileQualifiedType -Type_is_volatile_qualified.argtypes = [Type] -Type_is_volatile_qualified.restype = bool - -Type_is_restrict_qualified = lib.clang_isRestrictQualifiedType -Type_is_restrict_qualified.argtypes = [Type] -Type_is_restrict_qualified.restype = bool - -Type_is_pod = lib.clang_isPODType -Type_is_pod.argtypes = [Type] -Type_is_pod.restype = bool - -Type_is_variadic = lib.clang_isFunctionTypeVariadic -Type_is_variadic.argtypes = [Type] -Type_is_variadic.restype = bool - -Type_get_pointee = lib.clang_getPointeeType -Type_get_pointee.argtypes = [Type] -Type_get_pointee.restype = Type -Type_get_pointee.errcheck = Type.from_result - -Type_get_declaration = lib.clang_getTypeDeclaration -Type_get_declaration.argtypes = [Type] -Type_get_declaration.restype = Cursor -Type_get_declaration.errcheck = Cursor.from_result - -Type_get_result = lib.clang_getResultType -Type_get_result.argtypes = [Type] -Type_get_result.restype = Type -Type_get_result.errcheck = Type.from_result - -Type_get_num_arg_types = lib.clang_getNumArgTypes -Type_get_num_arg_types.argtypes = [Type] -Type_get_num_arg_types.restype = c_uint - -Type_get_arg_type = lib.clang_getArgType -Type_get_arg_type.argtypes = [Type, c_uint] -Type_get_arg_type.restype = Type -Type_get_arg_type.errcheck = Type.from_result -Type_get_element_type = lib.clang_getElementType - -Type_get_element_type.argtypes = [Type] -Type_get_element_type.restype = Type -Type_get_element_type.errcheck = Type.from_result - -Type_get_num_elements = lib.clang_getNumElements -Type_get_num_elements.argtypes = [Type] -Type_get_num_elements.restype = c_longlong - -Type_get_array_element = lib.clang_getArrayElementType -Type_get_array_element.argtypes = [Type] -Type_get_array_element.restype = Type -Type_get_array_element.errcheck = Type.from_result - -Type_get_array_size = lib.clang_getArraySize -Type_get_array_size.argtype = [Type] -Type_get_array_size.restype = c_longlong - -Type_equal = lib.clang_equalTypes -Type_equal.argtypes = [Type, Type] -Type_equal.restype = bool - -# Index Functions -Index_create = lib.clang_createIndex -Index_create.argtypes = [c_int, c_int] -Index_create.restype = c_object_p - -Index_dispose = lib.clang_disposeIndex -Index_dispose.argtypes = [Index] - -# Translation Unit Functions -TranslationUnit_read = lib.clang_createTranslationUnit -TranslationUnit_read.argtypes = [Index, c_char_p] -TranslationUnit_read.restype = c_object_p - -TranslationUnit_parse = lib.clang_parseTranslationUnit -TranslationUnit_parse.argtypes = [Index, c_char_p, c_void_p, - c_int, c_void_p, c_int, c_int] -TranslationUnit_parse.restype = c_object_p - -TranslationUnit_reparse = lib.clang_reparseTranslationUnit -TranslationUnit_reparse.argtypes = [TranslationUnit, c_int, c_void_p, c_int] -TranslationUnit_reparse.restype = c_int - -TranslationUnit_codeComplete = lib.clang_codeCompleteAt -TranslationUnit_codeComplete.argtypes = [TranslationUnit, c_char_p, c_int, - c_int, c_void_p, c_int, c_int] -TranslationUnit_codeComplete.restype = POINTER(CCRStructure) - -TranslationUnit_cursor = lib.clang_getTranslationUnitCursor -TranslationUnit_cursor.argtypes = [TranslationUnit] -TranslationUnit_cursor.restype = Cursor -TranslationUnit_cursor.errcheck = Cursor.from_result - -TranslationUnit_spelling = lib.clang_getTranslationUnitSpelling -TranslationUnit_spelling.argtypes = [TranslationUnit] -TranslationUnit_spelling.restype = _CXString -TranslationUnit_spelling.errcheck = _CXString.from_result - -TranslationUnit_dispose = lib.clang_disposeTranslationUnit -TranslationUnit_dispose.argtypes = [TranslationUnit] - -TranslationUnit_includes_callback = CFUNCTYPE(None, - c_object_p, - POINTER(SourceLocation), - c_uint, py_object) -TranslationUnit_includes = lib.clang_getInclusions -TranslationUnit_includes.argtypes = [TranslationUnit, - TranslationUnit_includes_callback, - py_object] - -# File Functions -File_getFile = lib.clang_getFile -File_getFile.argtypes = [TranslationUnit, c_char_p] -File_getFile.restype = c_object_p - -File_name = lib.clang_getFileName -File_name.argtypes = [File] -File_name.restype = _CXString - -File_time = lib.clang_getFileTime -File_time.argtypes = [File] -File_time.restype = c_uint - -# Code completion - -CodeCompletionResults_dispose = lib.clang_disposeCodeCompleteResults -CodeCompletionResults_dispose.argtypes = [CodeCompletionResults] - -_clang_codeCompleteGetNumDiagnostics = lib.clang_codeCompleteGetNumDiagnostics -_clang_codeCompleteGetNumDiagnostics.argtypes = [CodeCompletionResults] -_clang_codeCompleteGetNumDiagnostics.restype = c_int - -_clang_codeCompleteGetDiagnostic = lib.clang_codeCompleteGetDiagnostic -_clang_codeCompleteGetDiagnostic.argtypes = [CodeCompletionResults, c_int] -_clang_codeCompleteGetDiagnostic.restype = Diagnostic - -_clang_getCompletionChunkText = lib.clang_getCompletionChunkText -_clang_getCompletionChunkText.argtypes = [c_void_p, c_int] -_clang_getCompletionChunkText.restype = _CXString + # The database could not be loaded + ERROR_CANNOTLOADDATABASE = 1 -_clang_getCompletionChunkKind = lib.clang_getCompletionChunkKind -_clang_getCompletionChunkKind.argtypes = [c_void_p, c_int] -_clang_getCompletionChunkKind.restype = c_int + def __init__(self, enumeration, message): + assert isinstance(enumeration, int) -_clang_getCompletionChunkCompletionString = lib.clang_getCompletionChunkCompletionString -_clang_getCompletionChunkCompletionString.argtypes = [c_void_p, c_int] -_clang_getCompletionChunkCompletionString.restype = c_object_p + if enumeration > 1: + raise Exception("Encountered undefined CompilationDatabase error " + "constant: %d. Please file a bug to have this " + "value supported." % enumeration) -_clang_getNumCompletionChunks = lib.clang_getNumCompletionChunks -_clang_getNumCompletionChunks.argtypes = [c_void_p] -_clang_getNumCompletionChunks.restype = c_int + self.cdb_error = enumeration + Exception.__init__(self, 'Error %d: %s' % (enumeration, message)) -_clang_getCompletionAvailability = lib.clang_getCompletionAvailability -_clang_getCompletionAvailability.argtypes = [c_void_p] -_clang_getCompletionAvailability.restype = c_int +class CompileCommand(object): + """Represents the compile command used to build a file""" + def __init__(self, cmd, ccmds): + self.cmd = cmd + # Keep a reference to the originating CompileCommands + # to prevent garbage collection + self.ccmds = ccmds -_clang_getCompletionPriority = lib.clang_getCompletionPriority -_clang_getCompletionPriority.argtypes = [c_void_p] -_clang_getCompletionPriority.restype = c_int + @property + def directory(self): + """Get the working directory for this CompileCommand""" + return lib.clang_CompileCommand_getDirectory(self.cmd) + @property + def arguments(self): + """ + Get an iterable object providing each argument in the + command line for the compiler invocation as a _CXString. -### + Invariant : the first argument is the compiler executable + """ + length = lib.clang_CompileCommand_getNumArgs(self.cmd) + for i in xrange(length): + yield lib.clang_CompileCommand_getArg(self.cmd, i) + +class CompileCommands(object): + """ + CompileCommands is an iterable object containing all CompileCommand + that can be used for building a specific file. + """ + def __init__(self, ccmds): + self.ccmds = ccmds + + def __del__(self): + lib.clang_CompileCommands_dispose(self.ccmds) + + def __len__(self): + return int(lib.clang_CompileCommands_getSize(self.ccmds)) + + def __getitem__(self, i): + cc = lib.clang_CompileCommands_getCommand(self.ccmds, i) + if not cc: + raise IndexError + return CompileCommand(cc, self) + + @staticmethod + def from_result(res, fn, args): + if not res: + return None + return CompileCommands(res) + +class CompilationDatabase(ClangObject): + """ + The CompilationDatabase is a wrapper class around + clang::tooling::CompilationDatabase + + It enables querying how a specific source file can be built. + """ + + def __del__(self): + lib.clang_CompilationDatabase_dispose(self) + + @staticmethod + def from_result(res, fn, args): + if not res: + raise CompilationDatabaseError(0, + "CompilationDatabase loading failed") + return CompilationDatabase(res) + + @staticmethod + def fromDirectory(buildDir): + """Builds a CompilationDatabase from the database found in buildDir""" + errorCode = c_uint() + try: + cdb = lib.clang_CompilationDatabase_fromDirectory(buildDir, + byref(errorCode)) + except CompilationDatabaseError as e: + raise CompilationDatabaseError(int(errorCode.value), + "CompilationDatabase loading failed") + return cdb + + def getCompileCommands(self, filename): + """ + Get an iterable object providing all the CompileCommands available to + build filename. Returns None if filename is not found in the database. + """ + return lib.clang_CompilationDatabase_getCompileCommands(self, filename) + +class Token(Structure): + """Represents a single token from the preprocessor. + + Tokens are effectively segments of source code. Source code is first parsed + into tokens before being converted into the AST and Cursors. + + Tokens are obtained from parsed TranslationUnit instances. You currently + can't create tokens manually. + """ + _fields_ = [ + ('int_data', c_uint * 4), + ('ptr_data', c_void_p) + ] + + @property + def spelling(self): + """The spelling of this token. + + This is the textual representation of the token in source. + """ + return lib.clang_getTokenSpelling(self._tu, self) + + @property + def kind(self): + """Obtain the TokenKind of the current token.""" + return TokenKind.from_value(lib.clang_getTokenKind(self)) + + @property + def location(self): + """The SourceLocation this Token occurs at.""" + return lib.clang_getTokenLocation(self._tu, self) + + @property + def extent(self): + """The SourceRange this Token occupies.""" + return lib.clang_getTokenExtent(self._tu, self) + + @property + def cursor(self): + """The Cursor this Token corresponds to.""" + cursor = Cursor() + + lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor)) + + return cursor + +# Now comes the plumbing to hook up the C library. + +# Register callback types in common container. +callbacks['translation_unit_includes'] = CFUNCTYPE(None, c_object_p, + POINTER(SourceLocation), c_uint, py_object) +callbacks['cursor_visit'] = CFUNCTYPE(c_int, Cursor, Cursor, py_object) + +def register_functions(lib): + """Register function prototypes with a libclang library instance. + + This must be called as part of library instantiation so Python knows how + to call out to the shared library. + """ + # Functions are registered in strictly alphabetical order. + lib.clang_annotateTokens.argtype = [TranslationUnit, POINTER(Token), + c_uint, POINTER(Cursor)] + + lib.clang_CompilationDatabase_dispose.argtypes = [c_object_p] + + lib.clang_CompilationDatabase_fromDirectory.argtypes = [c_char_p, + POINTER(c_uint)] + lib.clang_CompilationDatabase_fromDirectory.restype = c_object_p + lib.clang_CompilationDatabase_fromDirectory.errcheck = CompilationDatabase.from_result + + lib.clang_CompilationDatabase_getCompileCommands.argtypes = [c_object_p, c_char_p] + lib.clang_CompilationDatabase_getCompileCommands.restype = c_object_p + lib.clang_CompilationDatabase_getCompileCommands.errcheck = CompileCommands.from_result + + lib.clang_CompileCommands_dispose.argtypes = [c_object_p] + + lib.clang_CompileCommands_getCommand.argtypes = [c_object_p, c_uint] + lib.clang_CompileCommands_getCommand.restype = c_object_p + + lib.clang_CompileCommands_getSize.argtypes = [c_object_p] + lib.clang_CompileCommands_getSize.restype = c_uint + + lib.clang_CompileCommand_getArg.argtypes = [c_object_p, c_uint] + lib.clang_CompileCommand_getArg.restype = _CXString + lib.clang_CompileCommand_getArg.errcheck = _CXString.from_result + + lib.clang_CompileCommand_getDirectory.argtypes = [c_object_p] + lib.clang_CompileCommand_getDirectory.restype = _CXString + lib.clang_CompileCommand_getDirectory.errcheck = _CXString.from_result + + lib.clang_CompileCommand_getNumArgs.argtypes = [c_object_p] + lib.clang_CompileCommand_getNumArgs.restype = c_uint + + lib.clang_codeCompleteAt.argtypes = [TranslationUnit, c_char_p, c_int, + c_int, c_void_p, c_int, c_int] + lib.clang_codeCompleteAt.restype = POINTER(CCRStructure) + + lib.clang_codeCompleteGetDiagnostic.argtypes = [CodeCompletionResults, + c_int] + lib.clang_codeCompleteGetDiagnostic.restype = Diagnostic + + lib.clang_codeCompleteGetNumDiagnostics.argtypes = [CodeCompletionResults] + lib.clang_codeCompleteGetNumDiagnostics.restype = c_int + + lib.clang_createIndex.argtypes = [c_int, c_int] + lib.clang_createIndex.restype = c_object_p + + lib.clang_createTranslationUnit.argtypes = [Index, c_char_p] + lib.clang_createTranslationUnit.restype = c_object_p + + lib.clang_CXXMethod_isStatic.argtypes = [Cursor] + lib.clang_CXXMethod_isStatic.restype = bool + + lib.clang_CXXMethod_isVirtual.argtypes = [Cursor] + lib.clang_CXXMethod_isVirtual.restype = bool + + lib.clang_defaultSaveOptions.argtypes = [TranslationUnit] + lib.clang_defaultSaveOptions.restype = c_uint + + lib.clang_disposeCodeCompleteResults.argtypes = [CodeCompletionResults] + + #lib.clang_disposeCXTUResourceUsage.argtypes = [CXTUResourceUsage] + + lib.clang_disposeDiagnostic.argtypes = [Diagnostic] + + lib.clang_disposeIndex.argtypes = [Index] + + lib.clang_disposeString.argtypes = [_CXString] + + lib.clang_disposeTokens.argtype = [TranslationUnit, POINTER(Token), c_uint] + + lib.clang_disposeTranslationUnit.argtypes = [TranslationUnit] + + lib.clang_equalCursors.argtypes = [Cursor, Cursor] + lib.clang_equalCursors.restype = bool + + lib.clang_equalLocations.argtypes = [SourceLocation, SourceLocation] + lib.clang_equalLocations.restype = bool + + lib.clang_equalRanges.argtypes = [SourceRange, SourceRange] + lib.clang_equalRanges.restype = bool + + lib.clang_equalTypes.argtypes = [Type, Type] + lib.clang_equalTypes.restype = bool + + lib.clang_getArgType.argtypes = [Type, c_uint] + lib.clang_getArgType.restype = Type + lib.clang_getArgType.errcheck = Type.from_result + + lib.clang_getArrayElementType.argtypes = [Type] + lib.clang_getArrayElementType.restype = Type + lib.clang_getArrayElementType.errcheck = Type.from_result + + lib.clang_getArraySize.argtypes = [Type] + lib.clang_getArraySize.restype = c_longlong + + lib.clang_getCanonicalCursor.argtypes = [Cursor] + lib.clang_getCanonicalCursor.restype = Cursor + lib.clang_getCanonicalCursor.errcheck = Cursor.from_cursor_result + + lib.clang_getCanonicalType.argtypes = [Type] + lib.clang_getCanonicalType.restype = Type + lib.clang_getCanonicalType.errcheck = Type.from_result + + lib.clang_getCompletionAvailability.argtypes = [c_void_p] + lib.clang_getCompletionAvailability.restype = c_int + + lib.clang_getCompletionChunkCompletionString.argtypes = [c_void_p, c_int] + lib.clang_getCompletionChunkCompletionString.restype = c_object_p + + lib.clang_getCompletionChunkKind.argtypes = [c_void_p, c_int] + lib.clang_getCompletionChunkKind.restype = c_int + + lib.clang_getCompletionChunkText.argtypes = [c_void_p, c_int] + lib.clang_getCompletionChunkText.restype = _CXString + + lib.clang_getCompletionPriority.argtypes = [c_void_p] + lib.clang_getCompletionPriority.restype = c_int + + lib.clang_getCString.argtypes = [_CXString] + lib.clang_getCString.restype = c_char_p + + lib.clang_getCursor.argtypes = [TranslationUnit, SourceLocation] + lib.clang_getCursor.restype = Cursor + + lib.clang_getCursorDefinition.argtypes = [Cursor] + lib.clang_getCursorDefinition.restype = Cursor + lib.clang_getCursorDefinition.errcheck = Cursor.from_result + + lib.clang_getCursorDisplayName.argtypes = [Cursor] + lib.clang_getCursorDisplayName.restype = _CXString + lib.clang_getCursorDisplayName.errcheck = _CXString.from_result + + lib.clang_getCursorExtent.argtypes = [Cursor] + lib.clang_getCursorExtent.restype = SourceRange + + lib.clang_getCursorLexicalParent.argtypes = [Cursor] + lib.clang_getCursorLexicalParent.restype = Cursor + lib.clang_getCursorLexicalParent.errcheck = Cursor.from_cursor_result + + lib.clang_getCursorLocation.argtypes = [Cursor] + lib.clang_getCursorLocation.restype = SourceLocation + + lib.clang_getCursorReferenced.argtypes = [Cursor] + lib.clang_getCursorReferenced.restype = Cursor + lib.clang_getCursorReferenced.errcheck = Cursor.from_result + + lib.clang_getCursorReferenceNameRange.argtypes = [Cursor, c_uint, c_uint] + lib.clang_getCursorReferenceNameRange.restype = SourceRange + + lib.clang_getCursorSemanticParent.argtypes = [Cursor] + lib.clang_getCursorSemanticParent.restype = Cursor + lib.clang_getCursorSemanticParent.errcheck = Cursor.from_cursor_result + + lib.clang_getCursorSpelling.argtypes = [Cursor] + lib.clang_getCursorSpelling.restype = _CXString + lib.clang_getCursorSpelling.errcheck = _CXString.from_result + + lib.clang_getCursorType.argtypes = [Cursor] + lib.clang_getCursorType.restype = Type + lib.clang_getCursorType.errcheck = Type.from_result + + lib.clang_getCursorUSR.argtypes = [Cursor] + lib.clang_getCursorUSR.restype = _CXString + lib.clang_getCursorUSR.errcheck = _CXString.from_result + + #lib.clang_getCXTUResourceUsage.argtypes = [TranslationUnit] + #lib.clang_getCXTUResourceUsage.restype = CXTUResourceUsage + + lib.clang_getCXXAccessSpecifier.argtypes = [Cursor] + lib.clang_getCXXAccessSpecifier.restype = c_uint + + lib.clang_getDeclObjCTypeEncoding.argtypes = [Cursor] + lib.clang_getDeclObjCTypeEncoding.restype = _CXString + lib.clang_getDeclObjCTypeEncoding.errcheck = _CXString.from_result + + lib.clang_getDiagnostic.argtypes = [c_object_p, c_uint] + lib.clang_getDiagnostic.restype = c_object_p + + lib.clang_getDiagnosticCategory.argtypes = [Diagnostic] + lib.clang_getDiagnosticCategory.restype = c_uint + + lib.clang_getDiagnosticCategoryName.argtypes = [c_uint] + lib.clang_getDiagnosticCategoryName.restype = _CXString + lib.clang_getDiagnosticCategoryName.errcheck = _CXString.from_result + + lib.clang_getDiagnosticFixIt.argtypes = [Diagnostic, c_uint, + POINTER(SourceRange)] + lib.clang_getDiagnosticFixIt.restype = _CXString + lib.clang_getDiagnosticFixIt.errcheck = _CXString.from_result + + lib.clang_getDiagnosticLocation.argtypes = [Diagnostic] + lib.clang_getDiagnosticLocation.restype = SourceLocation + + lib.clang_getDiagnosticNumFixIts.argtypes = [Diagnostic] + lib.clang_getDiagnosticNumFixIts.restype = c_uint + + lib.clang_getDiagnosticNumRanges.argtypes = [Diagnostic] + lib.clang_getDiagnosticNumRanges.restype = c_uint + + lib.clang_getDiagnosticOption.argtypes = [Diagnostic, POINTER(_CXString)] + lib.clang_getDiagnosticOption.restype = _CXString + lib.clang_getDiagnosticOption.errcheck = _CXString.from_result + + lib.clang_getDiagnosticRange.argtypes = [Diagnostic, c_uint] + lib.clang_getDiagnosticRange.restype = SourceRange + + lib.clang_getDiagnosticSeverity.argtypes = [Diagnostic] + lib.clang_getDiagnosticSeverity.restype = c_int + + lib.clang_getDiagnosticSpelling.argtypes = [Diagnostic] + lib.clang_getDiagnosticSpelling.restype = _CXString + lib.clang_getDiagnosticSpelling.errcheck = _CXString.from_result + + lib.clang_getElementType.argtypes = [Type] + lib.clang_getElementType.restype = Type + lib.clang_getElementType.errcheck = Type.from_result + + lib.clang_getEnumConstantDeclUnsignedValue.argtypes = [Cursor] + lib.clang_getEnumConstantDeclUnsignedValue.restype = c_ulonglong + + lib.clang_getEnumConstantDeclValue.argtypes = [Cursor] + lib.clang_getEnumConstantDeclValue.restype = c_longlong + + lib.clang_getEnumDeclIntegerType.argtypes = [Cursor] + lib.clang_getEnumDeclIntegerType.restype = Type + lib.clang_getEnumDeclIntegerType.errcheck = Type.from_result + + lib.clang_getFile.argtypes = [TranslationUnit, c_char_p] + lib.clang_getFile.restype = c_object_p + + lib.clang_getFileName.argtypes = [File] + lib.clang_getFileName.restype = _CXString + # TODO go through _CXString.from_result? + + lib.clang_getFileTime.argtypes = [File] + lib.clang_getFileTime.restype = c_uint + + lib.clang_getIBOutletCollectionType.argtypes = [Cursor] + lib.clang_getIBOutletCollectionType.restype = Type + lib.clang_getIBOutletCollectionType.errcheck = Type.from_result + + lib.clang_getIncludedFile.argtypes = [Cursor] + lib.clang_getIncludedFile.restype = File + lib.clang_getIncludedFile.errcheck = File.from_cursor_result + + lib.clang_getInclusions.argtypes = [TranslationUnit, + callbacks['translation_unit_includes'], py_object] + + lib.clang_getInstantiationLocation.argtypes = [SourceLocation, + POINTER(c_object_p), POINTER(c_uint), POINTER(c_uint), POINTER(c_uint)] + + lib.clang_getLocation.argtypes = [TranslationUnit, File, c_uint, c_uint] + lib.clang_getLocation.restype = SourceLocation + + lib.clang_getLocationForOffset.argtypes = [TranslationUnit, File, c_uint] + lib.clang_getLocationForOffset.restype = SourceLocation + + lib.clang_getNullCursor.restype = Cursor + + lib.clang_getNumArgTypes.argtypes = [Type] + lib.clang_getNumArgTypes.restype = c_uint + + lib.clang_getNumCompletionChunks.argtypes = [c_void_p] + lib.clang_getNumCompletionChunks.restype = c_int + + lib.clang_getNumDiagnostics.argtypes = [c_object_p] + lib.clang_getNumDiagnostics.restype = c_uint + + lib.clang_getNumElements.argtypes = [Type] + lib.clang_getNumElements.restype = c_longlong + + lib.clang_getNumOverloadedDecls.argtypes = [Cursor] + lib.clang_getNumOverloadedDecls.restyp = c_uint + + lib.clang_getOverloadedDecl.argtypes = [Cursor, c_uint] + lib.clang_getOverloadedDecl.restype = Cursor + lib.clang_getOverloadedDecl.errcheck = Cursor.from_cursor_result + + lib.clang_getPointeeType.argtypes = [Type] + lib.clang_getPointeeType.restype = Type + lib.clang_getPointeeType.errcheck = Type.from_result + + lib.clang_getRange.argtypes = [SourceLocation, SourceLocation] + lib.clang_getRange.restype = SourceRange + + lib.clang_getRangeEnd.argtypes = [SourceRange] + lib.clang_getRangeEnd.restype = SourceLocation + + lib.clang_getRangeStart.argtypes = [SourceRange] + lib.clang_getRangeStart.restype = SourceLocation + + lib.clang_getResultType.argtypes = [Type] + lib.clang_getResultType.restype = Type + lib.clang_getResultType.errcheck = Type.from_result + + lib.clang_getSpecializedCursorTemplate.argtypes = [Cursor] + lib.clang_getSpecializedCursorTemplate.restype = Cursor + lib.clang_getSpecializedCursorTemplate.errcheck = Cursor.from_cursor_result + + lib.clang_getTemplateCursorKind.argtypes = [Cursor] + lib.clang_getTemplateCursorKind.restype = c_uint + + lib.clang_getTokenExtent.argtypes = [TranslationUnit, Token] + lib.clang_getTokenExtent.restype = SourceRange + + lib.clang_getTokenKind.argtypes = [Token] + lib.clang_getTokenKind.restype = c_uint + + lib.clang_getTokenLocation.argtype = [TranslationUnit, Token] + lib.clang_getTokenLocation.restype = SourceLocation + + lib.clang_getTokenSpelling.argtype = [TranslationUnit, Token] + lib.clang_getTokenSpelling.restype = _CXString + lib.clang_getTokenSpelling.errcheck = _CXString.from_result + + lib.clang_getTranslationUnitCursor.argtypes = [TranslationUnit] + lib.clang_getTranslationUnitCursor.restype = Cursor + lib.clang_getTranslationUnitCursor.errcheck = Cursor.from_result + + lib.clang_getTranslationUnitSpelling.argtypes = [TranslationUnit] + lib.clang_getTranslationUnitSpelling.restype = _CXString + lib.clang_getTranslationUnitSpelling.errcheck = _CXString.from_result + + lib.clang_getTUResourceUsageName.argtypes = [c_uint] + lib.clang_getTUResourceUsageName.restype = c_char_p + + lib.clang_getTypeDeclaration.argtypes = [Type] + lib.clang_getTypeDeclaration.restype = Cursor + lib.clang_getTypeDeclaration.errcheck = Cursor.from_result + + lib.clang_getTypedefDeclUnderlyingType.argtypes = [Cursor] + lib.clang_getTypedefDeclUnderlyingType.restype = Type + lib.clang_getTypedefDeclUnderlyingType.errcheck = Type.from_result + + lib.clang_getTypeKindSpelling.argtypes = [c_uint] + lib.clang_getTypeKindSpelling.restype = _CXString + lib.clang_getTypeKindSpelling.errcheck = _CXString.from_result + + lib.clang_hashCursor.argtypes = [Cursor] + lib.clang_hashCursor.restype = c_uint + + lib.clang_isAttribute.argtypes = [CursorKind] + lib.clang_isAttribute.restype = bool + + lib.clang_isConstQualifiedType.argtypes = [Type] + lib.clang_isConstQualifiedType.restype = bool + + lib.clang_isCursorDefinition.argtypes = [Cursor] + lib.clang_isCursorDefinition.restype = bool + + lib.clang_isDeclaration.argtypes = [CursorKind] + lib.clang_isDeclaration.restype = bool + + lib.clang_isExpression.argtypes = [CursorKind] + lib.clang_isExpression.restype = bool + + lib.clang_isFileMultipleIncludeGuarded.argtypes = [TranslationUnit, File] + lib.clang_isFileMultipleIncludeGuarded.restype = bool + + lib.clang_isFunctionTypeVariadic.argtypes = [Type] + lib.clang_isFunctionTypeVariadic.restype = bool + + lib.clang_isInvalid.argtypes = [CursorKind] + lib.clang_isInvalid.restype = bool + + lib.clang_isPODType.argtypes = [Type] + lib.clang_isPODType.restype = bool + + lib.clang_isPreprocessing.argtypes = [CursorKind] + lib.clang_isPreprocessing.restype = bool + + lib.clang_isReference.argtypes = [CursorKind] + lib.clang_isReference.restype = bool + + lib.clang_isRestrictQualifiedType.argtypes = [Type] + lib.clang_isRestrictQualifiedType.restype = bool + + lib.clang_isStatement.argtypes = [CursorKind] + lib.clang_isStatement.restype = bool + + lib.clang_isTranslationUnit.argtypes = [CursorKind] + lib.clang_isTranslationUnit.restype = bool + + lib.clang_isUnexposed.argtypes = [CursorKind] + lib.clang_isUnexposed.restype = bool + + lib.clang_isVirtualBase.argtypes = [Cursor] + lib.clang_isVirtualBase.restype = bool + + lib.clang_isVolatileQualifiedType.argtypes = [Type] + lib.clang_isVolatileQualifiedType.restype = bool + + lib.clang_parseTranslationUnit.argypes = [Index, c_char_p, c_void_p, c_int, + c_void_p, c_int, c_int] + lib.clang_parseTranslationUnit.restype = c_object_p + + lib.clang_reparseTranslationUnit.argtypes = [TranslationUnit, c_int, + c_void_p, c_int] + lib.clang_reparseTranslationUnit.restype = c_int + + lib.clang_saveTranslationUnit.argtypes = [TranslationUnit, c_char_p, + c_uint] + lib.clang_saveTranslationUnit.restype = c_int + + lib.clang_tokenize.argtypes = [TranslationUnit, SourceRange, + POINTER(POINTER(Token)), POINTER(c_uint)] + + lib.clang_visitChildren.argtypes = [Cursor, callbacks['cursor_visit'], + py_object] + lib.clang_visitChildren.restype = c_uint + +register_functions(lib) + +def register_enumerations(): + for name, value in clang.enumerations.TokenKinds: + TokenKind.register(value, name) + +register_enumerations() -__all__ = ['Index', 'TranslationUnit', 'Cursor', 'CursorKind', 'Type', 'TypeKind', - 'Diagnostic', 'FixIt', 'CodeCompletionResults', 'SourceRange', - 'SourceLocation', 'File'] +__all__ = [ + 'CodeCompletionResults', + 'CompilationDatabase', + 'CompileCommands', + 'CompileCommand', + 'CursorKind', + 'Cursor', + 'Diagnostic', + 'File', + 'FixIt', + 'Index', + 'SourceLocation', + 'SourceRange', + 'TokenKind', + 'Token', + 'TranslationUnitLoadError', + 'TranslationUnit', + 'TypeKind', + 'Type', +] diff --git a/bindings/python/clang/enumerations.py b/bindings/python/clang/enumerations.py new file mode 100644 index 000000000000..a86a48ade3bd --- /dev/null +++ b/bindings/python/clang/enumerations.py @@ -0,0 +1,34 @@ +#===- enumerations.py - Python Enumerations ------------------*- python -*--===# +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +#===------------------------------------------------------------------------===# + +""" +Clang Enumerations +================== + +This module provides static definitions of enumerations that exist in libclang. + +Enumerations are typically defined as a list of tuples. The exported values are +typically munged into other types or classes at module load time. + +All enumerations are centrally defined in this file so they are all grouped +together and easier to audit. And, maybe even one day this file will be +automatically generated by scanning the libclang headers! +""" + +# Maps to CXTokenKind. Note that libclang maintains a separate set of token +# enumerations from the C++ API. +TokenKinds = [ + ('PUNCTUATION', 0), + ('KEYWORD', 1), + ('IDENTIFIER', 2), + ('LITERAL', 3), + ('COMMENT', 4), +] + +__all__ = ['TokenKinds'] diff --git a/bindings/python/tests/cindex/INPUTS/compile_commands.json b/bindings/python/tests/cindex/INPUTS/compile_commands.json new file mode 100644 index 000000000000..944150bf7ba6 --- /dev/null +++ b/bindings/python/tests/cindex/INPUTS/compile_commands.json @@ -0,0 +1,17 @@ +[ +{ + "directory": "/home/john.doe/MyProject", + "command": "clang++ -o project.o -c /home/john.doe/MyProject/project.cpp", + "file": "/home/john.doe/MyProject/project.cpp" +}, +{ + "directory": "/home/john.doe/MyProjectA", + "command": "clang++ -o project2.o -c /home/john.doe/MyProject/project2.cpp", + "file": "/home/john.doe/MyProject/project2.cpp" +}, +{ + "directory": "/home/john.doe/MyProjectB", + "command": "clang++ -DFEATURE=1 -o project2-feature.o -c /home/john.doe/MyProject/project2.cpp", + "file": "/home/john.doe/MyProject/project2.cpp" +} +] diff --git a/bindings/python/tests/cindex/test_cdb.py b/bindings/python/tests/cindex/test_cdb.py new file mode 100644 index 000000000000..d0f580ea9f47 --- /dev/null +++ b/bindings/python/tests/cindex/test_cdb.py @@ -0,0 +1,89 @@ +from clang.cindex import CompilationDatabase +from clang.cindex import CompilationDatabaseError +from clang.cindex import CompileCommands +from clang.cindex import CompileCommand +import os +import gc + +kInputsDir = os.path.join(os.path.dirname(__file__), 'INPUTS') + +def test_create_fail(): + """Check we fail loading a database with an assertion""" + path = os.path.dirname(__file__) + try: + cdb = CompilationDatabase.fromDirectory(path) + except CompilationDatabaseError as e: + assert e.cdb_error == CompilationDatabaseError.ERROR_CANNOTLOADDATABASE + else: + assert False + +def test_create(): + """Check we can load a compilation database""" + cdb = CompilationDatabase.fromDirectory(kInputsDir) + +def test_lookup_fail(): + """Check file lookup failure""" + cdb = CompilationDatabase.fromDirectory(kInputsDir) + assert cdb.getCompileCommands('file_do_not_exist.cpp') == None + +def test_lookup_succeed(): + """Check we get some results if the file exists in the db""" + cdb = CompilationDatabase.fromDirectory(kInputsDir) + cmds = cdb.getCompileCommands('/home/john.doe/MyProject/project.cpp') + assert len(cmds) != 0 + +def test_1_compilecommand(): + """Check file with single compile command""" + cdb = CompilationDatabase.fromDirectory(kInputsDir) + cmds = cdb.getCompileCommands('/home/john.doe/MyProject/project.cpp') + assert len(cmds) == 1 + assert cmds[0].directory == '/home/john.doe/MyProject' + expected = [ 'clang++', '-o', 'project.o', '-c', + '/home/john.doe/MyProject/project.cpp'] + for arg, exp in zip(cmds[0].arguments, expected): + assert arg == exp + +def test_2_compilecommand(): + """Check file with 2 compile commands""" + cdb = CompilationDatabase.fromDirectory(kInputsDir) + cmds = cdb.getCompileCommands('/home/john.doe/MyProject/project2.cpp') + assert len(cmds) == 2 + expected = [ + { 'wd': '/home/john.doe/MyProjectA', + 'line': ['clang++', '-o', 'project2.o', '-c', + '/home/john.doe/MyProject/project2.cpp']}, + { 'wd': '/home/john.doe/MyProjectB', + 'line': ['clang++', '-DFEATURE=1', '-o', 'project2-feature.o', '-c', + '/home/john.doe/MyProject/project2.cpp']} + ] + for i in range(len(cmds)): + assert cmds[i].directory == expected[i]['wd'] + for arg, exp in zip(cmds[i].arguments, expected[i]['line']): + assert arg == exp + +def test_compilecommand_iterator_stops(): + """Check that iterator stops after the correct number of elements""" + cdb = CompilationDatabase.fromDirectory(kInputsDir) + count = 0 + for cmd in cdb.getCompileCommands('/home/john.doe/MyProject/project2.cpp'): + count += 1 + assert count <= 2 + +def test_compilationDB_references(): + """Ensure CompilationsCommands are independent of the database""" + cdb = CompilationDatabase.fromDirectory(kInputsDir) + cmds = cdb.getCompileCommands('/home/john.doe/MyProject/project.cpp') + del cdb + gc.collect() + workingdir = cmds[0].directory + +def test_compilationCommands_references(): + """Ensure CompilationsCommand keeps a reference to CompilationCommands""" + cdb = CompilationDatabase.fromDirectory(kInputsDir) + cmds = cdb.getCompileCommands('/home/john.doe/MyProject/project.cpp') + del cdb + cmd0 = cmds[0] + del cmds + gc.collect() + workingdir = cmd0.directory + diff --git a/bindings/python/tests/cindex/test_cursor.py b/bindings/python/tests/cindex/test_cursor.py index 9f02bb2a7686..51695e20b0c7 100644 --- a/bindings/python/tests/cindex/test_cursor.py +++ b/bindings/python/tests/cindex/test_cursor.py @@ -1,6 +1,10 @@ +import gc + from clang.cindex import CursorKind +from clang.cindex import TranslationUnit from clang.cindex import TypeKind from .util import get_cursor +from .util import get_cursors from .util import get_tu kInput = """\ @@ -37,6 +41,8 @@ def test_get_children(): tu_nodes = list(it) assert len(tu_nodes) == 3 + for cursor in tu_nodes: + assert cursor.translation_unit is not None assert tu_nodes[0] != tu_nodes[1] assert tu_nodes[0].kind == CursorKind.STRUCT_DECL @@ -46,6 +52,7 @@ def test_get_children(): assert tu_nodes[0].location.line == 4 assert tu_nodes[0].location.column == 8 assert tu_nodes[0].hash > 0 + assert tu_nodes[0].translation_unit is not None s0_nodes = list(tu_nodes[0].get_children()) assert len(s0_nodes) == 2 @@ -66,6 +73,51 @@ def test_get_children(): assert tu_nodes[2].displayname == 'f0(int, int)' assert tu_nodes[2].is_definition() == True +def test_references(): + """Ensure that references to TranslationUnit are kept.""" + tu = get_tu('int x;') + cursors = list(tu.cursor.get_children()) + assert len(cursors) > 0 + + cursor = cursors[0] + assert isinstance(cursor.translation_unit, TranslationUnit) + + # Delete reference to TU and perform a full GC. + del tu + gc.collect() + assert isinstance(cursor.translation_unit, TranslationUnit) + + # If the TU was destroyed, this should cause a segfault. + parent = cursor.semantic_parent + +def test_canonical(): + source = 'struct X; struct X; struct X { int member; };' + tu = get_tu(source) + + cursors = [] + for cursor in tu.cursor.get_children(): + if cursor.spelling == 'X': + cursors.append(cursor) + + assert len(cursors) == 3 + assert cursors[1].canonical == cursors[2].canonical + +def test_is_static_method(): + """Ensure Cursor.is_static_method works.""" + + source = 'class X { static void foo(); void bar(); };' + tu = get_tu(source, lang='cpp') + + cls = get_cursor(tu, 'X') + foo = get_cursor(tu, 'foo') + bar = get_cursor(tu, 'bar') + assert cls is not None + assert foo is not None + assert bar is not None + + assert foo.is_static_method() + assert not bar.is_static_method() + def test_underlying_type(): tu = get_tu('typedef int foo;') typedef = get_cursor(tu, 'foo') @@ -75,6 +127,30 @@ def test_underlying_type(): underlying = typedef.underlying_typedef_type assert underlying.kind == TypeKind.INT +kParentTest = """\ + class C { + void f(); + } + + void C::f() { } + """ +def test_semantic_parent(): + tu = get_tu(kParentTest, 'cpp') + curs = get_cursors(tu, 'f') + decl = get_cursor(tu, 'C') + assert(len(curs) == 2) + assert(curs[0].semantic_parent == curs[1].semantic_parent) + assert(curs[0].semantic_parent == decl) + +def test_lexical_parent(): + tu = get_tu(kParentTest, 'cpp') + curs = get_cursors(tu, 'f') + decl = get_cursor(tu, 'C') + assert(len(curs) == 2) + assert(curs[0].lexical_parent != curs[1].lexical_parent) + assert(curs[0].lexical_parent == decl) + assert(curs[1].lexical_parent == tu.cursor) + def test_enum_type(): tu = get_tu('enum TEST { FOO=1, BAR=2 };') enum = get_cursor(tu, 'TEST') @@ -84,9 +160,84 @@ def test_enum_type(): enum_type = enum.enum_type assert enum_type.kind == TypeKind.UINT +def test_enum_type_cpp(): + tu = get_tu('enum TEST : long long { FOO=1, BAR=2 };', lang="cpp") + enum = get_cursor(tu, 'TEST') + assert enum is not None + + assert enum.kind == CursorKind.ENUM_DECL + assert enum.enum_type.kind == TypeKind.LONGLONG + def test_objc_type_encoding(): tu = get_tu('int i;', lang='objc') i = get_cursor(tu, 'i') assert i is not None assert i.objc_type_encoding == 'i' + +def test_enum_values(): + tu = get_tu('enum TEST { SPAM=1, EGG, HAM = EGG * 20};') + enum = get_cursor(tu, 'TEST') + assert enum is not None + + assert enum.kind == CursorKind.ENUM_DECL + + enum_constants = list(enum.get_children()) + assert len(enum_constants) == 3 + + spam, egg, ham = enum_constants + + assert spam.kind == CursorKind.ENUM_CONSTANT_DECL + assert spam.enum_value == 1 + assert egg.kind == CursorKind.ENUM_CONSTANT_DECL + assert egg.enum_value == 2 + assert ham.kind == CursorKind.ENUM_CONSTANT_DECL + assert ham.enum_value == 40 + +def test_enum_values_cpp(): + tu = get_tu('enum TEST : long long { SPAM = -1, HAM = 0x10000000000};', lang="cpp") + enum = get_cursor(tu, 'TEST') + assert enum is not None + + assert enum.kind == CursorKind.ENUM_DECL + + enum_constants = list(enum.get_children()) + assert len(enum_constants) == 2 + + spam, ham = enum_constants + + assert spam.kind == CursorKind.ENUM_CONSTANT_DECL + assert spam.enum_value == -1 + assert ham.kind == CursorKind.ENUM_CONSTANT_DECL + assert ham.enum_value == 0x10000000000 + +def test_annotation_attribute(): + tu = get_tu('int foo (void) __attribute__ ((annotate("here be annotation attribute")));') + + foo = get_cursor(tu, 'foo') + assert foo is not None + + for c in foo.get_children(): + if c.kind == CursorKind.ANNOTATE_ATTR: + assert c.displayname == "here be annotation attribute" + break + else: + assert False, "Couldn't find annotation" + +def test_result_type(): + tu = get_tu('int foo();') + foo = get_cursor(tu, 'foo') + + assert foo is not None + t = foo.result_type + assert t.kind == TypeKind.INT + +def test_get_tokens(): + """Ensure we can map cursors back to tokens.""" + tu = get_tu('int foo(int i);') + foo = get_cursor(tu, 'foo') + + tokens = list(foo.get_tokens()) + assert len(tokens) == 7 + assert tokens[0].spelling == 'int' + assert tokens[1].spelling == 'foo' diff --git a/bindings/python/tests/cindex/test_location.py b/bindings/python/tests/cindex/test_location.py index 528676ef14b5..9e9ef487af18 100644 --- a/bindings/python/tests/cindex/test_location.py +++ b/bindings/python/tests/cindex/test_location.py @@ -60,6 +60,15 @@ def test_location(): location3 = SourceLocation.from_position(tu, file, 1, 4) assert location2 != location3 + offset_location = SourceLocation.from_offset(tu, file, 5) + cursor = Cursor.from_location(tu, offset_location) + verified = False + for n in [n for n in tu.cursor.get_children() if n.spelling == 'one']: + assert n == cursor + verified = True + + assert verified + def test_extent(): tu = get_tu(baseInput) one = get_cursor(tu, 'one') diff --git a/bindings/python/tests/cindex/test_token_kind.py b/bindings/python/tests/cindex/test_token_kind.py new file mode 100644 index 000000000000..62ec63e0ad58 --- /dev/null +++ b/bindings/python/tests/cindex/test_token_kind.py @@ -0,0 +1,43 @@ +from clang.cindex import TokenKind +from nose.tools import eq_ +from nose.tools import ok_ +from nose.tools import raises + +def test_constructor(): + """Ensure TokenKind constructor works as expected.""" + + t = TokenKind(5, 'foo') + + eq_(t.value, 5) + eq_(t.name, 'foo') + +@raises(ValueError) +def test_bad_register(): + """Ensure a duplicate value is rejected for registration.""" + + TokenKind.register(2, 'foo') + +@raises(ValueError) +def test_unknown_value(): + """Ensure trying to fetch an unknown value raises.""" + + TokenKind.from_value(-1) + +def test_registration(): + """Ensure that items registered appear as class attributes.""" + ok_(hasattr(TokenKind, 'LITERAL')) + literal = TokenKind.LITERAL + + ok_(isinstance(literal, TokenKind)) + +def test_from_value(): + """Ensure registered values can be obtained from from_value().""" + t = TokenKind.from_value(3) + ok_(isinstance(t, TokenKind)) + eq_(t, TokenKind.LITERAL) + +def test_repr(): + """Ensure repr() works.""" + + r = repr(TokenKind.LITERAL) + eq_(r, 'TokenKind.LITERAL') diff --git a/bindings/python/tests/cindex/test_tokens.py b/bindings/python/tests/cindex/test_tokens.py new file mode 100644 index 000000000000..70748429094a --- /dev/null +++ b/bindings/python/tests/cindex/test_tokens.py @@ -0,0 +1,52 @@ +from clang.cindex import CursorKind +from clang.cindex import Index +from clang.cindex import SourceLocation +from clang.cindex import SourceRange +from clang.cindex import TokenKind +from nose.tools import eq_ +from nose.tools import ok_ + +from .util import get_tu + +def test_token_to_cursor(): + """Ensure we can obtain a Cursor from a Token instance.""" + tu = get_tu('int i = 5;') + r = tu.get_extent('t.c', (0, 9)) + tokens = list(tu.get_tokens(extent=r)) + + assert len(tokens) == 5 + assert tokens[1].spelling == 'i' + assert tokens[1].kind == TokenKind.IDENTIFIER + + cursor = tokens[1].cursor + assert cursor.kind == CursorKind.VAR_DECL + assert tokens[1].cursor == tokens[2].cursor + +def test_token_location(): + """Ensure Token.location works.""" + + tu = get_tu('int foo = 10;') + r = tu.get_extent('t.c', (0, 11)) + + tokens = list(tu.get_tokens(extent=r)) + eq_(len(tokens), 4) + + loc = tokens[1].location + ok_(isinstance(loc, SourceLocation)) + eq_(loc.line, 1) + eq_(loc.column, 5) + eq_(loc.offset, 4) + +def test_token_extent(): + """Ensure Token.extent works.""" + tu = get_tu('int foo = 10;') + r = tu.get_extent('t.c', (0, 11)) + + tokens = list(tu.get_tokens(extent=r)) + eq_(len(tokens), 4) + + extent = tokens[1].extent + ok_(isinstance(extent, SourceRange)) + + eq_(extent.start.offset, 4) + eq_(extent.end.offset, 7) diff --git a/bindings/python/tests/cindex/test_translation_unit.py b/bindings/python/tests/cindex/test_translation_unit.py index 2e65d9518da0..c91f126097ac 100644 --- a/bindings/python/tests/cindex/test_translation_unit.py +++ b/bindings/python/tests/cindex/test_translation_unit.py @@ -1,42 +1,48 @@ -from clang.cindex import * +import gc import os +from clang.cindex import CursorKind +from clang.cindex import Cursor +from clang.cindex import File +from clang.cindex import Index +from clang.cindex import SourceLocation +from clang.cindex import SourceRange +from clang.cindex import TranslationUnitSaveError +from clang.cindex import TranslationUnit +from .util import get_cursor +from .util import get_tu + kInputsDir = os.path.join(os.path.dirname(__file__), 'INPUTS') def test_spelling(): path = os.path.join(kInputsDir, 'hello.cpp') - index = Index.create() - tu = index.parse(path) + tu = TranslationUnit.from_source(path) assert tu.spelling == path def test_cursor(): path = os.path.join(kInputsDir, 'hello.cpp') - index = Index.create() - tu = index.parse(path) + tu = get_tu(path) c = tu.cursor assert isinstance(c, Cursor) assert c.kind is CursorKind.TRANSLATION_UNIT def test_parse_arguments(): path = os.path.join(kInputsDir, 'parse_arguments.c') - index = Index.create() - tu = index.parse(path, ['-DDECL_ONE=hello', '-DDECL_TWO=hi']) + tu = TranslationUnit.from_source(path, ['-DDECL_ONE=hello', '-DDECL_TWO=hi']) spellings = [c.spelling for c in tu.cursor.get_children()] assert spellings[-2] == 'hello' assert spellings[-1] == 'hi' def test_reparse_arguments(): path = os.path.join(kInputsDir, 'parse_arguments.c') - index = Index.create() - tu = index.parse(path, ['-DDECL_ONE=hello', '-DDECL_TWO=hi']) + tu = TranslationUnit.from_source(path, ['-DDECL_ONE=hello', '-DDECL_TWO=hi']) tu.reparse() spellings = [c.spelling for c in tu.cursor.get_children()] assert spellings[-2] == 'hello' assert spellings[-1] == 'hi' def test_unsaved_files(): - index = Index.create() - tu = index.parse('fake.c', ['-I./'], unsaved_files = [ + tu = TranslationUnit.from_source('fake.c', ['-I./'], unsaved_files = [ ('fake.c', """ #include "fake.h" int x; @@ -52,8 +58,7 @@ int SOME_DEFINE; def test_unsaved_files_2(): import StringIO - index = Index.create() - tu = index.parse('fake.c', unsaved_files = [ + tu = TranslationUnit.from_source('fake.c', unsaved_files = [ ('fake.c', StringIO.StringIO('int x;'))]) spellings = [c.spelling for c in tu.cursor.get_children()] assert spellings[-1] == 'x' @@ -78,7 +83,159 @@ def test_includes(): h3 = os.path.join(kInputsDir, "header3.h") inc = [(src, h1), (h1, h3), (src, h2), (h2, h3)] - index = Index.create() - tu = index.parse(src) + tu = TranslationUnit.from_source(src) for i in zip(inc, tu.get_includes()): assert eq(i[0], i[1]) + +def save_tu(tu): + """Convenience API to save a TranslationUnit to a file. + + Returns the filename it was saved to. + """ + + # FIXME Generate a temp file path using system APIs. + base = 'TEMP_FOR_TRANSLATIONUNIT_SAVE.c' + path = os.path.join(kInputsDir, base) + + # Just in case. + if os.path.exists(path): + os.unlink(path) + + tu.save(path) + + return path + +def test_save(): + """Ensure TranslationUnit.save() works.""" + + tu = get_tu('int foo();') + + path = save_tu(tu) + assert os.path.exists(path) + assert os.path.getsize(path) > 0 + os.unlink(path) + +def test_save_translation_errors(): + """Ensure that saving to an invalid directory raises.""" + + tu = get_tu('int foo();') + + path = '/does/not/exist/llvm-test.ast' + assert not os.path.exists(os.path.dirname(path)) + + try: + tu.save(path) + assert False + except TranslationUnitSaveError as ex: + expected = TranslationUnitSaveError.ERROR_UNKNOWN + assert ex.save_error == expected + +def test_load(): + """Ensure TranslationUnits can be constructed from saved files.""" + + tu = get_tu('int foo();') + assert len(tu.diagnostics) == 0 + path = save_tu(tu) + + assert os.path.exists(path) + assert os.path.getsize(path) > 0 + + tu2 = TranslationUnit.from_ast_file(filename=path) + assert len(tu2.diagnostics) == 0 + + foo = get_cursor(tu2, 'foo') + assert foo is not None + + # Just in case there is an open file descriptor somewhere. + del tu2 + + os.unlink(path) + +def test_index_parse(): + path = os.path.join(kInputsDir, 'hello.cpp') + index = Index.create() + tu = index.parse(path) + assert isinstance(tu, TranslationUnit) + +def test_get_file(): + """Ensure tu.get_file() works appropriately.""" + + tu = get_tu('int foo();') + + f = tu.get_file('t.c') + assert isinstance(f, File) + assert f.name == 't.c' + + try: + f = tu.get_file('foobar.cpp') + except: + pass + else: + assert False + +def test_get_source_location(): + """Ensure tu.get_source_location() works.""" + + tu = get_tu('int foo();') + + location = tu.get_location('t.c', 2) + assert isinstance(location, SourceLocation) + assert location.offset == 2 + assert location.file.name == 't.c' + + location = tu.get_location('t.c', (1, 3)) + assert isinstance(location, SourceLocation) + assert location.line == 1 + assert location.column == 3 + assert location.file.name == 't.c' + +def test_get_source_range(): + """Ensure tu.get_source_range() works.""" + + tu = get_tu('int foo();') + + r = tu.get_extent('t.c', (1,4)) + assert isinstance(r, SourceRange) + assert r.start.offset == 1 + assert r.end.offset == 4 + assert r.start.file.name == 't.c' + assert r.end.file.name == 't.c' + + r = tu.get_extent('t.c', ((1,2), (1,3))) + assert isinstance(r, SourceRange) + assert r.start.line == 1 + assert r.start.column == 2 + assert r.end.line == 1 + assert r.end.column == 3 + assert r.start.file.name == 't.c' + assert r.end.file.name == 't.c' + + start = tu.get_location('t.c', 0) + end = tu.get_location('t.c', 5) + + r = tu.get_extent('t.c', (start, end)) + assert isinstance(r, SourceRange) + assert r.start.offset == 0 + assert r.end.offset == 5 + assert r.start.file.name == 't.c' + assert r.end.file.name == 't.c' + +def test_get_tokens_gc(): + """Ensures get_tokens() works properly with garbage collection.""" + + tu = get_tu('int foo();') + r = tu.get_extent('t.c', (0, 10)) + tokens = list(tu.get_tokens(extent=r)) + + assert tokens[0].spelling == 'int' + gc.collect() + assert tokens[0].spelling == 'int' + + del tokens[1] + gc.collect() + assert tokens[0].spelling == 'int' + + # May trigger segfault if we don't do our job properly. + del tokens + gc.collect() + gc.collect() # Just in case. diff --git a/bindings/python/tests/cindex/test_type.py b/bindings/python/tests/cindex/test_type.py index 03621f3017c7..28e4411c7793 100644 --- a/bindings/python/tests/cindex/test_type.py +++ b/bindings/python/tests/cindex/test_type.py @@ -1,4 +1,7 @@ +import gc + from clang.cindex import CursorKind +from clang.cindex import TranslationUnit from clang.cindex import TypeKind from nose.tools import raises from .util import get_cursor @@ -28,6 +31,7 @@ def test_a_struct(): assert teststruct is not None, "Could not find teststruct." fields = list(teststruct.get_children()) assert all(x.kind == CursorKind.FIELD_DECL for x in fields) + assert all(x.translation_unit is not None for x in fields) assert fields[0].spelling == 'a' assert not fields[0].type.is_const_qualified() @@ -72,6 +76,26 @@ def test_a_struct(): assert fields[7].type.get_pointee().get_pointee().kind == TypeKind.POINTER assert fields[7].type.get_pointee().get_pointee().get_pointee().kind == TypeKind.INT +def test_references(): + """Ensure that a Type maintains a reference to a TranslationUnit.""" + + tu = get_tu('int x;') + children = list(tu.cursor.get_children()) + assert len(children) > 0 + + cursor = children[0] + t = cursor.type + + assert isinstance(t.translation_unit, TranslationUnit) + + # Delete main TranslationUnit reference and force a GC. + del tu + gc.collect() + assert isinstance(t.translation_unit, TranslationUnit) + + # If the TU was destroyed, this should cause a segfault. + decl = t.get_declaration() + constarrayInput=""" struct teststruct { void *A[2]; @@ -263,7 +287,7 @@ def test_is_volatile_qualified(): def test_is_restrict_qualified(): """Ensure Type.is_restrict_qualified works.""" - tu = get_tu('struct s { void * restrict i; void * j };') + tu = get_tu('struct s { void * restrict i; void * j; };') i = get_cursor(tu, 'i') j = get_cursor(tu, 'j') diff --git a/bindings/python/tests/cindex/util.py b/bindings/python/tests/cindex/util.py index 388b26948998..2323839306d0 100644 --- a/bindings/python/tests/cindex/util.py +++ b/bindings/python/tests/cindex/util.py @@ -1,7 +1,7 @@ # This file provides common utility functions for the test suite. from clang.cindex import Cursor -from clang.cindex import Index +from clang.cindex import TranslationUnit def get_tu(source, lang='c', all_warnings=False): """Obtain a translation unit from source and language. @@ -15,21 +15,20 @@ def get_tu(source, lang='c', all_warnings=False): all_warnings is a convenience argument to enable all compiler warnings. """ name = 't.c' + args = [] if lang == 'cpp': name = 't.cpp' + args.append('-std=c++11') elif lang == 'objc': name = 't.m' elif lang != 'c': raise Exception('Unknown language: %s' % lang) - args = [] if all_warnings: - args = ['-Wall', '-Wextra'] + args += ['-Wall', '-Wextra'] - index = Index.create() - tu = index.parse(name, args=args, unsaved_files=[(name, source)]) - assert tu is not None - return tu + return TranslationUnit.from_source(name, args, unsaved_files=[(name, + source)]) def get_cursor(source, spelling): """Obtain a cursor from a source object. @@ -57,9 +56,38 @@ def get_cursor(source, spelling): return result return None + +def get_cursors(source, spelling): + """Obtain all cursors from a source object with a specific spelling. + + This provides a convenient search mechanism to find all cursors with specific + spelling within a source. The first argument can be either a + TranslationUnit or Cursor instance. + + If no cursors are found, an empty list is returned. + """ + cursors = [] + children = [] + if isinstance(source, Cursor): + children = source.get_children() + else: + # Assume TU + children = source.cursor.get_children() + + for cursor in children: + if cursor.spelling == spelling: + cursors.append(cursor) + + # Recurse into children. + cursors.extend(get_cursors(cursor, spelling)) + + return cursors + + __all__ = [ 'get_cursor', + 'get_cursors', 'get_tu', ] diff --git a/bindings/xml/comment-xml-schema.rng b/bindings/xml/comment-xml-schema.rng new file mode 100644 index 000000000000..a0329f8c3d7b --- /dev/null +++ b/bindings/xml/comment-xml-schema.rng @@ -0,0 +1,434 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + template + specialization + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + template + specialization + partialSpecialization + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + .*\S.* + + + + + + + + + + + + + + + + + + .*\S.* + + + + + + + + + .*\S.* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + .*\S.* + + + + + + + + + + + + + + + + + + + + + + + + + + .*\S.* + + + + + + + + + + + + + in + out + in,out + + + + + + + + + + + + + + + + + + + + + + + + + + + + + preserve + + + + + code + verbatim + + + + + + + + + + + + + + .*\S.* + + + + + + .*\S.* + + + + + + .*\S.* + + + + + + .*\S.* + + + + + + + diff --git a/docs/AddressSanitizer.html b/docs/AddressSanitizer.html index c1dc91bf4c88..98ea934d965c 100644 --- a/docs/AddressSanitizer.html +++ b/docs/AddressSanitizer.html @@ -21,14 +21,16 @@

AddressSanitizer

Introduction

@@ -97,36 +99,47 @@ AddressSanitizer is enabled. __has_feature can be used for this purpose.
-#if defined(__has_feature) && __has_feature(address_sanitizer)
-  code that runs only under AddressSanitizer
-#else
-  code that does not run under AddressSanitizer
+#if defined(__has_feature)
+# if __has_feature(address_sanitizer)
+  code that builds only under AddressSanitizer
+# endif
 #endif
 
+

__attribute__((no_address_safety_analysis))

+Some code should not be instrumentated by AddressSanitizer. +One may use the function attribute + + no_address_safety_analysis +to disable instrumentation of a particular function. +This attribute may not be supported by other compilers, so we suggest to +use it together with __has_feature(address_sanitizer). +Note: currently, this attribute will be lost if the function is inlined. +

Supported Platforms

AddressSanitizer is supported on
  • Linux x86_64 (tested on Ubuntu 10.04). -
  • MacOS 10.6 i386/x86_64. +
  • MacOS 10.6 and 10.7 (i386/x86_64).
-Support for Linux i386/ARM and MacOS 10.7 is in progress +Support for Linux i386/ARM is in progress (it may work, but is not guaranteed too).

Limitations

    -
  • AddressSanitizer uses more real memory than a native run. - How much -- depends on the allocations sizes. The smaller the - allocations you make the bigger the overhead. -
  • On 64-bit platforms AddressSanitizer maps (but not reserves) - 16+ Terabytes of virtual address space. - This means that tools like ulimit may not work as usually expected. -
  • Static linking is not supported. +
  • AddressSanitizer uses more real memory than a native run. +How much -- depends on the allocations sizes. The smaller the +allocations you make the bigger the overhead. +
  • AddressSanitizer uses more stack memory. We have seen up to 3x increase. +
  • On 64-bit platforms AddressSanitizer maps (but not reserves) +16+ Terabytes of virtual address space. +This means that tools like ulimit may not work as usually expected. +
  • Static linking is not supported.

Current Status

-AddressSanitizer is fully functional on supported platforms in LLVM head. +AddressSanitizer is fully functional on supported platforms starting from LLVM 3.1. However, the test suite is not fully integrated yet and we lack the testing process (buildbots). diff --git a/docs/AutomaticReferenceCounting.html b/docs/AutomaticReferenceCounting.html index 1416df58e45e..3f1ccaf672ca 100644 --- a/docs/AutomaticReferenceCounting.html +++ b/docs/AutomaticReferenceCounting.html @@ -313,7 +313,7 @@ interoperation:

  • The type system must reliably identify which objects are to be managed. An int* might be a pointer to a malloc'ed -array, or it might be a interior pointer to such an array, or it might +array, or it might be an interior pointer to such an array, or it might point to some field or local variable. In contrast, values of the retainable object pointer types are never interior.
  • The type system must reliably indicate how to @@ -1863,7 +1863,7 @@ of these annotations. A program is ill-formed if it annotates the same function with both cf_audited_transfer and cf_unknown_transfer.

    -

    A pragma is provided to faciliate the mass annotation of interfaces:

    +

    A pragma is provided to facilitate the mass annotation of interfaces:

    #pragma arc_cf_code_audited begin
     ...
    diff --git a/docs/ClangPlugins.html b/docs/ClangPlugins.html
    new file mode 100644
    index 000000000000..ed560fe840ba
    --- /dev/null
    +++ b/docs/ClangPlugins.html
    @@ -0,0 +1,170 @@
    +
    +
    +
    +Clang Plugins
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Clang Plugins

    +

    Clang Plugins make it possible to run extra user defined actions during +a compilation. This document will provide a basic walkthrough of how to write +and run a Clang Plugin.

    + + +

    Introduction

    + + +

    Clang Plugins run FrontendActions over code. See the +FrontendAction tutorial on how to write a +FrontendAction using the RecursiveASTVisitor. In this tutorial, we'll +demonstrate how to write a simple clang plugin. +

    + + +

    Writing a PluginASTAction

    + + +

    The main difference from writing normal FrontendActions is that you can +handle plugin command line options. The +PluginASTAction base class declares a ParseArgs method which you have to +implement in your plugin. +

    +
    +  bool ParseArgs(const CompilerInstance &CI,
    +                 const std::vector<std::string>& args) {
    +    for (unsigned i = 0, e = args.size(); i != e; ++i) {
    +      if (args[i] == "-some-arg") {
    +        // Handle the command line argument.
    +      }
    +    }
    +    return true;
    +  }
    +
    + + +

    Registering a plugin

    + + +

    A plugin is loaded from a dynamic library at runtime by the compiler. To register +a plugin in a library, use FrontendPluginRegistry::Add:

    +
    +  static FrontendPluginRegistry::Add<MyPlugin> X("my-plugin-name", "my plugin description");
    +
    + + +

    Putting it all together

    + + +

    Let's look at an example plugin that prints top-level function names. +This example is also checked into the clang repository; please also take a look +at the latest checked in version of PrintFunctionNames.cpp.

    +
    +#include "clang/Frontend/FrontendPluginRegistry.h"
    +#include "clang/AST/ASTConsumer.h"
    +#include "clang/AST/AST.h"
    +#include "clang/Frontend/CompilerInstance.h"
    +#include "llvm/Support/raw_ostream.h"
    +using namespace clang;
    +
    +namespace {
    +
    +class PrintFunctionsConsumer : public ASTConsumer {
    +public:
    +  virtual bool HandleTopLevelDecl(DeclGroupRef DG) {
    +    for (DeclGroupRef::iterator i = DG.begin(), e = DG.end(); i != e; ++i) {
    +      const Decl *D = *i;
    +      if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
    +        llvm::errs() << "top-level-decl: \"" << ND->getNameAsString() << "\"\n";
    +    }
    +
    +    return true;
    +  }
    +};
    +
    +class PrintFunctionNamesAction : public PluginASTAction {
    +protected:
    +  ASTConsumer *CreateASTConsumer(CompilerInstance &CI, llvm::StringRef) {
    +    return new PrintFunctionsConsumer();
    +  }
    +
    +  bool ParseArgs(const CompilerInstance &CI,
    +                 const std::vector<std::string>& args) {
    +    for (unsigned i = 0, e = args.size(); i != e; ++i) {
    +      llvm::errs() << "PrintFunctionNames arg = " << args[i] << "\n";
    +
    +      // Example error handling.
    +      if (args[i] == "-an-error") {
    +        DiagnosticsEngine &D = CI.getDiagnostics();
    +        unsigned DiagID = D.getCustomDiagID(
    +          DiagnosticsEngine::Error, "invalid argument '" + args[i] + "'");
    +        D.Report(DiagID);
    +        return false;
    +      }
    +    }
    +    if (args.size() && args[0] == "help")
    +      PrintHelp(llvm::errs());
    +
    +    return true;
    +  }
    +  void PrintHelp(llvm::raw_ostream& ros) {
    +    ros << "Help for PrintFunctionNames plugin goes here\n";
    +  }
    +
    +};
    +
    +}
    +
    +static FrontendPluginRegistry::Add<PrintFunctionNamesAction>
    +X("print-fns", "print function names");
    +
    + + +

    Running the plugin

    + + +

    To run a plugin, the dynamic library containing the plugin registry must be +loaded via the -load command line option. This will load all plugins that are +registered, and you can select the plugins to run by specifying the -plugin +option. Additional parameters for the plugins can be passed with -plugin-arg-<plugin-name>.

    + +

    Note that those options must reach clang's cc1 process. There are two +ways to do so:

    +
      +
    • +Directly call the parsing process by using the -cc1 option; this has the +downside of not configuring the default header search paths, so you'll need to +specify the full system path configuration on the command line. +
    • +
    • +Use clang as usual, but prefix all arguments to the cc1 process with -Xclang. +
    • +
    +

    For example, to run the print-function-names plugin over a source file in clang, +first build the plugin, and then call clang with the plugin from the source tree:

    +
    +  $ export BD=/path/to/build/directory
    +  $ (cd $BD && make PrintFunctionNames )
    +  $ clang++ -D_GNU_SOURCE -D_DEBUG -D__STDC_CONSTANT_MACROS \
    +        -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -D_GNU_SOURCE \
    +        -I$BD/tools/clang/include -Itools/clang/include -I$BD/include -Iinclude \
    +        tools/clang/tools/clang-check/ClangCheck.cpp -fsyntax-only \
    +        -Xclang -load -Xclang $BD/lib/PrintFunctionNames.so -Xclang \
    +        -plugin -Xclang print-fns
    +
    + +

    Also see the print-function-name plugin example's +README

    + + + +
    + + + diff --git a/docs/ClangTools.html b/docs/ClangTools.html new file mode 100644 index 000000000000..0dfdc6a73701 --- /dev/null +++ b/docs/ClangTools.html @@ -0,0 +1,118 @@ + + + +Clang Tools + + + + + + + +
    + +

    Clang Tools

    +

    Clang Tools are standalone command line (and potentially GUI) tools design +for use by C++ developers who are already using and enjoying Clang as their +compiler. These tools provide developer-oriented functionality such as fast +syntax checking, automatic formatting, refactoring, etc.

    + +

    Only a couple of the most basic and fundamental tools are kept in the primary +Clang Subversion project. The rest of the tools are kept in a side-project so +that developers who don't want or need to build them don't. If you want to get +access to the extra Clang Tools repository, simply check it out into the tools +tree of your Clang checkout and follow the usual process for building and +working with a combined LLVM/Clang checkout:

    +
      +
    • With Subversion: +
        +
      • cd llvm/tools/clang/tools
      • +
      • svn co http://llvm.org/svn/llvm-project/clang-tools-extra/trunk + extra
      • +
      +
    • +
    • Or with Git: +
        +
      • cd llvm/tools/clang/tools
      • +
      • git clone http://llvm.org/git/clang-tools-extra.git extra
      • +
      +
    • +
    + +

    This document describes a high-level overview of the organization of Clang +Tools within the project as well as giving an introduction to some of the more +important tools. However, it should be noted that this document is currently +focused on Clang and Clang Tool developers, not on end users of these tools.

    + + +

    Clang Tools Organization

    + + +

    Clang Tools are CLI or GUI programs that are intended to be directly used by +C++ developers. That is they are not primarily for use by Clang +developers, although they are hopefully useful to C++ developers who happen to +work on Clang, and we try to actively dogfood their functionality. They are +developed in three components: the underlying infrastructure for building +a standalone tool based on Clang, core shared logic used by many different tools +in the form of refactoring and rewriting libraries, and the tools +themselves.

    + +

    The underlying infrastructure for Clang Tools is the +LibTooling platform. See its documentation for +much more detailed information about how this infrastructure works. The common +refactoring and rewriting toolkit-style library is also part of LibTooling +organizationally.

    + +

    A few Clang Tools are developed along side the core Clang libraries as +examples and test cases of fundamental functionality. However, most of the tools +are developed in a side repository to provide easy separation from the core +libraries. We intentionally do not support public libraries in the side +repository, as we want to carefully review and find good APIs for libraries as +they are lifted out of a few tools and into the core Clang library set.

    + +

    Regardless of which repository Clang Tools' code resides in, the development +process and practices for all Clang Tools are exactly those of Clang itself. +They are entirely within the Clang project, regardless of the version +control scheme.

    + + + +

    Core Clang Tools

    + + +

    The core set of Clang tools that are within the main repository are tools +that very specifically compliment, and allow use and testing of Clang +specific functionality.

    + +

    clang-check

    +

    This tool combines the LibTooling framework for running a Clang tool with the +basic Clang diagnostics by syntax checking specific files in a fast, command line +interface. It can also accept flags to re-display the diagnostics in different +formats with different flags, suitable for use driving an IDE or editor.

    + +

    FIXME: Link to user-oriented clang-check documentation.

    + +

    clang-fixit (Not yet implemented!)

    +

    A tool which specifically applies the Clang fix-it hint diagnostic technology +on top of a dedicated tool. It is designed to explore alternative interfaces for +applying fix-it hints, including automatic application, prompting users with +options for different fixes, etc.

    + +

    NB: The clang-fixit tool is planned, but not yet implemented.

    + +

    FIXME: Link to user-oriented clang-fixit documentation.

    + + +

    Extra Clang Tools

    + + +

    As various categories of Clang Tools are added to the extra repository, +they'll be tracked here. The focus of this documentation is on the scope and +features of the tools for other tool developers; each tool should provide its +own user-focused documentation.

    + +
    + + + diff --git a/docs/HowToSetupToolingForLLVM.html b/docs/HowToSetupToolingForLLVM.html new file mode 100644 index 000000000000..493c8820fc4f --- /dev/null +++ b/docs/HowToSetupToolingForLLVM.html @@ -0,0 +1,186 @@ + + + +How To Setup Clang Tooling For LLVM + + + + + + + +
    + +

    How To Setup Clang Tooling For LLVM

    +

    Clang Tooling provides infrastructure to write tools that need syntactic and +semantic infomation about a program. This term also relates to a set of specific +tools using this infrastructure (e.g. clang-check). This document +provides information on how to set up and use Clang Tooling for the LLVM source +code.

    + + + +

    Introduction

    + + +

    Clang Tooling needs a compilation database to figure out specific build +options for each file. Currently it can create a compilation database from the +compilation_commands.json file, generated by CMake. When invoking +clang tools, you can either specify a path to a build directory using a command +line parameter -p or let Clang Tooling find this file in your +source tree. In either case you need to configure your build using CMake to use +clang tools.

    + + +

    Setup Clang Tooling Using CMake and Make

    + + +

    If you intend to use make to build LLVM, you should have CMake 2.8.6 or later +installed (can be found here).

    +

    First, you need to generate Makefiles for LLVM with CMake. You need to make +a build directory and run CMake from it:

    +
    +  mkdir your/build/directory
    +  cd your/build/directory
    +  cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON path/to/llvm/sources
    +
    + +

    If you want to use clang instead of GCC, you can add +-DCMAKE_C_COMPILER=/path/to/clang + -DCMAKE_CXX_COMPILER=/path/to/clang++. +You can also use ccmake, which provides a curses interface to configure CMake +variables for lazy people.

    + +

    As a result, the new compile_commands.json file should appear in +the current directory. You should link it to the LLVM source tree so that Clang +Tooling is able to use it:

    +
    +  ln -s $PWD/compile_commands.json path/to/llvm/source/
    +
    + +

    Now you are ready to build and test LLVM using make:

    +
    +  make check-all
    +
    + + +

    Using Clang Tools

    + + +

    After you completed the previous steps, you are ready to run clang tools. If +you have a recent clang installed, you should have clang-check in +$PATH. Try to run it on any .cpp file inside the LLVM source tree:

    +
    +  clang-check tools/clang/lib/Tooling/CompilationDatabase.cpp
    +
    +

    If you're using vim, it's convenient to have clang-check integrated. Put this +into your .vimrc:

    +
    +  set makeprg=clang-check\ %
    +  map <F5> :make<CR><CR>
    +
    + +

    When editing C++ code, hit F5 to reparse the current buffer. The output will +go into the error window, which you can enable with :cope.

    + +

    Other clang-check options that can be useful when working with +clang AST:

    +
      +
    • -ast-print - Build ASTs and then pretty-print them.
    • +
    • -ast-dump - Build ASTs and then debug dump them.
    • +
    • -ast-dump-filter=<string> - Use with + -ast-dump or -ast-print to dump/print + only AST declaration nodes having a certain substring in a qualified name. + Use -ast-list to list all filterable declaration node + names.
    • +
    • -ast-list - Build ASTs and print the list of declaration + node qualified names.
    • +
    +

    Examples:

    +
    +$ clang-check tools/clang/tools/clang-check/ClangCheck.cpp -ast-dump -ast-dump-filter ActionFactory::newASTConsumer
    +Processing: tools/clang/tools/clang-check/ClangCheck.cpp.
    +Dumping ::ActionFactory::newASTConsumer:
    +clang::ASTConsumer *newASTConsumer() (CompoundStmt 0x44da290 </home/alexfh/local/llvm/tools/clang/tools/clang-check/ClangCheck.cpp:64:40, line:72:3>
    +  (IfStmt 0x44d97c8 <line:65:5, line:66:45>
    +    <<<NULL>>>
    +      (ImplicitCastExpr 0x44d96d0 <line:65:9> '_Bool':'_Bool' <UserDefinedConversion>
    +...
    +$ clang-check tools/clang/tools/clang-check/ClangCheck.cpp -ast-print -ast-dump-filter ActionFactory::newASTConsumer
    +Processing: tools/clang/tools/clang-check/ClangCheck.cpp.
    +Printing <anonymous namespace>::ActionFactory::newASTConsumer:
    +clang::ASTConsumer *newASTConsumer() {
    +    if (this->ASTList.operator _Bool())
    +        return clang::CreateASTDeclNodeLister();
    +    if (this->ASTDump.operator _Bool())
    +        return clang::CreateASTDumper(this->ASTDumpFilter);
    +    if (this->ASTPrint.operator _Bool())
    +        return clang::CreateASTPrinter(&llvm::outs(), this->ASTDumpFilter);
    +    return new clang::ASTConsumer();
    +}
    +
    + + +

    (Experimental) Using Ninja Build System

    + + +

    Optionally you can use the Ninja build system instead of +make. It is aimed at making your builds faster. Currently this step will require +building Ninja from sources and using a development version of CMake.

    +

    To take advantage of using Clang Tools along with Ninja build you need at +least CMake 2.8.9. At the moment CMake 2.8.9 is still under development, so you +can get latest development sources and build it yourself:

    +
    +  git clone git://cmake.org/cmake.git
    +  cd cmake
    +  ./bootstrap
    +  make
    +  sudo make install
    +
    + +

    Having the correct version of CMake, you can clone the Ninja git repository +and build Ninja from sources:

    +
    +  git clone git://github.com/martine/ninja.git
    +  cd ninja/
    +  ./bootstrap.py
    +
    +

    This will result in a single binary ninja in the current +directory. It doesn't require installation and can just be copied to any +location inside $PATH, say /usr/local/bin/:

    +
    +  sudo cp ninja /usr/local/bin/
    +  sudo chmod a+rx /usr/local/bin/ninja
    +
    +

    After doing all of this, you'll need to generate Ninja build files for LLVM +with CMake. You need to make a build directory and run CMake from it:

    +
    +  mkdir your/build/directory
    +  cd your/build/directory
    +  cmake -G Ninja -DCMAKE_EXPORT_COMPILE_COMMANDS=ON path/to/llvm/sources
    +
    + +

    If you want to use clang instead of GCC, you can add +-DCMAKE_C_COMPILER=/path/to/clang + -DCMAKE_CXX_COMPILER=/path/to/clang++. +You can also use ccmake, which provides a curses interface to configure CMake +variables in an interactive manner.

    + +

    As a result, the new compile_commands.json file should appear in +the current directory. You should link it to the LLVM source tree so that Clang +Tooling is able to use it:

    +
    +  ln -s $PWD/compile_commands.json path/to/llvm/source/
    +
    + +

    Now you are ready to build and test LLVM using Ninja:

    +
    +  ninja check-all
    +
    +

    Other target names can be used in the same way as with make.

    +
    + + + diff --git a/docs/InternalsManual.html b/docs/InternalsManual.html index bd6af8d6c165..3f3e124ae640 100644 --- a/docs/InternalsManual.html +++ b/docs/InternalsManual.html @@ -357,6 +357,12 @@ Clang:

    Example:"candidate found by name lookup is %q0" Class:NamedDecl* Description

    This formatter indicates that the fully-qualified name of the declaration should be printed, e.g., "std::vector" rather than "vector".

    + +"diff" format +Example:"no known conversion %diff{from | to | }1,2" +Class:QualType +Description

    This formatter takes two QualTypes and attempts to print a template difference between the two. If tree printing is off, the text inside the braces before the pipe is printed, with the formatted text replacing the $. If tree printing is on, the text after the pipe is printed and a type tree is printed after the diagnostic message. +

    @@ -441,6 +447,18 @@ href="#DiagnosticClient">Other diagnostic clients might choose to render the code differently (e.g., as markup inline) or even give the user the ability to automatically fix the problem.

    +

    Fix-it hints on errors and warnings need to obey these rules:

    + +
      +
    • Since they are automatically applied if -Xclang -fixit +is passed to the driver, they should only be used when it's very likely they +match the user's intent.
    • +
    • Clang must recover from errors as if the fix-it had been applied.
    • +
    + +

    If a fix-it can't obey these rules, put the fix-it on a note. Fix-its on +notes are not applied automatically.

    +

    All fix-it hints are described by the FixItHint class, instances of which should be attached to the diagnostic using the << operator in the same way that highlighted source ranges and @@ -1686,7 +1704,7 @@ interacts with constant evaluation:

  • __extension__: The expression form of this extension causes any evaluatable subexpression to be accepted as an integer constant expression.
  • -
  • __builtin_constant_p: This returns true (as a integer +
  • __builtin_constant_p: This returns true (as an integer constant expression) if the operand evaluates to either a numeric value (that is, not a pointer cast to integral type) of integral, enumeration, floating or complex type, or if it evaluates to the address of the first @@ -1751,18 +1769,6 @@ then __attribute__((myattribute("Hello", 3))) will be a valid use.

    Boilerplate

    -

    Add an element to the AttributeList::Kind enum in include/clang/Sema/AttributeList.h -named AT_lower_with_underscores. That is, a CamelCased -AttributeName in Attr.td name should become -AT_attribute_name.

    - -

    Add a case to the StringSwitch in AttributeList::getKind() -in lib/Sema/AttributeList.cpp -for each spelling of your attribute. Less common attributes should come toward -the end of that list.

    -

    Write a new HandleYourAttr() function in lib/Sema/SemaDeclAttr.cpp, and add a case to the switch in ProcessNonInheritableDeclAttr() or diff --git a/docs/IntroductionToTheClangAST.html b/docs/IntroductionToTheClangAST.html new file mode 100644 index 000000000000..28175dd81bb4 --- /dev/null +++ b/docs/IntroductionToTheClangAST.html @@ -0,0 +1,139 @@ + + + +Introduction to the Clang AST + + + + + + + +

    + +

    Introduction to the Clang AST

    +

    This document gives a gentle introduction to the mysteries of the Clang AST. +It is targeted at developers who either want to contribute to Clang, or use +tools that work based on Clang's AST, like the AST matchers.

    + + + +

    Introduction

    + + +

    Clang's AST is different from ASTs produced by some other compilers in that it closely +resembles both the written C++ code and the C++ standard. For example, +parenthesis expressions and compile time constants are available in an unreduced +form in the AST. This makes Clang's AST a good fit for refactoring tools.

    + +

    Documentation for all Clang AST nodes is available via the generated +Doxygen. The doxygen online +documentation is also indexed by your favorite search engine, which will make +a search for clang and the AST node's class name usually turn up the doxygen +of the class you're looking for (for example, search for: clang ParenExpr).

    + + +

    Examining the AST

    + + +

    A good way to familarize yourself with the Clang AST is to actually look +at it on some simple example code. Clang has a builtin AST-dump modes, which +can be enabled with the flags -ast-dump and -ast-dump-xml. Note that -ast-dump-xml +currently only works with debug-builds of clang.

    + +

    Let's look at a simple example AST:

    +
    +# cat test.cc
    +int f(int x) {
    +  int result = (x / 42);
    +  return result;
    +}
    +
    +# Clang by default is a frontend for many tools; -cc1 tells it to directly
    +# use the C++ compiler mode. -undef leaves out some internal declarations.
    +$ clang -cc1 -undef -ast-dump-xml test.cc
    +... cutting out internal declarations of clang ...
    +<TranslationUnit ptr="0x4871160">
    + <Function ptr="0x48a5800" name="f" prototype="true">
    +  <FunctionProtoType ptr="0x4871de0" canonical="0x4871de0">
    +   <BuiltinType ptr="0x4871250" canonical="0x4871250"/>
    +   <parameters>
    +    <BuiltinType ptr="0x4871250" canonical="0x4871250"/>
    +   </parameters>
    +  </FunctionProtoType>
    +  <ParmVar ptr="0x4871d80" name="x" initstyle="c">
    +   <BuiltinType ptr="0x4871250" canonical="0x4871250"/>
    +  </ParmVar>
    +  <Stmt>
    +(CompoundStmt 0x48a5a38 <t2.cc:1:14, line:4:1>
    +  (DeclStmt 0x48a59c0 <line:2:3, col:24>
    +    0x48a58c0 "int result =
    +      (ParenExpr 0x48a59a0 <col:16, col:23> 'int'
    +        (BinaryOperator 0x48a5978 <col:17, col:21> 'int' '/'
    +          (ImplicitCastExpr 0x48a5960 <col:17> 'int' <LValueToRValue>
    +            (DeclRefExpr 0x48a5918 <col:17> 'int' lvalue ParmVar 0x4871d80 'x' 'int'))
    +          (IntegerLiteral 0x48a5940 <col:21> 'int' 42)))")
    +  (ReturnStmt 0x48a5a18 <line:3:3, col:10>
    +    (ImplicitCastExpr 0x48a5a00 <col:10> 'int' <LValueToRValue>
    +      (DeclRefExpr 0x48a59d8 <col:10> 'int' lvalue Var 0x48a58c0 'result' 'int'))))
    +
    +  </Stmt>
    + </Function>
    +</TranslationUnit>
    +
    +

    In general, -ast-dump-xml dumps declarations in an XML-style format and +statements in an S-expression-style format. +The toplevel declaration in a translation unit is always the +translation unit declaration. +In this example, our first user written declaration is the +function declaration +of 'f'. The body of 'f' is a compound statement, +whose child nodes are a declaration statement +that declares our result variable, and the +return statement.

    + + +

    AST Context

    + + +

    All information about the AST for a translation unit is bundled up in the class +ASTContext. +It allows traversal of the whole translation unit starting from +getTranslationUnitDecl, +or to access Clang's table of identifiers +for the parsed translation unit.

    + + +

    AST Nodes

    + + +

    Clang's AST nodes are modeled on a class hierarchy that does not have a common +ancestor. Instead, there are multiple larger hierarchies for basic node types like +Decl and +Stmt. Many +important AST nodes derive from Type, +Decl, +DeclContext or +Stmt, +with some classes deriving from both Decl and DeclContext.

    +

    There are also a multitude of nodes in the AST that are not part of a +larger hierarchy, and are only reachable from specific other nodes, +like CXXBaseSpecifier. +

    + +

    Thus, to traverse the full AST, one starts from the TranslationUnitDecl +and then recursively traverses everything that can be reached from that node +- this information has to be encoded for each specific node type. This algorithm +is encoded in the RecursiveASTVisitor. +See the RecursiveASTVisitor tutorial.

    + +

    The two most basic nodes in the Clang AST are statements (Stmt) +and declarations (Decl). +Note that expressions (Expr) +are also statements in Clang's AST.

    + +
    + + + diff --git a/docs/JSONCompilationDatabase.html b/docs/JSONCompilationDatabase.html new file mode 100644 index 000000000000..290719472902 --- /dev/null +++ b/docs/JSONCompilationDatabase.html @@ -0,0 +1,89 @@ + + + +JSON Compilation Database Format Specification + + + + + + + +
    + +

    JSON Compilation Database Format Specification

    +

    This document describes a format for specifying how to replay +single compilations independently of the build system.

    + +

    Background

    +

    Tools based on the C++ Abstract Syntax Tree need full information how to +parse a translation unit. Usually this information is implicitly +available in the build system, but running tools as part of +the build system is not necessarily the best solution: +

      +
    • Build systems are inherently change driven, so running multiple +tools over the same code base without changing the code does not fit +into the architecture of many build systems.
    • +
    • Figuring out whether things have changed is often an IO bound +process; this makes it hard to build low latency end user tools based +on the build system.
    • +
    • Build systems are inherently sequential in the build graph, for example +due to generated source code. While tools that run independently of the +build still need the generated source code to exist, running tools multiple +times over unchanging source does not require serialization of the runs +according to the build dependency graph.
    • +
    +

    + +

    Supported Systems

    +

    Currently CMake (since 2.8.5) supports generation of compilation +databases for Unix Makefile builds (Ninja builds in the works) with the option +CMAKE_EXPORT_COMPILE_COMMANDS.

    +

    Clang's tooling interface supports reading compilation databases; see +the LibTooling documentation. libclang and its +python bindings also support this (since clang 3.2); see +CXCompilationDatabase.h.

    + +

    Format

    +

    A compilation database is a JSON file, which consist of an array of +"command objects", where each command object specifies one way a translation unit +is compiled in the project.

    +

    Each command object contains the translation unit's main file, the working +directory of the compile run and the actual compile command.

    +

    Example: +

    +[
    +  { "directory": "/home/user/llvm/build",
    +    "command": "/usr/bin/clang++ -Irelative -DSOMEDEF='\"With spaces and quotes.\"' -c -o file.o file.cc",
    +    "file": "file.cc" },
    +  ...
    +]
    +
    +The contracts for each field in the command object are: +
      +
    • directory: The working directory of the compilation. All paths specified +in the command or file fields must be either absolute or relative to +this directory.
    • +
    • file: The main translation unit source processed by this compilation step. +This is used by tools as the key into the compilation database. There can be multiple +command objects for the same file, for example if the same source file is +compiled with different configurations.
    • +
    • command: The compile command executed. After JSON unescaping, this must +be a valid command to rerun the exact compilation step for the translation unit in +the environment the build system uses. Parameters use shell quoting and shell escaping +of quotes, with '"' and '\' being the only special characters. Shell expansion is +not supported.
    • +
    +

    + +

    Build System Integration

    +

    The convention is to name the file compile_commands.json and put it at the top +of the build directory. Clang tools are pointed to the top of the build directory +to detect the file and use the compilation database to parse C++ code in the source +tree.

    + +
    + + + diff --git a/docs/LanguageExtensions.html b/docs/LanguageExtensions.html index 68f0afc1ffa5..eac3c69997be 100644 --- a/docs/LanguageExtensions.html +++ b/docs/LanguageExtensions.html @@ -91,18 +91,24 @@
  • Automatic reference counting
  • Enumerations with a fixed underlying type
  • Interoperability with C++11 lambdas
  • -
  • Object Literals and Subscripting
  • +
  • Object Literals and Subscripting
  • Function Overloading in C
  • Initializer lists for complex numbers in C
  • Builtin Functions
  • +
  • Non-standard C++11 Attributes + +
  • Target-Specific Extensions
    • X86/X86-64 Language Extensions
    • @@ -655,7 +661,7 @@ framework search path. For consistency, we recommend that such files never be included in installed versions of the framework.

      -

      Availability attribute

      Availability attribute

      Clang introduces the availability attribute, which can @@ -937,8 +943,8 @@ is enabled.

      Use __has_feature(c_atomic) or __has_extension(c_atomic) to determine if support for atomic types using _Atomic is enabled. Clang also provides a set of builtins which can be -used to implement the <stdatomic.h> operations on _Atomic -types.

      +used to implement the <stdatomic.h> operations on +_Atomic types.

      C11 generic selections

      @@ -1183,10 +1189,28 @@ in Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory management (autorelease).

      -

      Object Literals and Subscripting

      +

      Object Literals and Subscripting

      + + +

      Clang provides support for Object Literals +and Subscripting in Objective-C, which simplifies common Objective-C +programming patterns, makes programs more concise, and improves the safety of +container creation. There are several feature macros associated with object +literals and subscripting: __has_feature(objc_array_literals) +tests the availability of array literals; +__has_feature(objc_dictionary_literals) tests the availability of +dictionary literals; __has_feature(objc_subscripting) tests the +availability of object subscripting.

      + + +

      Objective-C Autosynthesis of Properties

      -

      Clang provides support for Object Literals and Subscripting in Objective-C, which simplifies common Objective-C programming patterns, makes programs more concise, and improves the safety of container creation. There are several feature macros associated with object literals and subscripting: __has_feature(objc_array_literals) tests the availability of array literals; __has_feature(objc_dictionary_literals) tests the availability of dictionary literals; __has_feature(objc_subscripting) tests the availability of object subscripting.

      +

      Clang provides support for autosynthesis of declared properties. Using this +feature, clang provides default synthesis of those properties not declared @dynamic +and not having user provided backing getter and setter methods. +__has_feature(objc_default_synthesize_properties) checks for availability +of this feature in version of clang being used.

      Function Overloading in C

      @@ -1343,6 +1367,42 @@ functions are implemented directly in terms of extended vector support instead of builtins, in order to reduce the number of builtins that we need to implement.

      + +

      __builtin_readcyclecounter

      + + +

      __builtin_readcyclecounter is used to access the cycle counter +register (or a similar low-latency, high-accuracy clock) on those targets that +support it. +

      + +

      Syntax:

      + +
      +__builtin_readcyclecounter()
      +
      + +

      Example of Use:

      + +
      +unsigned long long t0 = __builtin_readcyclecounter();
      +do_something();
      +unsigned long long t1 = __builtin_readcyclecounter();
      +unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow
      +
      + +

      Description:

      + +

      The __builtin_readcyclecounter() builtin returns the cycle counter value, +which may be either global or process/thread-specific depending on the target. +As the backing counters often overflow quickly (on the order of +seconds) this should only be used for timing small intervals. When not +supported by the target, the return value is always zero. This builtin +takes no arguments and produces an unsigned long long result. +

      + +

      Query for this feature with __has_builtin(__builtin_readcyclecounter).

      +

      __builtin_shufflevector

      @@ -1489,6 +1549,54 @@ with a __c11_ prefix. The supported operations are:

    • __c11_atomic_fetch_xor
    + +

    Non-standard C++11 Attributes

    + + +

    Clang supports one non-standard C++11 attribute. It resides in the +clang attribute namespace.

    + + +

    The clang::fallthrough attribute

    + + +

    The clang::fallthrough attribute is used along with the +-Wimplicit-fallthrough argument to annotate intentional fall-through +between switch labels. It can only be applied to a null statement placed at a +point of execution between any statement and the next switch label. It is common +to mark these places with a specific comment, but this attribute is meant to +replace comments with a more strict annotation, which can be checked by the +compiler. This attribute doesn't change semantics of the code and can be used +wherever an intended fall-through occurs. It is designed to mimic +control-flow statements like break;, so it can be placed in most places +where break; can, but only if there are no statements on the execution +path between it and the next switch label.

    +

    Here is an example:

    +
    +// compile with -Wimplicit-fallthrough
    +switch (n) {
    +case 33:
    +  f();
    +case 44:  // warning: unannotated fall-through
    +  g();
    +  [[clang::fallthrough]];
    +case 55:  // no warning
    +  if (x) {
    +    h();
    +    break;
    +  }
    +  else {
    +    i();
    +    [[clang::fallthrough]];
    +  }
    +case 66:  // no warning
    +  p();
    +  [[clang::fallthrough]];  // warning: fallthrough annotation does not directly precede case label
    +  q();
    +case 77:  // warning: unannotated fall-through
    +  r();
    +}
    +

    Target-Specific Extensions

    diff --git a/docs/LibTooling.html b/docs/LibTooling.html new file mode 100644 index 000000000000..ed0ad45e4e7f --- /dev/null +++ b/docs/LibTooling.html @@ -0,0 +1,229 @@ + + + +LibTooling + + + + + + + +
    + +

    LibTooling

    +

    LibTooling is a library to support writing standalone tools based on +Clang. This document will provide a basic walkthrough of how to write +a tool using LibTooling.

    + + +

    Introduction

    + + +

    Tools built with LibTooling, like Clang Plugins, run FrontendActions over +code. +In this tutorial, we'll demonstrate the different ways of running clang's +SyntaxOnlyAction, which runs a quick syntax check, over a bunch of +code.

    + + +

    Parsing a code snippet in memory.

    + + +

    If you ever wanted to run a FrontendAction over some sample code, for example +to unit test parts of the Clang AST, runToolOnCode is what you looked for. Let +me give you an example: +

    +  #include "clang/Tooling/Tooling.h"
    +
    +  TEST(runToolOnCode, CanSyntaxCheckCode) {
    +    // runToolOnCode returns whether the action was correctly run over the
    +    // given code.
    +    EXPECT_TRUE(runToolOnCode(new clang::SyntaxOnlyAction, "class X {};"));
    +  }
    +
    + + +

    Writing a standalone tool.

    + + +

    Once you unit tested your FrontendAction to the point where it cannot +possibly break, it's time to create a standalone tool. For a standalone tool +to run clang, it first needs to figure out what command line arguments to use +for a specified file. To that end we create a CompilationDatabase.

    + +

    Creating a compilation database.

    +

    CompilationDatabase provides static factory functions to help with parsing +compile commands from a build directory or the command line. The following code +allows for both explicit specification of a compile command line, as well as +retrieving the compile commands lines from a database. +

    +int main(int argc, const char **argv) {
    +  // First, try to create a fixed compile command database from the command line
    +  // arguments.
    +  llvm::OwningPtr<CompilationDatabase> Compilations(
    +    FixedCompilationDatabase::loadFromCommandLine(argc, argv));
    +
    +  // Next, use normal llvm command line parsing to get the tool specific
    +  // parameters.
    +  cl::ParseCommandLineOptions(argc, argv);
    +
    +  if (!Compilations) {
    +    // In case the user did not specify the compile command line via positional
    +    // command line arguments after "--", try to load the compile commands from
    +    // a database in the specified build directory or auto-detect it from a
    +    // source file.
    +    std::string ErrorMessage;
    +    if (!BuildPath.empty()) {
    +      Compilations.reset(
    +         CompilationDatabase::autoDetectFromDirectory(BuildPath, ErrorMessage));
    +    } else {
    +      Compilations.reset(CompilationDatabase::autoDetectFromSource(
    +          SourcePaths[0], ErrorMessage));
    +    }
    +    // If there is still no valid compile command database, we don't know how
    +    // to run the tool.
    +    if (!Compilations)
    +      llvm::report_fatal_error(ErrorMessage);
    +  }
    +}
    +
    +

    + +

    Creating and running a ClangTool.

    +

    Once we have a CompilationDatabase, we can create a ClangTool and run our +FrontendAction over some code. For example, to run the SyntaxOnlyAction over +the files "a.cc" and "b.cc" one would write: +

    +  // A clang tool can run over a number of sources in the same process...
    +  std::vector<std::string> Sources;
    +  Sources.push_back("a.cc");
    +  Sources.push_back("b.cc");
    +
    +  // We hand the CompilationDatabase we created and the sources to run over into
    +  // the tool constructor.
    +  ClangTool Tool(*Compilations, Sources);
    +
    +  // The ClangTool needs a new FrontendAction for each translation unit we run
    +  // on. Thus, it takes a FrontendActionFactory as parameter. To create a
    +  // FrontendActionFactory from a given FrontendAction type, we call
    +  // newFrontendActionFactory<clang::SyntaxOnlyAction>().
    +  int result = Tool.run(newFrontendActionFactory<clang::SyntaxOnlyAction>());
    +
    +

    + +

    Putting it together - the first tool.

    +

    Now we combine the two previous steps into our first real tool. This example +tool is also checked into the clang tree at tools/clang-check/ClangCheck.cpp. +

    +#include "llvm/Support/CommandLine.h"
    +#include "clang/Frontend/FrontendActions.h"
    +#include "clang/Tooling/CompilationDatabase.h"
    +#include "clang/Tooling/Tooling.h"
    +
    +using namespace clang::tooling;
    +using namespace llvm;
    +
    +cl::opt<std::string> BuildPath(
    +  "p",
    +  cl::desc("<build-path>"),
    +  cl::Optional);
    +
    +cl::list<std::string> SourcePaths(
    +  cl::Positional,
    +  cl::desc("<source0> [... <sourceN>]"),
    +  cl::OneOrMore);
    +
    +int main(int argc, const char **argv) {
    +  llvm::OwningPtr<CompilationDatabase> Compilations(
    +    FixedCompilationDatabase::loadFromCommandLine(argc, argv));
    +  cl::ParseCommandLineOptions(argc, argv);
    +  if (!Compilations) {
    +    std::string ErrorMessage;
    +    Compilations.reset(
    +      !BuildPath.empty() ?
    +        CompilationDatabase::autoDetectFromDirectory(BuildPath, ErrorMessage) :
    +        CompilationDatabase::autoDetectFromSource(SourcePaths[0], ErrorMessage)
    +      );
    +    if (!Compilations)
    +      llvm::report_fatal_error(ErrorMessage);
    +  }
    +  ClangTool Tool(*Compilations, SourcePaths);
    +  return Tool.run(newFrontendActionFactory<clang::SyntaxOnlyAction>());
    +}
    +
    +

    + +

    Running the tool on some code.

    +

    When you check out and build clang, clang-check is already built and +available to you in bin/clang-check inside your build directory.

    +

    You can run clang-check on a file in the llvm repository by specifying +all the needed parameters after a "--" separator: +

    +  $ cd /path/to/source/llvm
    +  $ export BD=/path/to/build/llvm
    +  $ $BD/bin/clang-check tools/clang/tools/clang-check/ClangCheck.cpp -- \
    +    clang++ -D__STDC_CONSTANT_MACROS -D__STDC_LIMIT_MACROS \
    +    -Itools/clang/include -I$BD/include -Iinclude -Itools/clang/lib/Headers -c
    +
    +

    + +

    As an alternative, you can also configure cmake to output a compile command +database into its build directory: +

    +  # Alternatively to calling cmake, use ccmake, toggle to advanced mode and
    +  # set the parameter CMAKE_EXPORT_COMPILE_COMMANDS from the UI.
    +  $ cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON .
    +
    +

    +

    +This creates a file called compile_commands.json in the build directory. Now +you can run clang-check over files in the project by specifying the build path +as first argument and some source files as further positional arguments: +

    +  $ cd /path/to/source/llvm
    +  $ export BD=/path/to/build/llvm
    +  $ $BD/bin/clang-check -p $BD tools/clang/tools/clang-check/ClangCheck.cpp
    +
    +

    + +

    Builtin includes.

    +

    Clang tools need their builtin headers and search for them the same way clang +does. Thus, the default location to look for builtin headers is in a path +$(dirname /path/to/tool)/../lib/clang/3.2/include relative to the tool +binary. This works out-of-the-box for tools running from llvm's toplevel +binary directory after building clang-headers, or if the tool is running +from the binary directory of a clang install next to the clang binary.

    + +

    Tips: if your tool fails to find stddef.h or similar headers, call +the tool with -v and look at the search paths it looks through.

    + +

    Linking.

    +

    Please note that this presents the linking requirements at the time of this +writing. For the most up-to-date information, look at one of the tools' +Makefiles (for example +clang-check/Makefile). +

    + +

    To link a binary using the tooling infrastructure, link in the following +libraries: +

      +
    • Tooling
    • +
    • Frontend
    • +
    • Driver
    • +
    • Serialization
    • +
    • Parse
    • +
    • Sema
    • +
    • Analysis
    • +
    • Edit
    • +
    • AST
    • +
    • Lex
    • +
    • Basic
    • +
    +

    + +
    + + + diff --git a/docs/ObjectiveCLiterals.html b/docs/ObjectiveCLiterals.html index 63b523c6dfcd..11751a6acda8 100644 --- a/docs/ObjectiveCLiterals.html +++ b/docs/ObjectiveCLiterals.html @@ -4,7 +4,7 @@ - Clang Language Extensions + Objective-C Literals + + + + + +
    + +

    ThreadSanitizer

    + + +

    Introduction

    +ThreadSanitizer is a tool that detects data races.
    +It consists of a compiler instrumentation module and a run-time library.
    +Typical slowdown introduced by ThreadSanitizer is 5x-15x (TODO: these numbers are +approximate so far). + +

    How to build

    +Follow the clang build instructions.
    +Note: CMake build does not work yet. +See bug 12272. + +

    Supported Platforms

    +ThreadSanitizer is supported on Linux x86_64 (tested on Ubuntu 10.04).
    +Support for MacOS 10.7 (64-bit only) is planned for late 2012.
    +Support for 32-bit platforms is problematic and not yet planned. + + + +

    Usage

    +Simply compile your program with -fthread-sanitizer -fPIE and link it +with -fthread-sanitizer -pie.
    +To get a reasonable performance add -O1 or higher.
    +Use -g to get file names and line numbers in the warning messages.
    + +Example: +
    +% cat projects/compiler-rt/lib/tsan/output_tests/tiny_race.c
    +#include 
    +int Global;
    +void *Thread1(void *x) {
    +  Global = 42;
    +  return x;
    +}
    +int main() {
    +  pthread_t t;
    +  pthread_create(&t, NULL, Thread1, NULL);
    +  Global = 43;
    +  pthread_join(t, NULL);
    +  return Global;
    +}
    +
    + +
    +% clang -fthread-sanitizer -g -O1 tiny_race.c -fPIE -pie
    +
    + +If a bug is detected, the program will print an error message to stderr. +Currently, ThreadSanitizer symbolizes its output using an external +addr2line +process (this will be fixed in future). +
    +% TSAN_OPTIONS=strip_path_prefix=`pwd`/  # Don't print full paths.
    +% ./a.out 2> log
    +% cat log
    +WARNING: ThreadSanitizer: data race (pid=19219)
    +  Write of size 4 at 0x7fcf47b21bc0 by thread 1:
    +    #0 Thread1 tiny_race.c:4 (exe+0x00000000a360)
    +  Previous write of size 4 at 0x7fcf47b21bc0 by main thread:
    +    #0 main tiny_race.c:10 (exe+0x00000000a3b4)
    +  Thread 1 (running) created at:
    +    #0 pthread_create ??:0 (exe+0x00000000c790)
    +    #1 main tiny_race.c:9 (exe+0x00000000a3a4)
    +
    + + +

    Limitations

    +
      +
    • ThreadSanitizer uses more real memory than a native run. +At the default settings the memory overhead is 9x plus 9Mb per each thread. +Settings with 5x and 3x overhead (but less accurate analysis) are also available. +
    • ThreadSanitizer maps (but does not reserve) a lot of virtual address space. +This means that tools like ulimit may not work as usually expected. +
    • Static linking is not supported. +
    • ThreadSanitizer requires -fPIE -pie +
    + + +

    Current Status

    +ThreadSanitizer is in alpha stage. +It is known to work on large C++ programs using pthreads, but we do not promise +anything (yet).
    +C++11 threading is not yet supported. + +We are actively working on enhancing the tool -- stay tuned. +Any help, especially in the form of minimized standalone tests is more than welcome. + +

    More Information

    +http://code.google.com/p/thread-sanitizer. + + +
    + + diff --git a/docs/Tooling.html b/docs/Tooling.html new file mode 100644 index 000000000000..74837f4c99b9 --- /dev/null +++ b/docs/Tooling.html @@ -0,0 +1,120 @@ + + + +Writing Clang Tools + + + + + + + +
    + +

    Writing Clang Tools

    +

    Clang provides infrastructure to write tools that need syntactic and semantic +information about a program. This document will give a short introduction of the +different ways to write clang tools, and their pros and cons.

    + + +

    LibClang

    + + +

    LibClang is a stable high level C interface to clang. When in doubt LibClang +is probably the interface you want to use. Consider the other interfaces only +when you have a good reason not to use LibClang.

    +

    Canonical examples of when to use LibClang:

    +
      +
    • Xcode
    • +
    • Clang Python Bindings
    • +
    +

    Use LibClang when you...

    +
      +
    • want to interface with clang from other languages than C++
    • +
    • need a stable interface that takes care to be backwards compatible
    • +
    • want powerful high-level abstractions, like iterating through an AST +with a cursor, and don't want to learn all the nitty gritty details of Clang's +AST.
    • +
    +

    Do not use LibClang when you...

    +
      +
    • want full control over the Clang AST
    • +
    + + +

    Clang Plugins

    + + +

    Clang Plugins allow you to run additional actions on the AST as part of +a compilation. Plugins are dynamic libraries that are loaded at runtime by +the compiler, and they're easy to integrate into your build environment.

    +

    Canonical examples of when to use Clang Plugins:

    +
      +
    • special lint-style warnings or errors for your project
    • +
    • creating additional build artifacts from a single compile step
    • +
    +

    Use Clang Plugins when you...

    +
      +
    • need your tool to rerun if any of the dependencies change
    • +
    • want your tool to make or break a build
    • +
    • need full control over the Clang AST
    • +
    +

    Do not use Clang Plugins when you...

    +
      +
    • want to run tools outside of your build environment
    • +
    • want full control on how Clang is set up, including mapping of in-memory + virtual files
    • +
    • need to run over a specific subset of files in your project which is not + necessarily related to any changes which would trigger rebuilds
    • +
    + + +

    LibTooling

    + + +

    LibTooling is a C++ interface aimed at writing standalone tools, as well as +integrating into services that run clang tools.

    +

    Canonical examples of when to use LibTooling:

    +
      +
    • a simple syntax checker
    • +
    • refactoring tools
    • +
    +

    Use LibTooling when you...

    +
      +
    • want to run tools over a single file, or a specific subset of files, + independently of the build system
    • +
    • want full control over the Clang AST
    • +
    • want to share code with Clang Plugins
    • +
    +

    Do not use LibTooling when you...

    +
      +
    • want to run as part of the build triggered by dependency changes
    • +
    • want a stable interface so you don't need to change your code when the + AST API changes
    • +
    • want high level abstractions like cursors and code completion out of the + box
    • +
    • do not want to write your tools in C++
    • +
    + + +

    Clang Tools

    + + +

    These are a collection of specific developer tools built on top of the +LibTooling infrastructure as part of the Clang project. They are targeted at +automating and improving core development activities of C/C++ developers.

    +

    Examples of tools we are building or planning as part of the Clang +project:

    +
      +
    • Syntax checking (clang-check)
    • +
    • Automatic fixing of compile errors (clangc-fixit)
    • +
    • Automatic code formatting
    • +
    • Migration tools for new features in new language standards
    • +
    • Core refactoring tools
    • +
    + +
    + + + diff --git a/docs/UsersManual.html b/docs/UsersManual.html index b33ed61217bc..69f916c94e84 100644 --- a/docs/UsersManual.html +++ b/docs/UsersManual.html @@ -43,12 +43,14 @@ td {
  • Diagnostic Categories
  • Controlling Diagnostics via Command Line Flags
  • Controlling Diagnostics via Pragmas
  • +
  • Controlling Diagnostics in System Headers
  • Enabling All Warnings
  • Controlling Static Analyzer Diagnostics
  • Precompiled Headers
  • Controlling Code Generation
  • +
  • Controlling Size of Debug Information
  • C Language Features @@ -185,9 +187,10 @@ introduces the language selection and other high level options like -c, -g, etc.

    -Werror=foo: Turn warning "foo" into an error.

    -Wno-error=foo: Turn warning "foo" into an warning even if -Werror is specified.

    -

    -Wfoo: Enable warning foo

    -

    -Wno-foo: Disable warning foo

    +

    -Wfoo: Enable warning "foo".

    +

    -Wno-foo: Disable warning "foo".

    -w: Disable all warnings.

    +

    -Weverything: Enable all warnings.

    -pedantic: Warn on language extensions.

    -pedantic-errors: Error on language extensions.

    -Wsystem-headers: Enable warnings from system headers.

    @@ -227,6 +230,9 @@ print something like:

    When this is disabled, Clang will print "test.c:28: warning..." with no column number.

    + +

    The printed column numbers count bytes from the beginning of the line; take +care if your source contains multibyte characters.

    @@ -393,6 +399,9 @@ exprs.c:47:15:{47:8-47:14}{47:17-47:24}: error: invalid operands to binary expre

    The {}'s are generated by -fdiagnostics-print-source-range-info.

    + +

    The printed column numbers count bytes from the beginning of the line; take +care if your source contains multibyte characters.

    @@ -413,6 +422,51 @@ respectively). Both the file name and the insertion string escape backslash (as "\\"), tabs (as "\t"), newlines (as "\n"), double quotes(as "\"") and non-printable characters (as octal "\xxx").

    + +

    The printed column numbers count bytes from the beginning of the line; take +care if your source contains multibyte characters.

    + + +
    +-fno-elide-type: +Turns off elision in template type printing.
    +

    The default for template type printing is to elide as many template +arguments as possible, removing those which are the same in both template types, +leaving only the differences. Adding this flag will print all the template +arguments. If supported by the terminal, highlighting will still appear on +differing arguments.

    + +Default: +
    +t.cc:4:5: note: candidate function not viable: no known conversion from 'vector<map<[...], map<float, [...]>>>' to 'vector<map<[...], map<double, [...]>>>' for 1st argument;
    +
    +-fno-elide-type: +
    +t.cc:4:5: note: candidate function not viable: no known conversion from 'vector<map<int, map<float, int>>>' to 'vector<map<int, map<double, int>>>' for 1st argument;
    +
    +
    + +
    +-fdiagnostics-show-template-tree: +Template type diffing prints a text tree.
    +

    For diffing large templated types, this option will cause Clang to +display the templates as an indented text tree, one argument per line, with +differences marked inline. This is compatible with -fno-elide-type.

    + +Default: +
    +t.cc:4:5: note: candidate function not viable: no known conversion from 'vector<map<[...], map<float, [...]>>>' to 'vector<map<[...], map<double, [...]>>>' for 1st argument;
    +
    +-fdiagnostics-show-template-tree +
    +t.cc:4:5: note: candidate function not viable: no known conversion for 1st argument;
    +  vector<
    +    map<
    +      [...],
    +      map<
    +        [float != float],
    +        [...]>>>
    +
    @@ -443,9 +497,6 @@ the end of preprocessor directives. For example:

    These extra tokens are not strictly conforming, and are usually best handled by commenting them out.

    - -

    This option is also enabled by -Wfoo, -Wbar, - and -Wbaz.

    @@ -609,7 +660,7 @@ mapping of category names to category id's can be obtained by running 'clang

    Controlling Diagnostics via Command Line Flags

    -

    -W flags, -pedantic, etc

    +

    TODO: -W flags, -pedantic, etc

    Controlling Diagnostics via Pragmas

    @@ -653,6 +704,45 @@ GCC do not support the exact same set of warnings, so even when using GCC compatible #pragmas there is no guarantee that they will have identical behaviour on both compilers.

    +

    Controlling Diagnostics in System Headers

    + +

    Warnings are suppressed when they occur in system headers. By default, an +included file is treated as a system header if it is found in an include path +specified by -isystem, but this can be overridden in several ways.

    + +

    The system_header pragma can be used to mark the current file as +being a system header. No warnings will be produced from the location of the +pragma onwards within the same file.

    + +
    +char a = 'xy'; // warning
    +
    +#pragma clang system_header
    +
    +char b = 'ab'; // no warning
    +
    + +

    The -isystem-prefix and -ino-system-prefix command-line +arguments can be used to override whether subsets of an include path are treated +as system headers. When the name in a #include directive is found +within a header search path and starts with a system prefix, the header is +treated as a system header. The last prefix on the command-line which matches +the specified header name takes precedence. For instance:

    + +
    +clang -Ifoo -isystem bar -isystem-prefix x/ -ino-system-prefix x/y/
    +
    + +

    Here, #include "x/a.h" is treated as including a system header, even +if the header is found in foo, and #include "x/y/b.h" is +treated as not including a system header, even if the header is found in +bar. +

    + +

    A #include directive which finds a file relative to the current +directory is treated as including a system header if the including file is +treated as a system header.

    +

    Enabling All Warnings

    In addition to the traditional -W flags, one can enable all @@ -667,37 +757,11 @@ on both compilers.

    While not strictly part of the compiler, the diagnostics from Clang's static analyzer can also be influenced -by the user via changes to the source code. This can be done in two ways: - -

      - -
    • Annotations: The static analyzer recognizes various GCC-style -attributes (e.g., __attribute__((nonnull)))) that can either suppress -static analyzer warnings or teach the analyzer about code invariants which -enable it to find more bugs. While many of these attributes are standard GCC -attributes, additional ones have been added to Clang to specifically support the -static analyzer. Detailed information on these annotations can be found in the -analyzer's -documentation.
    • - -
    • __clang_analyzer__: When the static analyzer is using Clang -to parse source files, it implicitly defines the preprocessor macro -__clang_analyzer__. While discouraged, code can use this macro to -selectively exclude code the analyzer examines. Here is an example: - -
      -#ifndef __clang_analyzer__
      -// Code not to be analyzed
      -#endif
      -
      - -In general, this usage is discouraged. Instead, we prefer that users file bugs -against the analyzer when it flags false positives. There is also active -discussion of allowing users in the future to selectively silence specific -analyzer warnings (some of which can already be done using annotations).
    • - -
    +by the user via changes to the source code. See the available +annotations and +the analyzer's +FAQ page for +more information.

    Precompiled Headers

    @@ -855,6 +919,39 @@ generator will always lower the builtin to a call to the specified function regardless of whether the target ISA has a trap instruction. This option is useful for environments (e.g. deeply embedded) where a trap cannot be properly handled, or when some custom behavior is desired. + +
    -ftls-model=[model]: Select which TLS model to +use.
    +
    Valid values are: global-dynamic, local-dynamic, +initial-exec and local-exec. The default value is +global-dynamic. The compiler may use a different model if the selected +model is not supported by the target, or if a more efficient model can be used. +The TLS model can be overridden per variable using the tls_model +attribute. +
    + + + +

    Controlling Size of Debug Information

    + + +

    Debug info kind generated by Clang can be set by one of the flags listed +below. If multiple flags are present, the last one is used.

    + + +
    +
    -g0: Don't generate any debug info (default). + +
    -gline-tables-only: +Generate line number tables only. +
    +This kind of debug info allows to obtain stack traces with function +names, file names and line numbers (by such tools as +gdb or addr2line). It doesn't contain any other data (e.g. +description of local variables or function parameters). +
    + +
    -g: Generate complete debug info.
    @@ -937,9 +1034,18 @@ interest in these features yet, so it's hard to say when they will be implemented.
  • clang does not support nested functions; this is a complex feature which -is infrequently used, so it is unlikely to be implemented anytime soon.
  • +is infrequently used, so it is unlikely to be implemented anytime soon. In C++11 +it can be emulated by assigning lambda functions to local variables, e.g: +
    +  auto const local_function = [&](int parameter) {
    +    // Do something
    +  };
    +  ...
    +  local_function(1);
    +
    + -
  • clang does not support global register variables, this is unlikely +
  • clang does not support global register variables; this is unlikely to be implemented soon because it requires additional LLVM backend support.
  • @@ -955,7 +1061,7 @@ in 4.3, the glibc headers will not try to use this extension with clang at the moment.
  • clang does not support the gcc extension for forward-declaring function -parameters; this has not showed up in any real-world code yet, though, so it +parameters; this has not shown up in any real-world code yet, though, so it might never be implemented.
  • @@ -1001,6 +1107,14 @@ support is incomplete; enabling Microsoft extensions will silently drop certain constructs (including __declspec and Microsoft-style asm statements).

    +

    clang has a -fms-compatibility flag that makes clang accept enough +invalid C++ to be able to parse most Microsoft headers. This flag is enabled by +default for Windows targets.

    + +

    -fdelayed-template-parsing lets clang delay all template instantiation until +the end of a translation unit. This flag is enabled by default for Windows +targets.

    +
    • clang allows setting _MSC_VER with -fmsc-version=. It defaults to 1300 which is the same as Visual C/C++ 2003. Any number is supported and can greatly affect @@ -1015,6 +1129,8 @@ record members can be declared using user defined typedefs.
    • controlling record layout. GCC also contains support for this feature, however where MSVC and GCC are incompatible clang follows the MSVC definition. + +
    • clang defaults to C++11 for Windows targets.
    @@ -1092,7 +1208,7 @@ Generating assembly requires a suitable LLVM backend.

    Darwin (Mac OS/X)

    -

    No __thread support, 64-bit ObjC support requires SL tools.

    +

    None

    Windows

    @@ -1100,6 +1216,8 @@ Generating assembly requires a suitable LLVM backend.

    Experimental supports are on Cygming.

    +

    See also Microsoft Extensions.

    +
    Cygwin

    Clang works on Cygwin-1.7.

    @@ -1135,7 +1253,7 @@ Clang assumes directories as below;

  • some_directory/bin/../include
  • -

    This directory layout is standard for any toolchain you will find on the official MinGW-w64 website. +

    This directory layout is standard for any toolchain you will find on the official MinGW-w64 website.

    Clang expects the GCC executable "gcc.exe" compiled for i686-w64-mingw32 (or x86_64-w64-mingw32) to be present on PATH.

    diff --git a/docs/tools/clang.pod b/docs/tools/clang.pod index 8f61568e0761..425a91ef037d 100644 --- a/docs/tools/clang.pod +++ b/docs/tools/clang.pod @@ -303,6 +303,14 @@ This flag sets the default visibility level. This flag specifies that variables without initializers get common linkage. It can be disabled with B<-fno-common>. +=item B<-ftls-model> + +Set the default thread-local storage (TLS) model to use for thread-local +variables. Valid values are: "global-dynamic", "local-dynamic", "initial-exec" +and "local-exec". The default is "global-dynamic". The default model can be +overridden with the tls_model attribute. The compiler will try to choose a more +efficient model if possible. + =item B<-flto> B<-emit-llvm> Generate output files in LLVM formats, suitable for link time optimization. When diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 19d886935d4e..84a5d2cecbe4 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -1,5 +1,5 @@ if(NOT CLANG_BUILD_EXAMPLES) - set(EXCLUDE_FROM_ALL ON) + set_property(DIRECTORY PROPERTY EXCLUDE_FROM_ALL ON) endif() add_subdirectory(analyzer-plugin) diff --git a/examples/PrintFunctionNames/CMakeLists.txt b/examples/PrintFunctionNames/CMakeLists.txt index 86793ce7e187..ba6a350cd954 100644 --- a/examples/PrintFunctionNames/CMakeLists.txt +++ b/examples/PrintFunctionNames/CMakeLists.txt @@ -1,14 +1,23 @@ set(MODULE TRUE) -set( LLVM_USED_LIBS - clangFrontend - clangAST - ) - set( LLVM_LINK_COMPONENTS support mc) add_clang_library(PrintFunctionNames PrintFunctionNames.cpp) +add_dependencies(PrintFunctionNames + ClangAttrClasses + ClangAttrList + ClangCommentNodes + ClangDeclNodes + ClangDiagnosticCommon + ClangStmtNodes + ) + +target_link_libraries(PrintFunctionNames + clangFrontend + clangAST + ) + set_target_properties(PrintFunctionNames PROPERTIES LINKER_LANGUAGE CXX diff --git a/examples/analyzer-plugin/CMakeLists.txt b/examples/analyzer-plugin/CMakeLists.txt index 2b9d82587fff..ba73030cc37b 100644 --- a/examples/analyzer-plugin/CMakeLists.txt +++ b/examples/analyzer-plugin/CMakeLists.txt @@ -1,13 +1,22 @@ set(MODULE TRUE) -set( LLVM_USED_LIBS - clangStaticAnalyzerCore - ) - set( LLVM_LINK_COMPONENTS support mc) add_clang_library(SampleAnalyzerPlugin MainCallChecker.cpp) +add_dependencies(SampleAnalyzerPlugin + ClangAttrClasses + ClangAttrList + ClangCommentNodes + ClangDeclNodes + ClangDiagnosticCommon + ClangStmtNodes + ) + +target_link_libraries(SampleAnalyzerPlugin + clangStaticAnalyzerCore + ) + set_target_properties(SampleAnalyzerPlugin PROPERTIES LINKER_LANGUAGE CXX diff --git a/examples/clang-interpreter/CMakeLists.txt b/examples/clang-interpreter/CMakeLists.txt index 809e324dbe60..9abefc274b1e 100644 --- a/examples/clang-interpreter/CMakeLists.txt +++ b/examples/clang-interpreter/CMakeLists.txt @@ -1,34 +1,37 @@ -set(LLVM_USED_LIBS - clangFrontend - clangSerialization - clangDriver - clangCodeGen - clangSema - clangStaticAnalyzerFrontend - clangStaticAnalyzerCheckers - clangStaticAnalyzerCore - clangAnalysis - clangRewrite - clangAST - clangParse - clangLex - clangBasic - ) - set(LLVM_LINK_COMPONENTS - jit - interpreter - nativecodegen - asmparser - bitreader - bitwriter - codegen - ipo - linker - selectiondag + jit + interpreter + nativecodegen + asmparser + bitreader + bitwriter + codegen + ipo + linker + selectiondag ) add_clang_executable(clang-interpreter main.cpp ) -add_dependencies(clang-interpreter clang-headers) + +add_dependencies(clang-interpreter + clang-headers + ) + +target_link_libraries(clang-interpreter + clangFrontend + clangSerialization + clangDriver + clangCodeGen + clangSema + clangStaticAnalyzerFrontend + clangStaticAnalyzerCheckers + clangStaticAnalyzerCore + clangAnalysis + clangRewrite + clangAST + clangParse + clangLex + clangBasic + ) diff --git a/include/clang-c/CXCompilationDatabase.h b/include/clang-c/CXCompilationDatabase.h new file mode 100644 index 000000000000..d11133cf9328 --- /dev/null +++ b/include/clang-c/CXCompilationDatabase.h @@ -0,0 +1,146 @@ +/*===-- clang-c/CXCompilationDatabase.h - Compilation database ---*- C -*-===*\ +|* *| +|* The LLVM Compiler Infrastructure *| +|* *| +|* This file is distributed under the University of Illinois Open Source *| +|* License. See LICENSE.TXT for details. *| +|* *| +|*===----------------------------------------------------------------------===*| +|* *| +|* This header provides a public inferface to use CompilationDatabase without *| +|* the full Clang C++ API. *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#ifndef CLANG_CXCOMPILATIONDATABASE_H +#define CLANG_CXCOMPILATIONDATABASE_H + +#include "clang-c/Platform.h" +#include "clang-c/CXString.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup COMPILATIONDB CompilationDatabase functions + * \ingroup CINDEX + * + * @{ + */ + +/** + * A compilation database holds all information used to compile files in a + * project. For each file in the database, it can be queried for the working + * directory or the command line used for the compiler invocation. + * + * Must be freed by \c clang_CompilationDatabase_dispose + */ +typedef void * CXCompilationDatabase; + +/** + * \brief Contains the results of a search in the compilation database + * + * When searching for the compile command for a file, the compilation db can + * return several commands, as the file may have been compiled with + * different options in different places of the project. This choice of compile + * commands is wrapped in this opaque data structure. It must be freed by + * \c clang_CompileCommands_dispose. + */ +typedef void * CXCompileCommands; + +/** + * \brief Represents the command line invocation to compile a specific file. + */ +typedef void * CXCompileCommand; + +/** + * \brief Error codes for Compilation Database + */ +typedef enum { + /* + * \brief No error occured + */ + CXCompilationDatabase_NoError = 0, + + /* + * \brief Database can not be loaded + */ + CXCompilationDatabase_CanNotLoadDatabase = 1 + +} CXCompilationDatabase_Error; + +/** + * \brief Creates a compilation database from the database found in directory + * buildDir. For example, CMake can output a compile_commands.json which can + * be used to build the database. + * + * It must be freed by \c clang_CompilationDatabase_dispose. + */ +CINDEX_LINKAGE CXCompilationDatabase +clang_CompilationDatabase_fromDirectory(const char *BuildDir, + CXCompilationDatabase_Error *ErrorCode); + +/** + * \brief Free the given compilation database + */ +CINDEX_LINKAGE void +clang_CompilationDatabase_dispose(CXCompilationDatabase); + +/** + * \brief Find the compile commands used for a file. The compile commands + * must be freed by \c clang_CompileCommands_dispose. + */ +CINDEX_LINKAGE CXCompileCommands +clang_CompilationDatabase_getCompileCommands(CXCompilationDatabase, + const char *CompleteFileName); + +/** + * \brief Free the given CompileCommands + */ +CINDEX_LINKAGE void clang_CompileCommands_dispose(CXCompileCommands); + +/** + * \brief Get the number of CompileCommand we have for a file + */ +CINDEX_LINKAGE unsigned +clang_CompileCommands_getSize(CXCompileCommands); + +/** + * \brief Get the I'th CompileCommand for a file + * + * Note : 0 <= i < clang_CompileCommands_getSize(CXCompileCommands) + */ +CINDEX_LINKAGE CXCompileCommand +clang_CompileCommands_getCommand(CXCompileCommands, unsigned I); + +/** + * \brief Get the working directory where the CompileCommand was executed from + */ +CINDEX_LINKAGE CXString +clang_CompileCommand_getDirectory(CXCompileCommand); + +/** + * \brief Get the number of arguments in the compiler invocation. + * + */ +CINDEX_LINKAGE unsigned +clang_CompileCommand_getNumArgs(CXCompileCommand); + +/** + * \brief Get the I'th argument value in the compiler invocations + * + * Invariant : + * - argument 0 is the compiler executable + */ +CINDEX_LINKAGE CXString +clang_CompileCommand_getArg(CXCompileCommand, unsigned I); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif +#endif + diff --git a/include/clang-c/CXString.h b/include/clang-c/CXString.h new file mode 100644 index 000000000000..74c31660ef10 --- /dev/null +++ b/include/clang-c/CXString.h @@ -0,0 +1,61 @@ +/*===-- clang-c/CXString.h - C Index strings --------------------*- C -*-===*\ +|* *| +|* The LLVM Compiler Infrastructure *| +|* *| +|* This file is distributed under the University of Illinois Open Source *| +|* License. See LICENSE.TXT for details. *| +|* *| +|*===----------------------------------------------------------------------===*| +|* *| +|* This header provides the interface to C Index strings. *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#ifndef CLANG_CXSTRING_H +#define CLANG_CXSTRING_H + +#include "clang-c/Platform.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \defgroup CINDEX_STRING String manipulation routines + * \ingroup CINDEX + * + * @{ + */ + +/** + * \brief A character string. + * + * The \c CXString type is used to return strings from the interface when + * the ownership of that string might different from one call to the next. + * Use \c clang_getCString() to retrieve the string data and, once finished + * with the string data, call \c clang_disposeString() to free the string. + */ +typedef struct { + void *data; + unsigned private_flags; +} CXString; + +/** + * \brief Retrieve the character data associated with the given string. + */ +CINDEX_LINKAGE const char *clang_getCString(CXString string); + +/** + * \brief Free the given string, + */ +CINDEX_LINKAGE void clang_disposeString(CXString string); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif +#endif + diff --git a/include/clang-c/Index.h b/include/clang-c/Index.h index 13ba6ba2ae16..edd3cbb4a7f4 100644 --- a/include/clang-c/Index.h +++ b/include/clang-c/Index.h @@ -20,31 +20,13 @@ #include #include +#include "clang-c/Platform.h" +#include "clang-c/CXString.h" + #ifdef __cplusplus extern "C" { #endif -/* MSVC DLL import/export. */ -#ifdef _MSC_VER - #ifdef _CINDEX_LIB_ - #define CINDEX_LINKAGE __declspec(dllexport) - #else - #define CINDEX_LINKAGE __declspec(dllimport) - #endif -#else - #define CINDEX_LINKAGE -#endif - -#ifdef __GNUC__ - #define CINDEX_DEPRECATED __attribute__((deprecated)) -#else - #ifdef _MSC_VER - #define CINDEX_DEPRECATED __declspec(deprecated) - #else - #define CINDEX_DEPRECATED - #endif -#endif - /** \defgroup CINDEX libclang: C Interface to Clang * * The C Interface to Clang provides a relatively small API that exposes @@ -132,43 +114,34 @@ enum CXAvailabilityKind { */ CXAvailability_NotAccessible }; - -/** - * \defgroup CINDEX_STRING String manipulation routines - * - * @{ - */ - -/** - * \brief A character string. - * - * The \c CXString type is used to return strings from the interface when - * the ownership of that string might different from one call to the next. - * Use \c clang_getCString() to retrieve the string data and, once finished - * with the string data, call \c clang_disposeString() to free the string. - */ -typedef struct { - void *data; - unsigned private_flags; -} CXString; - -/** - * \brief Retrieve the character data associated with the given string. - */ -CINDEX_LINKAGE const char *clang_getCString(CXString string); - -/** - * \brief Free the given string, - */ -CINDEX_LINKAGE void clang_disposeString(CXString string); /** - * @} + * \brief Describes a version number of the form major.minor.subminor. */ - +typedef struct CXVersion { + /** + * \brief The major version number, e.g., the '10' in '10.7.3'. A negative + * value indicates that there is no version number at all. + */ + int Major; + /** + * \brief The minor version number, e.g., the '7' in '10.7.3'. This value + * will be negative if no minor version number was provided, e.g., for + * version '10'. + */ + int Minor; + /** + * \brief The subminor version number, e.g., the '3' in '10.7.3'. This value + * will be negative if no minor or subminor version number was provided, + * e.g., in version '10' or '10.7'. + */ + int Subminor; +} CXVersion; + /** - * \brief clang_createIndex() provides a shared context for creating - * translation units. It provides two options: + * \brief Provides a shared context for creating translation units. + * + * It provides two options: * * - excludeDeclarationsFromPCH: When non-zero, allows enumeration of "local" * declarations (when loading any new translation units). A "local" declaration @@ -178,6 +151,7 @@ CINDEX_LINKAGE void clang_disposeString(CXString string); * * Here is an example: * + * \code * // excludeDeclsFromPCH = 1, displayDiagnostics=1 * Idx = clang_createIndex(1, 1); * @@ -198,6 +172,7 @@ CINDEX_LINKAGE void clang_disposeString(CXString string); * clang_visitChildren(clang_getTranslationUnitCursor(TU), * TranslationUnitVisitor, 0); * clang_disposeTranslationUnit(TU); + * \endcode * * This process of creating the 'pch', loading it separately, and using it (via * -include-pch) allows 'excludeDeclsFromPCH' to remove redundant callbacks @@ -223,16 +198,18 @@ typedef enum { /** * \brief Used to indicate that threads that libclang creates for indexing * purposes should use background priority. - * Affects \see clang_indexSourceFile, \see clang_indexTranslationUnit, - * \see clang_parseTranslationUnit, \see clang_saveTranslationUnit. + * + * Affects #clang_indexSourceFile, #clang_indexTranslationUnit, + * #clang_parseTranslationUnit, #clang_saveTranslationUnit. */ CXGlobalOpt_ThreadBackgroundPriorityForIndexing = 0x1, /** * \brief Used to indicate that threads that libclang creates for editing * purposes should use background priority. - * Affects \see clang_reparseTranslationUnit, \see clang_codeCompleteAt, - * \see clang_annotateTokens + * + * Affects #clang_reparseTranslationUnit, #clang_codeCompleteAt, + * #clang_annotateTokens */ CXGlobalOpt_ThreadBackgroundPriorityForEditing = 0x2, @@ -247,7 +224,7 @@ typedef enum { } CXGlobalOptFlags; /** - * \brief Sets general options associated with a CXIndex. + * \brief Sets general options associated with a CXIndex. * * For example: * \code @@ -294,7 +271,7 @@ CINDEX_LINKAGE time_t clang_getFileTime(CXFile SFile); /** * \brief Determine whether the given header is guarded against * multiple inclusions, either with the conventional - * #ifndef/#define/#endif macro guards or with #pragma once. + * \#ifndef/\#define/\#endif macro guards or with \#pragma once. */ CINDEX_LINKAGE unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file); @@ -359,7 +336,7 @@ typedef struct { CINDEX_LINKAGE CXSourceLocation clang_getNullLocation(); /** - * \determine Determine whether two source locations, which must refer into + * \brief Determine whether two source locations, which must refer into * the same translation unit, refer to exactly the same point in the source * code. * @@ -444,12 +421,14 @@ CINDEX_LINKAGE void clang_getExpansionLocation(CXSourceLocation location, * * Example: given the following source code in a file somefile.c * + * \code * #123 "dummy.c" 1 * * static int func(void) * { * return 0; * } + * \endcode * * the location information returned by this function would be * @@ -486,7 +465,7 @@ CINDEX_LINKAGE void clang_getPresumedLocation(CXSourceLocation location, * by the given source location. * * This interface has been replaced by the newer interface - * \see clang_getExpansionLocation(). See that interface's documentation for + * #clang_getExpansionLocation(). See that interface's documentation for * details. */ CINDEX_LINKAGE void clang_getInstantiationLocation(CXSourceLocation location, @@ -599,7 +578,7 @@ CINDEX_LINKAGE unsigned clang_getNumDiagnosticsInSet(CXDiagnosticSet Diags); /** * \brief Retrieve a diagnostic associated with the given CXDiagnosticSet. * - * \param Unit the CXDiagnosticSet to query. + * \param Diags the CXDiagnosticSet to query. * \param Index the zero-based diagnostic number to retrieve. * * \returns the requested diagnostic. This diagnostic must be freed @@ -633,23 +612,23 @@ enum CXLoadDiag_Error { /** * \brief Indicates that the serialized diagnostics file is invalid or - * corrupt. + * corrupt. */ CXLoadDiag_InvalidFile = 3 }; /** * \brief Deserialize a set of diagnostics from a Clang diagnostics bitcode - * file. + * file. * - * \param The name of the file to deserialize. - * \param A pointer to a enum value recording if there was a problem + * \param file The name of the file to deserialize. + * \param error A pointer to a enum value recording if there was a problem * deserializing the diagnostics. - * \param A pointer to a CXString for recording the error string + * \param errorString A pointer to a CXString for recording the error string * if the file was not successfully loaded. * * \returns A loaded CXDiagnosticSet if successful, and NULL otherwise. These - * diagnostics should be released using clang_disposeDiagnosticSet(). + * diagnostics should be released using clang_disposeDiagnosticSet(). */ CINDEX_LINKAGE CXDiagnosticSet clang_loadDiagnostics(const char *file, enum CXLoadDiag_Error *error, @@ -661,8 +640,10 @@ CINDEX_LINKAGE CXDiagnosticSet clang_loadDiagnostics(const char *file, CINDEX_LINKAGE void clang_disposeDiagnosticSet(CXDiagnosticSet Diags); /** - * \brief Retrieve the child diagnostics of a CXDiagnostic. This - * CXDiagnosticSet does not need to be released by clang_diposeDiagnosticSet. + * \brief Retrieve the child diagnostics of a CXDiagnostic. + * + * This CXDiagnosticSet does not need to be released by + * clang_diposeDiagnosticSet. */ CINDEX_LINKAGE CXDiagnosticSet clang_getChildDiagnostics(CXDiagnostic D); @@ -855,7 +836,6 @@ CXString clang_getDiagnosticCategoryName(unsigned Category); /** * \brief Retrieve the diagnostic category text for a given diagnostic. * - * * \returns The text of the given diagnostic category. */ CINDEX_LINKAGE CXString clang_getDiagnosticCategoryText(CXDiagnostic); @@ -951,12 +931,12 @@ clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit); * '-c' * '-emit-ast' * '-fsyntax-only' - * '-o ' (both '-o' and '' are ignored) + * '-o \' (both '-o' and '\' are ignored) * * \param CIdx The index object with which the translation unit will be * associated. * - * \param source_filename - The name of the source file to load, or NULL if the + * \param source_filename The name of the source file to load, or NULL if the * source file is included in \p clang_command_line_args. * * \param num_clang_command_line_args The number of command-line arguments in @@ -966,7 +946,7 @@ clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit); * passed to the \c clang executable if it were being invoked out-of-process. * These command-line options will be parsed and will affect how the translation * unit is parsed. Note that the following options are ignored: '-c', - * '-emit-ast', '-fsyntex-only' (which is the default), and '-o '. + * '-emit-ast', '-fsyntax-only' (which is the default), and '-o \'. * * \param num_unsaved_files the number of unsaved file entries in \p * unsaved_files. @@ -1078,7 +1058,14 @@ enum CXTranslationUnit_Flags { * This option can be used to search for declarations/definitions while * ignoring the usages. */ - CXTranslationUnit_SkipFunctionBodies = 0x40 + CXTranslationUnit_SkipFunctionBodies = 0x40, + + /** + * \brief Used to indicate that brief documentation comments should be + * included into the set of code completions returned from this translation + * unit. + */ + CXTranslationUnit_IncludeBriefCommentsInCodeCompletion = 0x80 }; /** @@ -1115,7 +1102,7 @@ CINDEX_LINKAGE unsigned clang_defaultEditingTranslationUnitOptions(void); * passed to the \c clang executable if it were being invoked out-of-process. * These command-line options will be parsed and will affect how the translation * unit is parsed. Note that the following options are ignored: '-c', - * '-emit-ast', '-fsyntex-only' (which is the default), and '-o '. + * '-emit-ast', '-fsyntax-only' (which is the default), and '-o \'. * * \param num_command_line_args The number of command-line arguments in * \p command_line_args. @@ -1411,13 +1398,13 @@ enum CXCursorKind { CXCursor_VarDecl = 9, /** \brief A function or method parameter. */ CXCursor_ParmDecl = 10, - /** \brief An Objective-C @interface. */ + /** \brief An Objective-C \@interface. */ CXCursor_ObjCInterfaceDecl = 11, - /** \brief An Objective-C @interface for a category. */ + /** \brief An Objective-C \@interface for a category. */ CXCursor_ObjCCategoryDecl = 12, - /** \brief An Objective-C @protocol declaration. */ + /** \brief An Objective-C \@protocol declaration. */ CXCursor_ObjCProtocolDecl = 13, - /** \brief An Objective-C @property declaration. */ + /** \brief An Objective-C \@property declaration. */ CXCursor_ObjCPropertyDecl = 14, /** \brief An Objective-C instance variable. */ CXCursor_ObjCIvarDecl = 15, @@ -1425,9 +1412,9 @@ enum CXCursorKind { CXCursor_ObjCInstanceMethodDecl = 16, /** \brief An Objective-C class method. */ CXCursor_ObjCClassMethodDecl = 17, - /** \brief An Objective-C @implementation. */ + /** \brief An Objective-C \@implementation. */ CXCursor_ObjCImplementationDecl = 18, - /** \brief An Objective-C @implementation for a category. */ + /** \brief An Objective-C \@implementation for a category. */ CXCursor_ObjCCategoryImplDecl = 19, /** \brief A typedef */ CXCursor_TypedefDecl = 20, @@ -1463,9 +1450,9 @@ enum CXCursorKind { CXCursor_UsingDeclaration = 35, /** \brief A C++ alias declaration */ CXCursor_TypeAliasDecl = 36, - /** \brief An Objective-C @synthesize definition. */ + /** \brief An Objective-C \@synthesize definition. */ CXCursor_ObjCSynthesizeDecl = 37, - /** \brief An Objective-C @dynamic definition. */ + /** \brief An Objective-C \@dynamic definition. */ CXCursor_ObjCDynamicDecl = 38, /** \brief An access specifier. */ CXCursor_CXXAccessSpecifier = 39, @@ -1768,15 +1755,15 @@ enum CXCursorKind { */ CXCursor_ObjCStringLiteral = 137, - /** \brief An Objective-C @encode expression. + /** \brief An Objective-C \@encode expression. */ CXCursor_ObjCEncodeExpr = 138, - /** \brief An Objective-C @selector expression. + /** \brief An Objective-C \@selector expression. */ CXCursor_ObjCSelectorExpr = 139, - /** \brief An Objective-C @protocol expression. + /** \brief An Objective-C \@protocol expression. */ CXCursor_ObjCProtocolExpr = 140, @@ -1921,23 +1908,23 @@ enum CXCursorKind { */ CXCursor_AsmStmt = 215, - /** \brief Objective-C's overall @try-@catch-@finally statement. + /** \brief Objective-C's overall \@try-\@catch-\@finally statement. */ CXCursor_ObjCAtTryStmt = 216, - /** \brief Objective-C's @catch statement. + /** \brief Objective-C's \@catch statement. */ CXCursor_ObjCAtCatchStmt = 217, - /** \brief Objective-C's @finally statement. + /** \brief Objective-C's \@finally statement. */ CXCursor_ObjCAtFinallyStmt = 218, - /** \brief Objective-C's @throw statement. + /** \brief Objective-C's \@throw statement. */ CXCursor_ObjCAtThrowStmt = 219, - /** \brief Objective-C's @synchronized statement. + /** \brief Objective-C's \@synchronized statement. */ CXCursor_ObjCAtSynchronizedStmt = 220, @@ -1973,6 +1960,10 @@ enum CXCursorKind { */ CXCursor_SEHFinallyStmt = 228, + /** \brief A MS inline assembly statement extension. + */ + CXCursor_MSAsmStmt = 229, + /** \brief The null satement ";": C99 6.8.3p3. * * This cursor kind is used to describe the null statement. @@ -2045,6 +2036,13 @@ typedef struct { void *data[3]; } CXCursor; +/** + * \brief A comment AST node. + */ +typedef struct { + const void *Data; +} CXComment; + /** * \defgroup CINDEX_CURSOR_MANIP Cursor manipulations * @@ -2165,7 +2163,8 @@ enum CXLinkageKind { CINDEX_LINKAGE enum CXLinkageKind clang_getCursorLinkage(CXCursor cursor); /** - * \brief Determine the availability of the entity that this cursor refers to. + * \brief Determine the availability of the entity that this cursor refers to, + * taking the current target platform into account. * * \param cursor The cursor to query. * @@ -2174,6 +2173,94 @@ CINDEX_LINKAGE enum CXLinkageKind clang_getCursorLinkage(CXCursor cursor); CINDEX_LINKAGE enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor); +/** + * Describes the availability of a given entity on a particular platform, e.g., + * a particular class might only be available on Mac OS 10.7 or newer. + */ +typedef struct CXPlatformAvailability { + /** + * \brief A string that describes the platform for which this structure + * provides availability information. + * + * Possible values are "ios" or "macosx". + */ + CXString Platform; + /** + * \brief The version number in which this entity was introduced. + */ + CXVersion Introduced; + /** + * \brief The version number in which this entity was deprecated (but is + * still available). + */ + CXVersion Deprecated; + /** + * \brief The version number in which this entity was obsoleted, and therefore + * is no longer available. + */ + CXVersion Obsoleted; + /** + * \brief Whether the entity is unconditionally unavailable on this platform. + */ + int Unavailable; + /** + * \brief An optional message to provide to a user of this API, e.g., to + * suggest replacement APIs. + */ + CXString Message; +} CXPlatformAvailability; + +/** + * \brief Determine the availability of the entity that this cursor refers to + * on any platforms for which availability information is known. + * + * \param cursor The cursor to query. + * + * \param always_deprecated If non-NULL, will be set to indicate whether the + * entity is deprecated on all platforms. + * + * \param deprecated_message If non-NULL, will be set to the message text + * provided along with the unconditional deprecation of this entity. The client + * is responsible for deallocating this string. + * + * \param always_unavailable If non-NULL, will be set to indicate whether the + * entity is unavailable on all platforms. + * + * \param unavailable_message If non-NULL, will be set to the message text + * provided along with the unconditional unavailability of this entity. The + * client is responsible for deallocating this string. + * + * \param availability If non-NULL, an array of CXPlatformAvailability instances + * that will be populated with platform availability information, up to either + * the number of platforms for which availability information is available (as + * returned by this function) or \c availability_size, whichever is smaller. + * + * \param availability_size The number of elements available in the + * \c availability array. + * + * \returns The number of platforms (N) for which availability information is + * available (which is unrelated to \c availability_size). + * + * Note that the client is responsible for calling + * \c clang_disposeCXPlatformAvailability to free each of the + * platform-availability structures returned. There are + * \c min(N, availability_size) such structures. + */ +CINDEX_LINKAGE int +clang_getCursorPlatformAvailability(CXCursor cursor, + int *always_deprecated, + CXString *deprecated_message, + int *always_unavailable, + CXString *unavailable_message, + CXPlatformAvailability *availability, + int availability_size); + +/** + * \brief Free the memory associated with a \c CXPlatformAvailability structure. + */ +CINDEX_LINKAGE void +clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability); + /** * \brief Describe the "language" of the entity referred to by a cursor. */ @@ -2571,10 +2658,10 @@ CINDEX_LINKAGE int clang_Cursor_getNumArguments(CXCursor C); CINDEX_LINKAGE CXCursor clang_Cursor_getArgument(CXCursor C, unsigned i); /** - * \determine Determine whether two CXTypes represent the same type. + * \brief Determine whether two CXTypes represent the same type. * - * \returns non-zero if the CXTypes represent the same type and - zero otherwise. + * \returns non-zero if the CXTypes represent the same type and + * zero otherwise. */ CINDEX_LINKAGE unsigned clang_equalTypes(CXType A, CXType B); @@ -2589,26 +2676,28 @@ CINDEX_LINKAGE unsigned clang_equalTypes(CXType A, CXType B); CINDEX_LINKAGE CXType clang_getCanonicalType(CXType T); /** - * \determine Determine whether a CXType has the "const" qualifier set, - * without looking through typedefs that may have added "const" at a different level. + * \brief Determine whether a CXType has the "const" qualifier set, + * without looking through typedefs that may have added "const" at a + * different level. */ CINDEX_LINKAGE unsigned clang_isConstQualifiedType(CXType T); /** - * \determine Determine whether a CXType has the "volatile" qualifier set, - * without looking through typedefs that may have added "volatile" at a different level. + * \brief Determine whether a CXType has the "volatile" qualifier set, + * without looking through typedefs that may have added "volatile" at + * a different level. */ CINDEX_LINKAGE unsigned clang_isVolatileQualifiedType(CXType T); /** - * \determine Determine whether a CXType has the "restrict" qualifier set, - * without looking through typedefs that may have added "restrict" at a different level. + * \brief Determine whether a CXType has the "restrict" qualifier set, + * without looking through typedefs that may have added "restrict" at a + * different level. */ CINDEX_LINKAGE unsigned clang_isRestrictQualifiedType(CXType T); /** * \brief For pointer types, returns the type of the pointee. - * */ CINDEX_LINKAGE CXType clang_getPointeeType(CXType T); @@ -2642,7 +2731,8 @@ CINDEX_LINKAGE enum CXCallingConv clang_getFunctionTypeCallingConv(CXType T); CINDEX_LINKAGE CXType clang_getResultType(CXType T); /** - * \brief Retrieve the number of non-variadic arguments associated with a function type. + * \brief Retrieve the number of non-variadic arguments associated with a + * function type. * * If a non-function type is passed in, -1 is returned. */ @@ -2651,14 +2741,13 @@ CINDEX_LINKAGE int clang_getNumArgTypes(CXType T); /** * \brief Retrieve the type of an argument of a function type. * - * If a non-function type is passed in or the function does not have enough parameters, - * an invalid type is returned. + * If a non-function type is passed in or the function does not have enough + * parameters, an invalid type is returned. */ CINDEX_LINKAGE CXType clang_getArgType(CXType T, unsigned i); /** * \brief Return 1 if the CXType is a variadic function type, and 0 otherwise. - * */ CINDEX_LINKAGE unsigned clang_isFunctionTypeVariadic(CXType T); @@ -2699,7 +2788,7 @@ CINDEX_LINKAGE long long clang_getNumElements(CXType T); CINDEX_LINKAGE CXType clang_getArrayElementType(CXType T); /** - * \brief Return the the array size of a constant array. + * \brief Return the array size of a constant array. * * If a non-array type is passed in, -1 is returned. */ @@ -3052,7 +3141,7 @@ CINDEX_LINKAGE CXCursor clang_getCanonicalCursor(CXCursor); * \brief If the cursor points to a selector identifier in a objc method or * message expression, this returns the selector index. * - * After getting a cursor with \see clang_getCursor, this can be called to + * After getting a cursor with #clang_getCursor, this can be called to * determine if the location points to a selector identifier. * * \returns The selector index if the cursor is an objc method or message @@ -3061,6 +3150,557 @@ CINDEX_LINKAGE CXCursor clang_getCanonicalCursor(CXCursor); */ CINDEX_LINKAGE int clang_Cursor_getObjCSelectorIndex(CXCursor); +/** + * \brief Given a cursor pointing to a C++ method call or an ObjC message, + * returns non-zero if the method/message is "dynamic", meaning: + * + * For a C++ method: the call is virtual. + * For an ObjC message: the receiver is an object instance, not 'super' or a + * specific class. + * + * If the method/message is "static" or the cursor does not point to a + * method/message, it will return zero. + */ +CINDEX_LINKAGE int clang_Cursor_isDynamicCall(CXCursor C); + +/** + * \brief Given a cursor that represents a declaration, return the associated + * comment's source range. The range may include multiple consecutive comments + * with whitespace in between. + */ +CINDEX_LINKAGE CXSourceRange clang_Cursor_getCommentRange(CXCursor C); + +/** + * \brief Given a cursor that represents a declaration, return the associated + * comment text, including comment markers. + */ +CINDEX_LINKAGE CXString clang_Cursor_getRawCommentText(CXCursor C); + +/** + * \brief Given a cursor that represents a documentable entity (e.g., + * declaration), return the associated \\brief paragraph; otherwise return the + * first paragraph. + */ +CINDEX_LINKAGE CXString clang_Cursor_getBriefCommentText(CXCursor C); + +/** + * \brief Given a cursor that represents a documentable entity (e.g., + * declaration), return the associated parsed comment as a + * \c CXComment_FullComment AST node. + */ +CINDEX_LINKAGE CXComment clang_Cursor_getParsedComment(CXCursor C); + +/** + * @} + */ + +/** + * \defgroup CINDEX_COMMENT Comment AST introspection + * + * The routines in this group provide access to information in the + * documentation comment ASTs. + * + * @{ + */ + +/** + * \brief Describes the type of the comment AST node (\c CXComment). A comment + * node can be considered block content (e. g., paragraph), inline content + * (plain text) or neither (the root AST node). + */ +enum CXCommentKind { + /** + * \brief Null comment. No AST node is constructed at the requested location + * because there is no text or a syntax error. + */ + CXComment_Null = 0, + + /** + * \brief Plain text. Inline content. + */ + CXComment_Text = 1, + + /** + * \brief A command with word-like arguments that is considered inline content. + * + * For example: \\c command. + */ + CXComment_InlineCommand = 2, + + /** + * \brief HTML start tag with attributes (name-value pairs). Considered + * inline content. + * + * For example: + * \verbatim + *

    + * \endverbatim + */ + CXComment_HTMLStartTag = 3, + + /** + * \brief HTML end tag. Considered inline content. + * + * For example: + * \verbatim + * + * \endverbatim + */ + CXComment_HTMLEndTag = 4, + + /** + * \brief A paragraph, contains inline comment. The paragraph itself is + * block content. + */ + CXComment_Paragraph = 5, + + /** + * \brief A command that has zero or more word-like arguments (number of + * word-like arguments depends on command name) and a paragraph as an + * argument. Block command is block content. + * + * Paragraph argument is also a child of the block command. + * + * For example: \\brief has 0 word-like arguments and a paragraph argument. + * + * AST nodes of special kinds that parser knows about (e. g., \\param + * command) have their own node kinds. + */ + CXComment_BlockCommand = 6, + + /** + * \brief A \\param or \\arg command that describes the function parameter + * (name, passing direction, description). + * + * \brief For example: \\param [in] ParamName description. + */ + CXComment_ParamCommand = 7, + + /** + * \brief A \\tparam command that describes a template parameter (name and + * description). + * + * \brief For example: \\tparam T description. + */ + CXComment_TParamCommand = 8, + + /** + * \brief A verbatim block command (e. g., preformatted code). Verbatim + * block has an opening and a closing command and contains multiple lines of + * text (\c CXComment_VerbatimBlockLine child nodes). + * + * For example: + * \\verbatim + * aaa + * \\endverbatim + */ + CXComment_VerbatimBlockCommand = 9, + + /** + * \brief A line of text that is contained within a + * CXComment_VerbatimBlockCommand node. + */ + CXComment_VerbatimBlockLine = 10, + + /** + * \brief A verbatim line command. Verbatim line has an opening command, + * a single line of text (up to the newline after the opening command) and + * has no closing command. + */ + CXComment_VerbatimLine = 11, + + /** + * \brief A full comment attached to a declaration, contains block content. + */ + CXComment_FullComment = 12 +}; + +/** + * \brief The most appropriate rendering mode for an inline command, chosen on + * command semantics in Doxygen. + */ +enum CXCommentInlineCommandRenderKind { + /** + * \brief Command argument should be rendered in a normal font. + */ + CXCommentInlineCommandRenderKind_Normal, + + /** + * \brief Command argument should be rendered in a bold font. + */ + CXCommentInlineCommandRenderKind_Bold, + + /** + * \brief Command argument should be rendered in a monospaced font. + */ + CXCommentInlineCommandRenderKind_Monospaced, + + /** + * \brief Command argument should be rendered emphasized (typically italic + * font). + */ + CXCommentInlineCommandRenderKind_Emphasized +}; + +/** + * \brief Describes parameter passing direction for \\param or \\arg command. + */ +enum CXCommentParamPassDirection { + /** + * \brief The parameter is an input parameter. + */ + CXCommentParamPassDirection_In, + + /** + * \brief The parameter is an output parameter. + */ + CXCommentParamPassDirection_Out, + + /** + * \brief The parameter is an input and output parameter. + */ + CXCommentParamPassDirection_InOut +}; + +/** + * \param Comment AST node of any kind. + * + * \returns the type of the AST node. + */ +CINDEX_LINKAGE enum CXCommentKind clang_Comment_getKind(CXComment Comment); + +/** + * \param Comment AST node of any kind. + * + * \returns number of children of the AST node. + */ +CINDEX_LINKAGE unsigned clang_Comment_getNumChildren(CXComment Comment); + +/** + * \param Comment AST node of any kind. + * + * \param ArgIdx argument index (zero-based). + * + * \returns the specified child of the AST node. + */ +CINDEX_LINKAGE +CXComment clang_Comment_getChild(CXComment Comment, unsigned ChildIdx); + +/** + * \brief A \c CXComment_Paragraph node is considered whitespace if it contains + * only \c CXComment_Text nodes that are empty or whitespace. + * + * Other AST nodes (except \c CXComment_Paragraph and \c CXComment_Text) are + * never considered whitespace. + * + * \returns non-zero if \c Comment is whitespace. + */ +CINDEX_LINKAGE unsigned clang_Comment_isWhitespace(CXComment Comment); + +/** + * \returns non-zero if \c Comment is inline content and has a newline + * immediately following it in the comment text. Newlines between paragraphs + * do not count. + */ +CINDEX_LINKAGE +unsigned clang_InlineContentComment_hasTrailingNewline(CXComment Comment); + +/** + * \param Comment a \c CXComment_Text AST node. + * + * \returns text contained in the AST node. + */ +CINDEX_LINKAGE CXString clang_TextComment_getText(CXComment Comment); + +/** + * \param Comment a \c CXComment_InlineCommand AST node. + * + * \returns name of the inline command. + */ +CINDEX_LINKAGE +CXString clang_InlineCommandComment_getCommandName(CXComment Comment); + +/** + * \param Comment a \c CXComment_InlineCommand AST node. + * + * \returns the most appropriate rendering mode, chosen on command + * semantics in Doxygen. + */ +CINDEX_LINKAGE enum CXCommentInlineCommandRenderKind +clang_InlineCommandComment_getRenderKind(CXComment Comment); + +/** + * \param Comment a \c CXComment_InlineCommand AST node. + * + * \returns number of command arguments. + */ +CINDEX_LINKAGE +unsigned clang_InlineCommandComment_getNumArgs(CXComment Comment); + +/** + * \param Comment a \c CXComment_InlineCommand AST node. + * + * \param ArgIdx argument index (zero-based). + * + * \returns text of the specified argument. + */ +CINDEX_LINKAGE +CXString clang_InlineCommandComment_getArgText(CXComment Comment, + unsigned ArgIdx); + +/** + * \param Comment a \c CXComment_HTMLStartTag or \c CXComment_HTMLEndTag AST + * node. + * + * \returns HTML tag name. + */ +CINDEX_LINKAGE CXString clang_HTMLTagComment_getTagName(CXComment Comment); + +/** + * \param Comment a \c CXComment_HTMLStartTag AST node. + * + * \returns non-zero if tag is self-closing (for example, <br />). + */ +CINDEX_LINKAGE +unsigned clang_HTMLStartTagComment_isSelfClosing(CXComment Comment); + +/** + * \param Comment a \c CXComment_HTMLStartTag AST node. + * + * \returns number of attributes (name-value pairs) attached to the start tag. + */ +CINDEX_LINKAGE unsigned clang_HTMLStartTag_getNumAttrs(CXComment Comment); + +/** + * \param Comment a \c CXComment_HTMLStartTag AST node. + * + * \param AttrIdx attribute index (zero-based). + * + * \returns name of the specified attribute. + */ +CINDEX_LINKAGE +CXString clang_HTMLStartTag_getAttrName(CXComment Comment, unsigned AttrIdx); + +/** + * \param Comment a \c CXComment_HTMLStartTag AST node. + * + * \param AttrIdx attribute index (zero-based). + * + * \returns value of the specified attribute. + */ +CINDEX_LINKAGE +CXString clang_HTMLStartTag_getAttrValue(CXComment Comment, unsigned AttrIdx); + +/** + * \param Comment a \c CXComment_BlockCommand AST node. + * + * \returns name of the block command. + */ +CINDEX_LINKAGE +CXString clang_BlockCommandComment_getCommandName(CXComment Comment); + +/** + * \param Comment a \c CXComment_BlockCommand AST node. + * + * \returns number of word-like arguments. + */ +CINDEX_LINKAGE +unsigned clang_BlockCommandComment_getNumArgs(CXComment Comment); + +/** + * \param Comment a \c CXComment_BlockCommand AST node. + * + * \param ArgIdx argument index (zero-based). + * + * \returns text of the specified word-like argument. + */ +CINDEX_LINKAGE +CXString clang_BlockCommandComment_getArgText(CXComment Comment, + unsigned ArgIdx); + +/** + * \param Comment a \c CXComment_BlockCommand or + * \c CXComment_VerbatimBlockCommand AST node. + * + * \returns paragraph argument of the block command. + */ +CINDEX_LINKAGE +CXComment clang_BlockCommandComment_getParagraph(CXComment Comment); + +/** + * \param Comment a \c CXComment_ParamCommand AST node. + * + * \returns parameter name. + */ +CINDEX_LINKAGE +CXString clang_ParamCommandComment_getParamName(CXComment Comment); + +/** + * \param Comment a \c CXComment_ParamCommand AST node. + * + * \returns non-zero if the parameter that this AST node represents was found + * in the function prototype and \c clang_ParamCommandComment_getParamIndex + * function will return a meaningful value. + */ +CINDEX_LINKAGE +unsigned clang_ParamCommandComment_isParamIndexValid(CXComment Comment); + +/** + * \param Comment a \c CXComment_ParamCommand AST node. + * + * \returns zero-based parameter index in function prototype. + */ +CINDEX_LINKAGE +unsigned clang_ParamCommandComment_getParamIndex(CXComment Comment); + +/** + * \param Comment a \c CXComment_ParamCommand AST node. + * + * \returns non-zero if parameter passing direction was specified explicitly in + * the comment. + */ +CINDEX_LINKAGE +unsigned clang_ParamCommandComment_isDirectionExplicit(CXComment Comment); + +/** + * \param Comment a \c CXComment_ParamCommand AST node. + * + * \returns parameter passing direction. + */ +CINDEX_LINKAGE +enum CXCommentParamPassDirection clang_ParamCommandComment_getDirection( + CXComment Comment); + +/** + * \param Comment a \c CXComment_TParamCommand AST node. + * + * \returns template parameter name. + */ +CINDEX_LINKAGE +CXString clang_TParamCommandComment_getParamName(CXComment Comment); + +/** + * \param Comment a \c CXComment_TParamCommand AST node. + * + * \returns non-zero if the parameter that this AST node represents was found + * in the template parameter list and + * \c clang_TParamCommandComment_getDepth and + * \c clang_TParamCommandComment_getIndex functions will return a meaningful + * value. + */ +CINDEX_LINKAGE +unsigned clang_TParamCommandComment_isParamPositionValid(CXComment Comment); + +/** + * \param Comment a \c CXComment_TParamCommand AST node. + * + * \returns zero-based nesting depth of this parameter in the template parameter list. + * + * For example, + * \verbatim + * template class TT> + * void test(TT aaa); + * \endverbatim + * for C and TT nesting depth is 0, + * for T nesting depth is 1. + */ +CINDEX_LINKAGE +unsigned clang_TParamCommandComment_getDepth(CXComment Comment); + +/** + * \param Comment a \c CXComment_TParamCommand AST node. + * + * \returns zero-based parameter index in the template parameter list at a + * given nesting depth. + * + * For example, + * \verbatim + * template class TT> + * void test(TT aaa); + * \endverbatim + * for C and TT nesting depth is 0, so we can ask for index at depth 0: + * at depth 0 C's index is 0, TT's index is 1. + * + * For T nesting depth is 1, so we can ask for index at depth 0 and 1: + * at depth 0 T's index is 1 (same as TT's), + * at depth 1 T's index is 0. + */ +CINDEX_LINKAGE +unsigned clang_TParamCommandComment_getIndex(CXComment Comment, unsigned Depth); + +/** + * \param Comment a \c CXComment_VerbatimBlockLine AST node. + * + * \returns text contained in the AST node. + */ +CINDEX_LINKAGE +CXString clang_VerbatimBlockLineComment_getText(CXComment Comment); + +/** + * \param Comment a \c CXComment_VerbatimLine AST node. + * + * \returns text contained in the AST node. + */ +CINDEX_LINKAGE CXString clang_VerbatimLineComment_getText(CXComment Comment); + +/** + * \brief Convert an HTML tag AST node to string. + * + * \param Comment a \c CXComment_HTMLStartTag or \c CXComment_HTMLEndTag AST + * node. + * + * \returns string containing an HTML tag. + */ +CINDEX_LINKAGE CXString clang_HTMLTagComment_getAsString(CXComment Comment); + +/** + * \brief Convert a given full parsed comment to an HTML fragment. + * + * Specific details of HTML layout are subject to change. Don't try to parse + * this HTML back into an AST, use other APIs instead. + * + * Currently the following CSS classes are used: + * \li "para-brief" for \\brief paragraph and equivalent commands; + * \li "para-returns" for \\returns paragraph and equivalent commands; + * \li "word-returns" for the "Returns" word in \\returns paragraph. + * + * Function argument documentation is rendered as a \ list with arguments + * sorted in function prototype order. CSS classes used: + * \li "param-name-index-NUMBER" for parameter name (\); + * \li "param-descr-index-NUMBER" for parameter description (\); + * \li "param-name-index-invalid" and "param-descr-index-invalid" are used if + * parameter index is invalid. + * + * Template parameter documentation is rendered as a \ list with + * parameters sorted in template parameter list order. CSS classes used: + * \li "tparam-name-index-NUMBER" for parameter name (\); + * \li "tparam-descr-index-NUMBER" for parameter description (\); + * \li "tparam-name-index-other" and "tparam-descr-index-other" are used for + * names inside template template parameters; + * \li "tparam-name-index-invalid" and "tparam-descr-index-invalid" are used if + * parameter position is invalid. + * + * \param Comment a \c CXComment_FullComment AST node. + * + * \returns string containing an HTML fragment. + */ +CINDEX_LINKAGE CXString clang_FullComment_getAsHTML(CXComment Comment); + +/** + * \brief Convert a given full parsed comment to an XML document. + * + * A Relax NG schema for the XML can be found in comment-xml-schema.rng file + * inside clang source tree. + * + * \param TU the translation unit \c Comment belongs to. + * + * \param Comment a \c CXComment_FullComment AST node. + * + * \returns string containing an XML document. + */ +CINDEX_LINKAGE CXString clang_FullComment_getAsXML(CXTranslationUnit TU, + CXComment Comment); + /** * @} */ @@ -3148,7 +3788,7 @@ CINDEX_LINKAGE CXCursor clang_getSpecializedCursorTemplate(CXCursor C); * \param PieceIndex For contiguous names or when passing the flag * CXNameRange_WantSinglePiece, only one piece with index 0 is * available. When the CXNameRange_WantSinglePiece flag is not passed for a - * non-contiguous names, this index can be used to retreive the individual + * non-contiguous names, this index can be used to retrieve the individual * pieces of the name. See also CXNameRange_WantSinglePiece. * * \returns The piece of the name pointed to by the given cursor. If there is no @@ -3166,8 +3806,8 @@ enum CXNameRefFlags { CXNameRange_WantQualifier = 0x1, /** - * \brief Include the explicit template arguments, e.g. in x.f, in - * the range. + * \brief Include the explicit template arguments, e.g. \ in x.f, + * in the range. */ CXNameRange_WantTemplateArgs = 0x2, @@ -3686,12 +4326,20 @@ clang_getCompletionAnnotation(CXCompletionString completion_string, * \param kind If non-NULL, will be set to the kind of the parent context, * or CXCursor_NotImplemented if there is no context. * - * \param Returns the name of the completion parent, e.g., "NSObject" if + * \returns The name of the completion parent, e.g., "NSObject" if * the completion string represents a method in the NSObject class. */ CINDEX_LINKAGE CXString clang_getCompletionParent(CXCompletionString completion_string, enum CXCursorKind *kind); + +/** + * \brief Retrieve the brief documentation comment attached to the declaration + * that corresponds to the given completion string. + */ +CINDEX_LINKAGE CXString +clang_getCompletionBriefComment(CXCompletionString completion_string); + /** * \brief Retrieve a completion string for an arbitrary declaration or macro * definition cursor. @@ -3742,7 +4390,13 @@ enum CXCodeComplete_Flags { * \brief Whether to include code patterns for language constructs * within the set of code completions, e.g., for loops. */ - CXCodeComplete_IncludeCodePatterns = 0x02 + CXCodeComplete_IncludeCodePatterns = 0x02, + + /** + * \brief Whether to include brief documentation within the set of code + * completions returned. + */ + CXCodeComplete_IncludeBriefComments = 0x04 }; /** @@ -3986,7 +4640,7 @@ unsigned clang_codeCompleteGetNumDiagnostics(CXCodeCompleteResults *Results); /** * \brief Retrieve a diagnostic associated with the given code completion. * - * \param Result the code completion results to query. + * \param Results the code completion results to query. * \param Index the zero-based diagnostic number to retrieve. * * \returns the requested diagnostic. This diagnostic must be freed @@ -4078,8 +4732,8 @@ CINDEX_LINKAGE CXString clang_getClangVersion(); /** * \brief Enable/disable crash recovery. * - * \param Flag to indicate if crash recovery is enabled. A non-zero value - * enables crash recovery, while 0 disables it. + * \param isEnabled Flag to indicate if crash recovery is enabled. A non-zero + * value enables crash recovery, while 0 disables it. */ CINDEX_LINKAGE void clang_toggleCrashRecovery(unsigned isEnabled); @@ -4088,7 +4742,7 @@ CINDEX_LINKAGE void clang_toggleCrashRecovery(unsigned isEnabled); * (used with clang_getInclusions()). * * This visitor function will be invoked by clang_getInclusions() for each - * file included (either at the top-level or by #include directives) within + * file included (either at the top-level or by \#include directives) within * a translation unit. The first argument is the file being included, and * the second and third arguments provide the inclusion stack. The * array is sorted in order of immediate inclusion. For example, @@ -4246,19 +4900,19 @@ typedef struct { } CXIdxLoc; /** - * \brief Data for \see ppIncludedFile callback. + * \brief Data for ppIncludedFile callback. */ typedef struct { /** - * \brief Location of '#' in the #include/#import directive. + * \brief Location of '#' in the \#include/\#import directive. */ CXIdxLoc hashLoc; /** - * \brief Filename as written in the #include/#import directive. + * \brief Filename as written in the \#include/\#import directive. */ const char *filename; /** - * \brief The actual file that the #include/#import directive resolved to. + * \brief The actual file that the \#include/\#import directive resolved to. */ CXFile file; int isImport; @@ -4266,7 +4920,7 @@ typedef struct { } CXIdxIncludedFileInfo; /** - * \brief Data for \see importedASTFile callback. + * \brief Data for IndexerCallbacks#importedASTFile. */ typedef struct { CXFile file; @@ -4380,7 +5034,7 @@ typedef struct { CXIdxLoc loc; const CXIdxContainerInfo *semanticContainer; /** - * \brief Generally same as \see semanticContainer but can be different in + * \brief Generally same as #semanticContainer but can be different in * cases like out-of-line C++ member functions. */ const CXIdxContainerInfo *lexicalContainer; @@ -4452,7 +5106,7 @@ typedef struct { } CXIdxCXXClassDeclInfo; /** - * \brief Data for \see indexEntityReference callback. + * \brief Data for IndexerCallbacks#indexEntityReference. */ typedef enum { /** @@ -4467,7 +5121,7 @@ typedef enum { } CXIdxEntityRefKind; /** - * \brief Data for \see indexEntityReference callback. + * \brief Data for IndexerCallbacks#indexEntityReference. */ typedef struct { CXIdxEntityRefKind kind; @@ -4498,6 +5152,10 @@ typedef struct { const CXIdxContainerInfo *container; } CXIdxEntityRefInfo; +/** + * \brief A group of callbacks used by #clang_indexSourceFile and + * #clang_indexTranslationUnit. + */ typedef struct { /** * \brief Called periodically to check whether indexing should be aborted. @@ -4512,10 +5170,10 @@ typedef struct { CXDiagnosticSet, void *reserved); CXIdxClientFile (*enteredMainFile)(CXClientData client_data, - CXFile mainFile, void *reserved); + CXFile mainFile, void *reserved); /** - * \brief Called when a file gets #included/#imported. + * \brief Called when a file gets \#included/\#imported. */ CXIdxClientFile (*ppIncludedFile)(CXClientData client_data, const CXIdxIncludedFileInfo *); @@ -4628,9 +5286,9 @@ typedef enum { CXIndexOpt_None = 0x0, /** - * \brief Used to indicate that \see indexEntityReference should be invoked - * for only one reference of an entity per source file that does not also - * include a declaration/definition of the entity. + * \brief Used to indicate that IndexerCallbacks#indexEntityReference should + * be invoked for only one reference of an entity per source file that does + * not also include a declaration/definition of the entity. */ CXIndexOpt_SuppressRedundantRefs = 0x1, @@ -4654,7 +5312,7 @@ typedef enum { /** * \brief Index the given source file and the translation unit corresponding - * to that file via callbacks implemented through \see IndexerCallbacks. + * to that file via callbacks implemented through #IndexerCallbacks. * * \param client_data pointer data supplied by the client, which will * be passed to the invoked callbacks. @@ -4662,7 +5320,7 @@ typedef enum { * \param index_callbacks Pointer to indexing callbacks that the client * implements. * - * \param index_callbacks_size Size of \see IndexerCallbacks structure that gets + * \param index_callbacks_size Size of #IndexerCallbacks structure that gets * passed in index_callbacks. * * \param index_options A bitmask of options that affects how indexing is @@ -4674,7 +5332,7 @@ typedef enum { * \returns If there is a failure from which the there is no recovery, returns * non-zero, otherwise returns 0. * - * The rest of the parameters are the same as \see clang_parseTranslationUnit. + * The rest of the parameters are the same as #clang_parseTranslationUnit. */ CINDEX_LINKAGE int clang_indexSourceFile(CXIndexAction, CXClientData client_data, @@ -4691,7 +5349,7 @@ CINDEX_LINKAGE int clang_indexSourceFile(CXIndexAction, /** * \brief Index the given translation unit via callbacks implemented through - * \see IndexerCallbacks. + * #IndexerCallbacks. * * The order of callback invocations is not guaranteed to be the same as * when indexing a source file. The high level order will be: @@ -4700,7 +5358,7 @@ CINDEX_LINKAGE int clang_indexSourceFile(CXIndexAction, * -Declaration/reference callbacks invocations * -Diagnostic callback invocations * - * The parameters are the same as \see clang_indexSourceFile. + * The parameters are the same as #clang_indexSourceFile. * * \returns If there is a failure from which the there is no recovery, returns * non-zero, otherwise returns 0. diff --git a/include/clang-c/Platform.h b/include/clang-c/Platform.h new file mode 100644 index 000000000000..0f866c64563c --- /dev/null +++ b/include/clang-c/Platform.h @@ -0,0 +1,45 @@ +/*===-- clang-c/Platform.h - C Index platform decls -------------*- C -*-===*\ +|* *| +|* The LLVM Compiler Infrastructure *| +|* *| +|* This file is distributed under the University of Illinois Open Source *| +|* License. See LICENSE.TXT for details. *| +|* *| +|*===----------------------------------------------------------------------===*| +|* *| +|* This header provides platform specific macros (dllimport, deprecated, ...) *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#ifndef CLANG_C_PLATFORM_H +#define CLANG_C_PLATFORM_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* MSVC DLL import/export. */ +#ifdef _MSC_VER + #ifdef _CINDEX_LIB_ + #define CINDEX_LINKAGE __declspec(dllexport) + #else + #define CINDEX_LINKAGE __declspec(dllimport) + #endif +#else + #define CINDEX_LINKAGE +#endif + +#ifdef __GNUC__ + #define CINDEX_DEPRECATED __attribute__((deprecated)) +#else + #ifdef _MSC_VER + #define CINDEX_DEPRECATED __declspec(deprecated) + #else + #define CINDEX_DEPRECATED + #endif +#endif + +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/clang/AST/ASTContext.h b/include/clang/AST/ASTContext.h index 96e41c5d0357..8fd7d6ef4233 100644 --- a/include/clang/AST/ASTContext.h +++ b/include/clang/AST/ASTContext.h @@ -27,6 +27,7 @@ #include "clang/AST/TemplateName.h" #include "clang/AST/Type.h" #include "clang/AST/CanonicalType.h" +#include "clang/AST/RawCommentList.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" @@ -51,7 +52,6 @@ namespace clang { class ASTMutationListener; class IdentifierTable; class SelectorTable; - class SourceManager; class TargetInfo; class CXXABI; // Decls @@ -80,6 +80,10 @@ namespace clang { namespace Builtin { class Context; } + namespace comments { + class FullComment; + } + /// ASTContext - This class holds long-lived AST nodes (such as types and /// decls) that can be referred to throughout the semantic analysis of a file. class ASTContext : public RefCountedBase { @@ -198,10 +202,9 @@ class ASTContext : public RefCountedBase { /// \brief The typedef for the __uint128_t type. mutable TypedefDecl *UInt128Decl; - /// BuiltinVaListType - built-in va list type. - /// This is initially null and set by Sema::LazilyCreateBuiltin when - /// a builtin that takes a valist is encountered. - QualType BuiltinVaListType; + /// \brief The typedef for the target specific predefined + /// __builtin_va_list type. + mutable TypedefDecl *BuiltinVaListDecl; /// \brief The typedef for the predefined 'id' type. mutable TypedefDecl *ObjCIdDecl; @@ -392,6 +395,11 @@ public: SourceManager& getSourceManager() { return SourceMgr; } const SourceManager& getSourceManager() const { return SourceMgr; } + + llvm::BumpPtrAllocator &getAllocator() const { + return BumpAlloc; + } + void *Allocate(unsigned Size, unsigned Align = 8) const { return BumpAlloc.Allocate(Size, Align); } @@ -419,6 +427,85 @@ public: return FullSourceLoc(Loc,SourceMgr); } + /// \brief All comments in this translation unit. + RawCommentList Comments; + + /// \brief True if comments are already loaded from ExternalASTSource. + mutable bool CommentsLoaded; + + class RawCommentAndCacheFlags { + public: + enum Kind { + /// We searched for a comment attached to the particular declaration, but + /// didn't find any. + /// + /// getRaw() == 0. + NoCommentInDecl = 0, + + /// We have found a comment attached to this particular declaration. + /// + /// getRaw() != 0. + FromDecl, + + /// This declaration does not have an attached comment, and we have + /// searched the redeclaration chain. + /// + /// If getRaw() == 0, the whole redeclaration chain does not have any + /// comments. + /// + /// If getRaw() != 0, it is a comment propagated from other + /// redeclaration. + FromRedecl + }; + + Kind getKind() const LLVM_READONLY { + return Data.getInt(); + } + + void setKind(Kind K) { + Data.setInt(K); + } + + const RawComment *getRaw() const LLVM_READONLY { + return Data.getPointer(); + } + + void setRaw(const RawComment *RC) { + Data.setPointer(RC); + } + + private: + llvm::PointerIntPair Data; + }; + + /// \brief Mapping from declarations to comments attached to any + /// redeclaration. + /// + /// Raw comments are owned by Comments list. This mapping is populated + /// lazily. + mutable llvm::DenseMap RedeclComments; + + /// \brief Return the documentation comment attached to a given declaration, + /// without looking into cache. + RawComment *getRawCommentForDeclNoCache(const Decl *D) const; + +public: + RawCommentList &getRawCommentList() { + return Comments; + } + + void addComment(const RawComment &RC) { + Comments.addComment(RC, BumpAlloc); + } + + /// \brief Return the documentation comment attached to a given declaration. + /// Returns NULL if no comment is attached. + const RawComment *getRawCommentForAnyRedecl(const Decl *D) const; + + /// Return parsed documentation comment attached to a given declaration. + /// Returns NULL if no comment is attached. + comments::FullComment *getCommentForDecl(const Decl *D) const; + /// \brief Retrieve the attributes for the given declaration. AttrVec& getDeclAttrs(const Decl *D); @@ -557,6 +644,7 @@ public: CanQualType BoolTy; CanQualType CharTy; CanQualType WCharTy; // [C++ 3.9.1p5], integer type in C99. + CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions. CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99. CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99. CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty; @@ -575,6 +663,10 @@ public: mutable QualType AutoDeductTy; // Deduction against 'auto'. mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'. + // Type used to help define __builtin_va_list for some targets. + // The type is built when constructing 'BuiltinVaListDecl'. + mutable QualType VaListTagTy; + ASTContext(LangOptions& LOpts, SourceManager &SM, const TargetInfo *t, IdentifierTable &idents, SelectorTable &sels, Builtin::Context &builtins, @@ -929,6 +1021,10 @@ public: /// Used when in C++, as a GCC extension. QualType getUnsignedWCharType() const; + /// getWIntType - In C99, this returns a type compatible with the type + /// defined in as defined by the target. + QualType getWIntType() const { return WIntTy; } + /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) /// defined in . Pointer - pointer requires this (C99 6.5.6p9). QualType getPointerDiffType() const; @@ -1148,8 +1244,19 @@ public: return getObjCInterfaceType(getObjCProtocolDecl()); } - void setBuiltinVaListType(QualType T); - QualType getBuiltinVaListType() const { return BuiltinVaListType; } + /// \brief Retrieve the C type declaration corresponding to the predefined + /// __builtin_va_list type. + TypedefDecl *getBuiltinVaListDecl() const; + + /// \brief Retrieve the type of the __builtin_va_list type. + QualType getBuiltinVaListType() const { + return getTypeDeclType(getBuiltinVaListDecl()); + } + + /// \brief Retrieve the C type declaration corresponding to the predefined + /// __va_list_tag type used to help define the __builtin_va_list type for + /// some targets. + QualType getVaListTagType() const; /// getCVRQualifiedType - Returns a type with additional const, /// volatile, or restrict qualifiers. @@ -1210,10 +1317,10 @@ public: const TemplateArgument &ArgPack) const; enum GetBuiltinTypeError { - GE_None, //< No error - GE_Missing_stdio, //< Missing a type from - GE_Missing_setjmp, //< Missing a type from - GE_Missing_ucontext //< Missing a type from + GE_None, ///< No error + GE_Missing_stdio, ///< Missing a type from + GE_Missing_setjmp, ///< Missing a type from + GE_Missing_ucontext ///< Missing a type from }; /// GetBuiltinType - Return the type for the specified builtin. If @@ -1440,15 +1547,11 @@ public: /// \brief Retrieves the default calling convention to use for /// C++ instance methods. - CallingConv getDefaultMethodCallConv(); + CallingConv getDefaultCXXMethodCallConv(bool isVariadic); /// \brief Retrieves the canonical representation of the given /// calling convention. - CallingConv getCanonicalCallConv(CallingConv CC) const { - if (!LangOpts.MRTD && CC == CC_C) - return CC_Default; - return CC; - } + CallingConv getCanonicalCallConv(CallingConv CC) const; /// \brief Determines whether two calling conventions name the same /// calling convention. @@ -1463,7 +1566,7 @@ public: /// be used to refer to a given template. For most templates, this /// expression is just the template declaration itself. For example, /// the template std::vector can be referred to via a variety of - /// names---std::vector, ::std::vector, vector (if vector is in + /// names---std::vector, \::std::vector, vector (if vector is in /// scope), etc.---but all of these names map down to the same /// TemplateDecl, which is used to form the canonical template name. /// @@ -1523,12 +1626,12 @@ public: /// This routine adjusts the given parameter type @p T to the actual /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8], /// C++ [dcl.fct]p3). The adjusted parameter type is returned. - QualType getAdjustedParameterType(QualType T); + QualType getAdjustedParameterType(QualType T) const; /// \brief Retrieve the parameter type as adjusted for use in the signature /// of a function, decaying array and function types and removing top-level /// cv-qualifiers. - QualType getSignatureParameterType(QualType T); + QualType getSignatureParameterType(QualType T) const; /// getArrayDecayedType - Return the properly qualified result of decaying the /// specified array type to a pointer. This operation is non-trivial when @@ -1700,7 +1803,7 @@ public: /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists. ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D); - /// \brief returns true if there is at lease one @implementation in TU. + /// \brief returns true if there is at least one \@implementation in TU. bool AnyObjCImplementation() { return !ObjCImpls.empty(); } @@ -1716,15 +1819,12 @@ public: /// interface, or null if non exists. const ObjCMethodDecl *getObjCMethodRedeclaration( const ObjCMethodDecl *MD) const { - llvm::DenseMap::const_iterator - I = ObjCMethodRedecls.find(MD); - if (I == ObjCMethodRedecls.end()) - return 0; - return I->second; + return ObjCMethodRedecls.lookup(MD); } void setObjCMethodRedeclaration(const ObjCMethodDecl *MD, const ObjCMethodDecl *Redecl) { + assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration"); ObjCMethodRedecls[MD] = Redecl; } diff --git a/include/clang/AST/ASTImporter.h b/include/clang/AST/ASTImporter.h index 7157efe5b3f2..46a9881039c7 100644 --- a/include/clang/AST/ASTImporter.h +++ b/include/clang/AST/ASTImporter.h @@ -271,7 +271,8 @@ namespace clang { /// \brief Determine whether the given types are structurally /// equivalent. - bool IsStructurallyEquivalent(QualType From, QualType To); + bool IsStructurallyEquivalent(QualType From, QualType To, + bool Complain = true); }; } diff --git a/include/clang/AST/ASTVector.h b/include/clang/AST/ASTVector.h index 217dfade525f..4ff5ea37b882 100644 --- a/include/clang/AST/ASTVector.h +++ b/include/clang/AST/ASTVector.h @@ -374,7 +374,7 @@ void ASTVector::grow(ASTContext &C, size_t MinSize) { NewCapacity = MinSize; // Allocate the memory from the ASTContext. - T *NewElts = new (C) T[NewCapacity]; + T *NewElts = new (C, llvm::alignOf()) T[NewCapacity]; // Copy the elements over. if (llvm::is_class::value) { @@ -387,7 +387,7 @@ void ASTVector::grow(ASTContext &C, size_t MinSize) { memcpy(NewElts, Begin, CurSize * sizeof(T)); } - C.Deallocate(Begin); + // ASTContext never frees any memory. Begin = NewElts; End = NewElts+CurSize; Capacity = Begin+NewCapacity; diff --git a/include/clang/AST/Attr.h b/include/clang/AST/Attr.h index ef1aa256626c..27b44d4bd97b 100644 --- a/include/clang/AST/Attr.h +++ b/include/clang/AST/Attr.h @@ -1,4 +1,4 @@ -//===--- Attr.h - Classes for representing expressions ----------*- C++ -*-===// +//===--- Attr.h - Classes for representing attributes ----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // @@ -147,14 +147,12 @@ public: typedef SmallVector AttrVec; typedef SmallVector ConstAttrVec; -/// DestroyAttrs - Destroy the contents of an AttrVec. -inline void DestroyAttrs (AttrVec& V, ASTContext &C) { -} - /// specific_attr_iterator - Iterates over a subrange of an AttrVec, only /// providing attributes that are of a specifc type. -template +template class specific_attr_iterator { + typedef typename Container::const_iterator Iterator; + /// Current - The current, underlying iterator. /// In order to ensure we don't dereference an invalid iterator unless /// specifically requested, we don't necessarily advance this all the @@ -162,14 +160,14 @@ class specific_attr_iterator { /// operation is acting on what should be a past-the-end iterator, /// then we offer no guarantees, but this way we do not dererence a /// past-the-end iterator when we move to a past-the-end position. - mutable AttrVec::const_iterator Current; + mutable Iterator Current; void AdvanceToNext() const { while (!isa(*Current)) ++Current; } - void AdvanceToNext(AttrVec::const_iterator I) const { + void AdvanceToNext(Iterator I) const { while (Current != I && !isa(*Current)) ++Current; } @@ -182,7 +180,7 @@ public: typedef std::ptrdiff_t difference_type; specific_attr_iterator() : Current() { } - explicit specific_attr_iterator(AttrVec::const_iterator i) : Current(i) { } + explicit specific_attr_iterator(Iterator i) : Current(i) { } reference operator*() const { AdvanceToNext(); @@ -217,23 +215,27 @@ public: } }; -template -inline specific_attr_iterator specific_attr_begin(const AttrVec& vec) { - return specific_attr_iterator(vec.begin()); +template +inline specific_attr_iterator + specific_attr_begin(const Container& container) { + return specific_attr_iterator(container.begin()); } -template -inline specific_attr_iterator specific_attr_end(const AttrVec& vec) { - return specific_attr_iterator(vec.end()); +template +inline specific_attr_iterator + specific_attr_end(const Container& container) { + return specific_attr_iterator(container.end()); } -template -inline bool hasSpecificAttr(const AttrVec& vec) { - return specific_attr_begin(vec) != specific_attr_end(vec); +template +inline bool hasSpecificAttr(const Container& container) { + return specific_attr_begin(container) != + specific_attr_end(container); } -template -inline T *getSpecificAttr(const AttrVec& vec) { - specific_attr_iterator i = specific_attr_begin(vec); - if (i != specific_attr_end(vec)) +template +inline SpecificAttr *getSpecificAttr(const Container& container) { + specific_attr_iterator i = + specific_attr_begin(container); + if (i != specific_attr_end(container)) return *i; else return 0; diff --git a/include/clang/AST/BaseSubobject.h b/include/clang/AST/BaseSubobject.h index 6a036bb62cf4..da538e3566a7 100644 --- a/include/clang/AST/BaseSubobject.h +++ b/include/clang/AST/BaseSubobject.h @@ -66,9 +66,9 @@ template<> struct DenseMapInfo { } static unsigned getHashValue(const clang::BaseSubobject &Base) { - return - DenseMapInfo::getHashValue(Base.getBase()) ^ - DenseMapInfo::getHashValue(Base.getBaseOffset().getQuantity()); + typedef std::pair PairTy; + return DenseMapInfo::getHashValue(PairTy(Base.getBase(), + Base.getBaseOffset())); } static bool isEqual(const clang::BaseSubobject &LHS, diff --git a/include/clang/AST/CMakeLists.txt b/include/clang/AST/CMakeLists.txt index c10cda84fb83..d7458aa7900e 100644 --- a/include/clang/AST/CMakeLists.txt +++ b/include/clang/AST/CMakeLists.txt @@ -15,3 +15,8 @@ clang_tablegen(StmtNodes.inc -gen-clang-stmt-nodes clang_tablegen(DeclNodes.inc -gen-clang-decl-nodes SOURCE ../Basic/DeclNodes.td TARGET ClangDeclNodes) + +clang_tablegen(CommentNodes.inc -gen-clang-comment-nodes + SOURCE ../Basic/CommentNodes.td + TARGET ClangCommentNodes) + diff --git a/include/clang/AST/CXXInheritance.h b/include/clang/AST/CXXInheritance.h index 44c554b606c4..ee6eba78e415 100644 --- a/include/clang/AST/CXXInheritance.h +++ b/include/clang/AST/CXXInheritance.h @@ -128,8 +128,7 @@ class CXXBasePaths { /// while the element contains the number of non-virtual base /// class subobjects for that class type. The key of the map is /// the cv-unqualified canonical type of the base class subobject. - std::map, QualTypeOrdering> - ClassSubobjects; + llvm::SmallDenseMap, 8> ClassSubobjects; /// FindAmbiguities - Whether Sema::IsDerivedFrom should try find /// ambiguous paths while it is looking for a path from a derived diff --git a/include/clang/AST/Comment.h b/include/clang/AST/Comment.h new file mode 100644 index 000000000000..01aaac3f77ad --- /dev/null +++ b/include/clang/AST/Comment.h @@ -0,0 +1,1059 @@ +//===--- Comment.h - Comment AST nodes --------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines comment AST nodes. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_AST_COMMENT_H +#define LLVM_CLANG_AST_COMMENT_H + +#include "clang/Basic/SourceLocation.h" +#include "clang/AST/Type.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/StringRef.h" + +namespace clang { +class Decl; +class ParmVarDecl; +class TemplateParameterList; + +namespace comments { + +/// Any part of the comment. +/// Abstract class. +class Comment { +protected: + /// Preferred location to show caret. + SourceLocation Loc; + + /// Source range of this AST node. + SourceRange Range; + + class CommentBitfields { + friend class Comment; + + /// Type of this AST node. + unsigned Kind : 8; + }; + enum { NumCommentBits = 8 }; + + class InlineContentCommentBitfields { + friend class InlineContentComment; + + unsigned : NumCommentBits; + + /// True if there is a newline after this inline content node. + /// (There is no separate AST node for a newline.) + unsigned HasTrailingNewline : 1; + }; + enum { NumInlineContentCommentBits = NumCommentBits + 1 }; + + class TextCommentBitfields { + friend class TextComment; + + unsigned : NumInlineContentCommentBits; + + /// True if \c IsWhitespace field contains a valid value. + mutable unsigned IsWhitespaceValid : 1; + + /// True if this comment AST node contains only whitespace. + mutable unsigned IsWhitespace : 1; + }; + enum { NumTextCommentBits = NumInlineContentCommentBits + 2 }; + + class InlineCommandCommentBitfields { + friend class InlineCommandComment; + + unsigned : NumInlineContentCommentBits; + + unsigned RenderKind : 2; + }; + enum { NumInlineCommandCommentBits = NumInlineContentCommentBits + 1 }; + + class HTMLStartTagCommentBitfields { + friend class HTMLStartTagComment; + + unsigned : NumInlineContentCommentBits; + + /// True if this tag is self-closing (e. g.,
    ). This is based on tag + /// spelling in comment (plain
    would not set this flag). + unsigned IsSelfClosing : 1; + }; + enum { NumHTMLStartTagCommentBits = NumInlineContentCommentBits + 1 }; + + class ParagraphCommentBitfields { + friend class ParagraphComment; + + unsigned : NumCommentBits; + + /// True if \c IsWhitespace field contains a valid value. + mutable unsigned IsWhitespaceValid : 1; + + /// True if this comment AST node contains only whitespace. + mutable unsigned IsWhitespace : 1; + }; + enum { NumParagraphCommentBits = NumCommentBits + 2 }; + + class ParamCommandCommentBitfields { + friend class ParamCommandComment; + + unsigned : NumCommentBits; + + /// Parameter passing direction, see ParamCommandComment::PassDirection. + unsigned Direction : 2; + + /// True if direction was specified explicitly in the comment. + unsigned IsDirectionExplicit : 1; + }; + enum { NumParamCommandCommentBits = 11 }; + + union { + CommentBitfields CommentBits; + InlineContentCommentBitfields InlineContentCommentBits; + TextCommentBitfields TextCommentBits; + InlineCommandCommentBitfields InlineCommandCommentBits; + HTMLStartTagCommentBitfields HTMLStartTagCommentBits; + ParagraphCommentBitfields ParagraphCommentBits; + ParamCommandCommentBitfields ParamCommandCommentBits; + }; + + void setSourceRange(SourceRange SR) { + Range = SR; + } + + void setLocation(SourceLocation L) { + Loc = L; + } + +public: + enum CommentKind { + NoCommentKind = 0, +#define COMMENT(CLASS, PARENT) CLASS##Kind, +#define COMMENT_RANGE(BASE, FIRST, LAST) \ + First##BASE##Constant=FIRST##Kind, Last##BASE##Constant=LAST##Kind, +#define LAST_COMMENT_RANGE(BASE, FIRST, LAST) \ + First##BASE##Constant=FIRST##Kind, Last##BASE##Constant=LAST##Kind +#define ABSTRACT_COMMENT(COMMENT) +#include "clang/AST/CommentNodes.inc" + }; + + Comment(CommentKind K, + SourceLocation LocBegin, + SourceLocation LocEnd) : + Loc(LocBegin), Range(SourceRange(LocBegin, LocEnd)) { + CommentBits.Kind = K; + } + + CommentKind getCommentKind() const { + return static_cast(CommentBits.Kind); + } + + const char *getCommentKindName() const; + + LLVM_ATTRIBUTE_USED void dump() const; + LLVM_ATTRIBUTE_USED void dump(SourceManager &SM) const; + void dump(llvm::raw_ostream &OS, SourceManager *SM) const; + + static bool classof(const Comment *) { return true; } + + SourceRange getSourceRange() const LLVM_READONLY { return Range; } + + SourceLocation getLocStart() const LLVM_READONLY { + return Range.getBegin(); + } + + SourceLocation getLocEnd() const LLVM_READONLY { + return Range.getEnd(); + } + + SourceLocation getLocation() const LLVM_READONLY { return Loc; } + + typedef Comment * const *child_iterator; + + child_iterator child_begin() const; + child_iterator child_end() const; + + // TODO: const child iterator + + unsigned child_count() const { + return child_end() - child_begin(); + } +}; + +/// Inline content (contained within a block). +/// Abstract class. +class InlineContentComment : public Comment { +protected: + InlineContentComment(CommentKind K, + SourceLocation LocBegin, + SourceLocation LocEnd) : + Comment(K, LocBegin, LocEnd) { + InlineContentCommentBits.HasTrailingNewline = 0; + } + +public: + static bool classof(const Comment *C) { + return C->getCommentKind() >= FirstInlineContentCommentConstant && + C->getCommentKind() <= LastInlineContentCommentConstant; + } + + static bool classof(const InlineContentComment *) { return true; } + + void addTrailingNewline() { + InlineContentCommentBits.HasTrailingNewline = 1; + } + + bool hasTrailingNewline() const { + return InlineContentCommentBits.HasTrailingNewline; + } +}; + +/// Plain text. +class TextComment : public InlineContentComment { + StringRef Text; + +public: + TextComment(SourceLocation LocBegin, + SourceLocation LocEnd, + StringRef Text) : + InlineContentComment(TextCommentKind, LocBegin, LocEnd), + Text(Text) { + TextCommentBits.IsWhitespaceValid = false; + } + + static bool classof(const Comment *C) { + return C->getCommentKind() == TextCommentKind; + } + + static bool classof(const TextComment *) { return true; } + + child_iterator child_begin() const { return NULL; } + + child_iterator child_end() const { return NULL; } + + StringRef getText() const LLVM_READONLY { return Text; } + + bool isWhitespace() const { + if (TextCommentBits.IsWhitespaceValid) + return TextCommentBits.IsWhitespace; + + TextCommentBits.IsWhitespace = isWhitespaceNoCache(); + TextCommentBits.IsWhitespaceValid = true; + return TextCommentBits.IsWhitespace; + } + +private: + bool isWhitespaceNoCache() const; +}; + +/// A command with word-like arguments that is considered inline content. +class InlineCommandComment : public InlineContentComment { +public: + struct Argument { + SourceRange Range; + StringRef Text; + + Argument(SourceRange Range, StringRef Text) : Range(Range), Text(Text) { } + }; + + /// The most appropriate rendering mode for this command, chosen on command + /// semantics in Doxygen. + enum RenderKind { + RenderNormal, + RenderBold, + RenderMonospaced, + RenderEmphasized + }; + +protected: + /// Command name. + StringRef Name; + + /// Command arguments. + llvm::ArrayRef Args; + +public: + InlineCommandComment(SourceLocation LocBegin, + SourceLocation LocEnd, + StringRef Name, + RenderKind RK, + llvm::ArrayRef Args) : + InlineContentComment(InlineCommandCommentKind, LocBegin, LocEnd), + Name(Name), Args(Args) { + InlineCommandCommentBits.RenderKind = RK; + } + + static bool classof(const Comment *C) { + return C->getCommentKind() == InlineCommandCommentKind; + } + + static bool classof(const InlineCommandComment *) { return true; } + + child_iterator child_begin() const { return NULL; } + + child_iterator child_end() const { return NULL; } + + StringRef getCommandName() const { + return Name; + } + + SourceRange getCommandNameRange() const { + return SourceRange(getLocStart().getLocWithOffset(-1), + getLocEnd()); + } + + RenderKind getRenderKind() const { + return static_cast(InlineCommandCommentBits.RenderKind); + } + + unsigned getNumArgs() const { + return Args.size(); + } + + StringRef getArgText(unsigned Idx) const { + return Args[Idx].Text; + } + + SourceRange getArgRange(unsigned Idx) const { + return Args[Idx].Range; + } +}; + +/// Abstract class for opening and closing HTML tags. HTML tags are always +/// treated as inline content (regardless HTML semantics); opening and closing +/// tags are not matched. +class HTMLTagComment : public InlineContentComment { +protected: + StringRef TagName; + SourceRange TagNameRange; + + HTMLTagComment(CommentKind K, + SourceLocation LocBegin, + SourceLocation LocEnd, + StringRef TagName, + SourceLocation TagNameBegin, + SourceLocation TagNameEnd) : + InlineContentComment(K, LocBegin, LocEnd), + TagName(TagName), + TagNameRange(TagNameBegin, TagNameEnd) { + setLocation(TagNameBegin); + } + +public: + static bool classof(const Comment *C) { + return C->getCommentKind() >= FirstHTMLTagCommentConstant && + C->getCommentKind() <= LastHTMLTagCommentConstant; + } + + static bool classof(const HTMLTagComment *) { return true; } + + StringRef getTagName() const LLVM_READONLY { return TagName; } + + SourceRange getTagNameSourceRange() const LLVM_READONLY { + SourceLocation L = getLocation(); + return SourceRange(L.getLocWithOffset(1), + L.getLocWithOffset(1 + TagName.size())); + } +}; + +/// An opening HTML tag with attributes. +class HTMLStartTagComment : public HTMLTagComment { +public: + class Attribute { + public: + SourceLocation NameLocBegin; + StringRef Name; + + SourceLocation EqualsLoc; + + SourceRange ValueRange; + StringRef Value; + + Attribute() { } + + Attribute(SourceLocation NameLocBegin, StringRef Name) : + NameLocBegin(NameLocBegin), Name(Name), + EqualsLoc(SourceLocation()), + ValueRange(SourceRange()), Value(StringRef()) + { } + + Attribute(SourceLocation NameLocBegin, StringRef Name, + SourceLocation EqualsLoc, + SourceRange ValueRange, StringRef Value) : + NameLocBegin(NameLocBegin), Name(Name), + EqualsLoc(EqualsLoc), + ValueRange(ValueRange), Value(Value) + { } + + SourceLocation getNameLocEnd() const { + return NameLocBegin.getLocWithOffset(Name.size()); + } + + SourceRange getNameRange() const { + return SourceRange(NameLocBegin, getNameLocEnd()); + } + }; + +private: + ArrayRef Attributes; + +public: + HTMLStartTagComment(SourceLocation LocBegin, + StringRef TagName) : + HTMLTagComment(HTMLStartTagCommentKind, + LocBegin, LocBegin.getLocWithOffset(1 + TagName.size()), + TagName, + LocBegin.getLocWithOffset(1), + LocBegin.getLocWithOffset(1 + TagName.size())) { + HTMLStartTagCommentBits.IsSelfClosing = false; + } + + static bool classof(const Comment *C) { + return C->getCommentKind() == HTMLStartTagCommentKind; + } + + static bool classof(const HTMLStartTagComment *) { return true; } + + child_iterator child_begin() const { return NULL; } + + child_iterator child_end() const { return NULL; } + + unsigned getNumAttrs() const { + return Attributes.size(); + } + + const Attribute &getAttr(unsigned Idx) const { + return Attributes[Idx]; + } + + void setAttrs(ArrayRef Attrs) { + Attributes = Attrs; + if (!Attrs.empty()) { + const Attribute &Attr = Attrs.back(); + SourceLocation L = Attr.ValueRange.getEnd(); + if (L.isValid()) + Range.setEnd(L); + else { + Range.setEnd(Attr.getNameLocEnd()); + } + } + } + + void setGreaterLoc(SourceLocation GreaterLoc) { + Range.setEnd(GreaterLoc); + } + + bool isSelfClosing() const { + return HTMLStartTagCommentBits.IsSelfClosing; + } + + void setSelfClosing() { + HTMLStartTagCommentBits.IsSelfClosing = true; + } +}; + +/// A closing HTML tag. +class HTMLEndTagComment : public HTMLTagComment { +public: + HTMLEndTagComment(SourceLocation LocBegin, + SourceLocation LocEnd, + StringRef TagName) : + HTMLTagComment(HTMLEndTagCommentKind, + LocBegin, LocEnd, + TagName, + LocBegin.getLocWithOffset(2), + LocBegin.getLocWithOffset(2 + TagName.size())) + { } + + static bool classof(const Comment *C) { + return C->getCommentKind() == HTMLEndTagCommentKind; + } + + static bool classof(const HTMLEndTagComment *) { return true; } + + child_iterator child_begin() const { return NULL; } + + child_iterator child_end() const { return NULL; } +}; + +/// Block content (contains inline content). +/// Abstract class. +class BlockContentComment : public Comment { +protected: + BlockContentComment(CommentKind K, + SourceLocation LocBegin, + SourceLocation LocEnd) : + Comment(K, LocBegin, LocEnd) + { } + +public: + static bool classof(const Comment *C) { + return C->getCommentKind() >= FirstBlockContentCommentConstant && + C->getCommentKind() <= LastBlockContentCommentConstant; + } + + static bool classof(const BlockContentComment *) { return true; } +}; + +/// A single paragraph that contains inline content. +class ParagraphComment : public BlockContentComment { + llvm::ArrayRef Content; + +public: + ParagraphComment(llvm::ArrayRef Content) : + BlockContentComment(ParagraphCommentKind, + SourceLocation(), + SourceLocation()), + Content(Content) { + if (Content.empty()) { + ParagraphCommentBits.IsWhitespace = true; + ParagraphCommentBits.IsWhitespaceValid = true; + return; + } + + ParagraphCommentBits.IsWhitespaceValid = false; + + setSourceRange(SourceRange(Content.front()->getLocStart(), + Content.back()->getLocEnd())); + setLocation(Content.front()->getLocStart()); + } + + static bool classof(const Comment *C) { + return C->getCommentKind() == ParagraphCommentKind; + } + + static bool classof(const ParagraphComment *) { return true; } + + child_iterator child_begin() const { + return reinterpret_cast(Content.begin()); + } + + child_iterator child_end() const { + return reinterpret_cast(Content.end()); + } + + bool isWhitespace() const { + if (ParagraphCommentBits.IsWhitespaceValid) + return ParagraphCommentBits.IsWhitespace; + + ParagraphCommentBits.IsWhitespace = isWhitespaceNoCache(); + ParagraphCommentBits.IsWhitespaceValid = true; + return ParagraphCommentBits.IsWhitespace; + } + +private: + bool isWhitespaceNoCache() const; +}; + +/// A command that has zero or more word-like arguments (number of word-like +/// arguments depends on command name) and a paragraph as an argument +/// (e. g., \\brief). +class BlockCommandComment : public BlockContentComment { +public: + struct Argument { + SourceRange Range; + StringRef Text; + + Argument() { } + Argument(SourceRange Range, StringRef Text) : Range(Range), Text(Text) { } + }; + +protected: + /// Command name. + StringRef Name; + + /// Word-like arguments. + llvm::ArrayRef Args; + + /// Paragraph argument. + ParagraphComment *Paragraph; + + BlockCommandComment(CommentKind K, + SourceLocation LocBegin, + SourceLocation LocEnd, + StringRef Name) : + BlockContentComment(K, LocBegin, LocEnd), + Name(Name), + Paragraph(NULL) { + setLocation(getCommandNameRange().getBegin()); + } + +public: + BlockCommandComment(SourceLocation LocBegin, + SourceLocation LocEnd, + StringRef Name) : + BlockContentComment(BlockCommandCommentKind, LocBegin, LocEnd), + Name(Name), + Paragraph(NULL) { + setLocation(getCommandNameRange().getBegin()); + } + + static bool classof(const Comment *C) { + return C->getCommentKind() >= FirstBlockCommandCommentConstant && + C->getCommentKind() <= LastBlockCommandCommentConstant; + } + + static bool classof(const BlockCommandComment *) { return true; } + + child_iterator child_begin() const { + return reinterpret_cast(&Paragraph); + } + + child_iterator child_end() const { + return reinterpret_cast(&Paragraph + 1); + } + + StringRef getCommandName() const { + return Name; + } + + SourceRange getCommandNameRange() const { + return SourceRange(getLocStart().getLocWithOffset(1), + getLocStart().getLocWithOffset(1 + Name.size())); + } + + unsigned getNumArgs() const { + return Args.size(); + } + + StringRef getArgText(unsigned Idx) const { + return Args[Idx].Text; + } + + SourceRange getArgRange(unsigned Idx) const { + return Args[Idx].Range; + } + + void setArgs(llvm::ArrayRef A) { + Args = A; + if (Args.size() > 0) { + SourceLocation NewLocEnd = Args.back().Range.getEnd(); + if (NewLocEnd.isValid()) + setSourceRange(SourceRange(getLocStart(), NewLocEnd)); + } + } + + ParagraphComment *getParagraph() const LLVM_READONLY { + return Paragraph; + } + + bool hasNonWhitespaceParagraph() const { + return Paragraph && !Paragraph->isWhitespace(); + } + + void setParagraph(ParagraphComment *PC) { + Paragraph = PC; + SourceLocation NewLocEnd = PC->getLocEnd(); + if (NewLocEnd.isValid()) + setSourceRange(SourceRange(getLocStart(), NewLocEnd)); + } +}; + +/// Doxygen \\param command. +class ParamCommandComment : public BlockCommandComment { +private: + /// Parameter index in the function declaration. + unsigned ParamIndex; + +public: + enum { InvalidParamIndex = ~0U }; + + ParamCommandComment(SourceLocation LocBegin, + SourceLocation LocEnd, + StringRef Name) : + BlockCommandComment(ParamCommandCommentKind, LocBegin, LocEnd, Name), + ParamIndex(InvalidParamIndex) { + ParamCommandCommentBits.Direction = In; + ParamCommandCommentBits.IsDirectionExplicit = false; + } + + static bool classof(const Comment *C) { + return C->getCommentKind() == ParamCommandCommentKind; + } + + static bool classof(const ParamCommandComment *) { return true; } + + enum PassDirection { + In, + Out, + InOut + }; + + static const char *getDirectionAsString(PassDirection D); + + PassDirection getDirection() const LLVM_READONLY { + return static_cast(ParamCommandCommentBits.Direction); + } + + bool isDirectionExplicit() const LLVM_READONLY { + return ParamCommandCommentBits.IsDirectionExplicit; + } + + void setDirection(PassDirection Direction, bool Explicit) { + ParamCommandCommentBits.Direction = Direction; + ParamCommandCommentBits.IsDirectionExplicit = Explicit; + } + + bool hasParamName() const { + return getNumArgs() > 0; + } + + StringRef getParamName() const { + return Args[0].Text; + } + + SourceRange getParamNameRange() const { + return Args[0].Range; + } + + bool isParamIndexValid() const LLVM_READONLY { + return ParamIndex != InvalidParamIndex; + } + + unsigned getParamIndex() const LLVM_READONLY { + assert(isParamIndexValid()); + return ParamIndex; + } + + void setParamIndex(unsigned Index) { + ParamIndex = Index; + assert(isParamIndexValid()); + } +}; + +/// Doxygen \\tparam command, describes a template parameter. +class TParamCommandComment : public BlockCommandComment { +private: + /// If this template parameter name was resolved (found in template parameter + /// list), then this stores a list of position indexes in all template + /// parameter lists. + /// + /// For example: + /// \verbatim + /// template class TT> + /// void test(TT aaa); + /// \endverbatim + /// For C: Position = { 0 } + /// For TT: Position = { 1 } + /// For T: Position = { 1, 0 } + llvm::ArrayRef Position; + +public: + TParamCommandComment(SourceLocation LocBegin, + SourceLocation LocEnd, + StringRef Name) : + BlockCommandComment(TParamCommandCommentKind, LocBegin, LocEnd, Name) + { } + + static bool classof(const Comment *C) { + return C->getCommentKind() == TParamCommandCommentKind; + } + + static bool classof(const TParamCommandComment *) { return true; } + + bool hasParamName() const { + return getNumArgs() > 0; + } + + StringRef getParamName() const { + return Args[0].Text; + } + + SourceRange getParamNameRange() const { + return Args[0].Range; + } + + bool isPositionValid() const LLVM_READONLY { + return !Position.empty(); + } + + unsigned getDepth() const { + assert(isPositionValid()); + return Position.size(); + } + + unsigned getIndex(unsigned Depth) const { + assert(isPositionValid()); + return Position[Depth]; + } + + void setPosition(ArrayRef NewPosition) { + Position = NewPosition; + assert(isPositionValid()); + } +}; + +/// A line of text contained in a verbatim block. +class VerbatimBlockLineComment : public Comment { + StringRef Text; + +public: + VerbatimBlockLineComment(SourceLocation LocBegin, + StringRef Text) : + Comment(VerbatimBlockLineCommentKind, + LocBegin, + LocBegin.getLocWithOffset(Text.size())), + Text(Text) + { } + + static bool classof(const Comment *C) { + return C->getCommentKind() == VerbatimBlockLineCommentKind; + } + + static bool classof(const VerbatimBlockLineComment *) { return true; } + + child_iterator child_begin() const { return NULL; } + + child_iterator child_end() const { return NULL; } + + StringRef getText() const LLVM_READONLY { + return Text; + } +}; + +/// A verbatim block command (e. g., preformatted code). Verbatim block has an +/// opening and a closing command and contains multiple lines of text +/// (VerbatimBlockLineComment nodes). +class VerbatimBlockComment : public BlockCommandComment { +protected: + StringRef CloseName; + SourceLocation CloseNameLocBegin; + llvm::ArrayRef Lines; + +public: + VerbatimBlockComment(SourceLocation LocBegin, + SourceLocation LocEnd, + StringRef Name) : + BlockCommandComment(VerbatimBlockCommentKind, + LocBegin, LocEnd, Name) + { } + + static bool classof(const Comment *C) { + return C->getCommentKind() == VerbatimBlockCommentKind; + } + + static bool classof(const VerbatimBlockComment *) { return true; } + + child_iterator child_begin() const { + return reinterpret_cast(Lines.begin()); + } + + child_iterator child_end() const { + return reinterpret_cast(Lines.end()); + } + + void setCloseName(StringRef Name, SourceLocation LocBegin) { + CloseName = Name; + CloseNameLocBegin = LocBegin; + } + + void setLines(llvm::ArrayRef L) { + Lines = L; + } + + StringRef getCloseName() const { + return CloseName; + } + + unsigned getNumLines() const { + return Lines.size(); + } + + StringRef getText(unsigned LineIdx) const { + return Lines[LineIdx]->getText(); + } +}; + +/// A verbatim line command. Verbatim line has an opening command, a single +/// line of text (up to the newline after the opening command) and has no +/// closing command. +class VerbatimLineComment : public BlockCommandComment { +protected: + StringRef Text; + SourceLocation TextBegin; + +public: + VerbatimLineComment(SourceLocation LocBegin, + SourceLocation LocEnd, + StringRef Name, + SourceLocation TextBegin, + StringRef Text) : + BlockCommandComment(VerbatimLineCommentKind, + LocBegin, LocEnd, + Name), + Text(Text), + TextBegin(TextBegin) + { } + + static bool classof(const Comment *C) { + return C->getCommentKind() == VerbatimLineCommentKind; + } + + static bool classof(const VerbatimLineComment *) { return true; } + + child_iterator child_begin() const { return NULL; } + + child_iterator child_end() const { return NULL; } + + StringRef getText() const { + return Text; + } + + SourceRange getTextRange() const { + return SourceRange(TextBegin, getLocEnd()); + } +}; + +/// Information about the declaration, useful to clients of FullComment. +struct DeclInfo { + /// Declaration the comment is attached to. Should not be NULL. + const Decl *ThisDecl; + + /// Parameters that can be referenced by \\param if \c ThisDecl is something + /// that we consider a "function". + ArrayRef ParamVars; + + /// Function result type if \c ThisDecl is something that we consider + /// a "function". + QualType ResultType; + + /// Template parameters that can be referenced by \\tparam if \c ThisDecl is + /// a template (\c IsTemplateDecl or \c IsTemplatePartialSpecialization is + /// true). + const TemplateParameterList *TemplateParameters; + + /// A simplified description of \c ThisDecl kind that should be good enough + /// for documentation rendering purposes. + enum DeclKind { + /// Everything else not explicitly mentioned below. + OtherKind, + + /// Something that we consider a "function": + /// \li function, + /// \li function template, + /// \li function template specialization, + /// \li member function, + /// \li member function template, + /// \li member function template specialization, + /// \li ObjC method. + FunctionKind, + + /// Something that we consider a "class": + /// \li class/struct, + /// \li class template, + /// \li class template (partial) specialization. + ClassKind, + + /// Something that we consider a "variable": + /// \li namespace scope variables; + /// \li static and non-static class data members; + /// \li enumerators. + VariableKind, + + /// A C++ namespace. + NamespaceKind, + + /// A C++ typedef-name (a 'typedef' decl specifier or alias-declaration), + /// see \c TypedefNameDecl. + TypedefKind, + + /// An enumeration or scoped enumeration. + EnumKind + }; + + /// What kind of template specialization \c ThisDecl is. + enum TemplateDeclKind { + NotTemplate, + Template, + TemplateSpecialization, + TemplatePartialSpecialization + }; + + /// If false, only \c ThisDecl is valid. + unsigned IsFilled : 1; + + /// Simplified kind of \c ThisDecl, see\c DeclKind enum. + unsigned Kind : 3; + + /// Is \c ThisDecl a template declaration. + unsigned TemplateKind : 2; + + /// Is \c ThisDecl an ObjCMethodDecl. + unsigned IsObjCMethod : 1; + + /// Is \c ThisDecl a non-static member function of C++ class or + /// instance method of ObjC class. + /// Can be true only if \c IsFunctionDecl is true. + unsigned IsInstanceMethod : 1; + + /// Is \c ThisDecl a static member function of C++ class or + /// class method of ObjC class. + /// Can be true only if \c IsFunctionDecl is true. + unsigned IsClassMethod : 1; + + void fill(); + + DeclKind getKind() const LLVM_READONLY { + return static_cast(Kind); + } + + TemplateDeclKind getTemplateKind() const LLVM_READONLY { + return static_cast(TemplateKind); + } +}; + +/// A full comment attached to a declaration, contains block content. +class FullComment : public Comment { + llvm::ArrayRef Blocks; + + DeclInfo *ThisDeclInfo; + +public: + FullComment(llvm::ArrayRef Blocks, DeclInfo *D) : + Comment(FullCommentKind, SourceLocation(), SourceLocation()), + Blocks(Blocks), ThisDeclInfo(D) { + if (Blocks.empty()) + return; + + setSourceRange(SourceRange(Blocks.front()->getLocStart(), + Blocks.back()->getLocEnd())); + setLocation(Blocks.front()->getLocStart()); + } + + static bool classof(const Comment *C) { + return C->getCommentKind() == FullCommentKind; + } + + static bool classof(const FullComment *) { return true; } + + child_iterator child_begin() const { + return reinterpret_cast(Blocks.begin()); + } + + child_iterator child_end() const { + return reinterpret_cast(Blocks.end()); + } + + const Decl *getDecl() const LLVM_READONLY { + return ThisDeclInfo->ThisDecl; + } + + const DeclInfo *getDeclInfo() const LLVM_READONLY { + if (!ThisDeclInfo->IsFilled) + ThisDeclInfo->fill(); + return ThisDeclInfo; + } +}; + +} // end namespace comments +} // end namespace clang + +#endif + diff --git a/include/clang/AST/CommentBriefParser.h b/include/clang/AST/CommentBriefParser.h new file mode 100644 index 000000000000..003c33727e35 --- /dev/null +++ b/include/clang/AST/CommentBriefParser.h @@ -0,0 +1,56 @@ +//===--- CommentBriefParser.h - Dumb comment parser -------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines a very simple Doxygen comment parser. +// +//===----------------------------------------------------------------------===// + + +#ifndef LLVM_CLANG_AST_BRIEF_COMMENT_PARSER_H +#define LLVM_CLANG_AST_BRIEF_COMMENT_PARSER_H + +#include "clang/AST/CommentLexer.h" + +namespace clang { +namespace comments { + +/// A very simple comment parser that extracts "a brief description". +/// +/// Due to a variety of comment styles, it considers the following as "a brief +/// description", in order of priority: +/// \li a \\brief or \\short command, +/// \li the first paragraph, +/// \li a \\result or \\return or \\returns paragraph. +class BriefParser { + Lexer &L; + + const CommandTraits &Traits; + + /// Current lookahead token. + Token Tok; + + SourceLocation ConsumeToken() { + SourceLocation Loc = Tok.getLocation(); + L.lex(Tok); + return Loc; + } + +public: + BriefParser(Lexer &L, const CommandTraits &Traits); + + /// Return \\brief paragraph, if it exists; otherwise return the first + /// paragraph. + std::string Parse(); +}; + +} // end namespace comments +} // end namespace clang + +#endif + diff --git a/include/clang/AST/CommentCommandTraits.h b/include/clang/AST/CommentCommandTraits.h new file mode 100644 index 000000000000..f1883755e520 --- /dev/null +++ b/include/clang/AST/CommentCommandTraits.h @@ -0,0 +1,156 @@ +//===--- CommentCommandTraits.h - Comment command properties ----*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the class that provides information about comment +// commands. +// +//===----------------------------------------------------------------------===// + + +#ifndef LLVM_CLANG_AST_COMMENT_COMMAND_TRAITS_H +#define LLVM_CLANG_AST_COMMENT_COMMAND_TRAITS_H + +#include "clang/Basic/LLVM.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/StringSwitch.h" + +namespace clang { +namespace comments { + +/// This class provides informaiton about commands that can be used +/// in comments. +class CommandTraits { +public: + CommandTraits() { } + + /// \brief Check if a given command is a verbatim-like block command. + /// + /// A verbatim-like block command eats every character (except line starting + /// decorations) until matching end command is seen or comment end is hit. + /// + /// \param BeginName name of the command that starts the verbatim block. + /// \param [out] EndName name of the command that ends the verbatim block. + /// + /// \returns true if a given command is a verbatim block command. + bool isVerbatimBlockCommand(StringRef StartName, StringRef &EndName) const; + + /// \brief Register a new verbatim block command. + void addVerbatimBlockCommand(StringRef BeginName, StringRef EndName); + + /// \brief Check if a given command is a verbatim line command. + /// + /// A verbatim-like line command eats everything until a newline is seen or + /// comment end is hit. + bool isVerbatimLineCommand(StringRef Name) const; + + /// \brief Check if a given command is a command that contains a declaration + /// for the entity being documented. + /// + /// For example: + /// \code + /// \fn void f(int a); + /// \endcode + bool isDeclarationCommand(StringRef Name) const; + + /// \brief Register a new verbatim line command. + void addVerbatimLineCommand(StringRef Name); + + /// \brief Check if a given command is a block command (of any kind). + bool isBlockCommand(StringRef Name) const; + + /// \brief Check if a given command is introducing documentation for + /// a function parameter (\\param or an alias). + bool isParamCommand(StringRef Name) const; + + /// \brief Check if a given command is introducing documentation for + /// a template parameter (\\tparam or an alias). + bool isTParamCommand(StringRef Name) const; + + /// \brief Check if a given command is introducing a brief documentation + /// paragraph (\\brief or an alias). + bool isBriefCommand(StringRef Name) const; + + /// \brief Check if a given command is \\brief or an alias. + bool isReturnsCommand(StringRef Name) const; + + /// \returns the number of word-like arguments for a given block command, + /// except for \\param and \\tparam commands -- these have special argument + /// parsers. + unsigned getBlockCommandNumArgs(StringRef Name) const; + + /// \brief Check if a given command is a inline command (of any kind). + bool isInlineCommand(StringRef Name) const; + +private: + struct VerbatimBlockCommand { + StringRef BeginName; + StringRef EndName; + }; + + typedef SmallVector VerbatimBlockCommandVector; + + /// Registered additional verbatim-like block commands. + VerbatimBlockCommandVector VerbatimBlockCommands; + + struct VerbatimLineCommand { + StringRef Name; + }; + + typedef SmallVector VerbatimLineCommandVector; + + /// Registered verbatim-like line commands. + VerbatimLineCommandVector VerbatimLineCommands; +}; + +inline bool CommandTraits::isBlockCommand(StringRef Name) const { + return isBriefCommand(Name) || isReturnsCommand(Name) || + isParamCommand(Name) || isTParamCommand(Name) || + llvm::StringSwitch(Name) + .Case("author", true) + .Case("authors", true) + .Case("pre", true) + .Case("post", true) + .Default(false); +} + +inline bool CommandTraits::isParamCommand(StringRef Name) const { + return Name == "param"; +} + +inline bool CommandTraits::isTParamCommand(StringRef Name) const { + return Name == "tparam" || // Doxygen + Name == "templatefield"; // HeaderDoc +} + +inline bool CommandTraits::isBriefCommand(StringRef Name) const { + return Name == "brief" || Name == "short"; +} + +inline bool CommandTraits::isReturnsCommand(StringRef Name) const { + return Name == "returns" || Name == "return" || Name == "result"; +} + +inline unsigned CommandTraits::getBlockCommandNumArgs(StringRef Name) const { + return 0; +} + +inline bool CommandTraits::isInlineCommand(StringRef Name) const { + return llvm::StringSwitch(Name) + .Case("b", true) + .Cases("c", "p", true) + .Cases("a", "e", "em", true) + .Default(false); +} + +} // end namespace comments +} // end namespace clang + +#endif + diff --git a/include/clang/AST/CommentDiagnostic.h b/include/clang/AST/CommentDiagnostic.h new file mode 100644 index 000000000000..6e8941057994 --- /dev/null +++ b/include/clang/AST/CommentDiagnostic.h @@ -0,0 +1,29 @@ +//===--- CommentDiagnostic.h - Diagnostics for the AST library --*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_COMMENTDIAGNOSTIC_H +#define LLVM_CLANG_COMMENTDIAGNOSTIC_H + +#include "clang/Basic/Diagnostic.h" + +namespace clang { + namespace diag { + enum { +#define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,\ + SFINAE,ACCESS,NOWERROR,SHOWINSYSHEADER,CATEGORY) ENUM, +#define COMMENTSTART +#include "clang/Basic/DiagnosticCommentKinds.inc" +#undef DIAG + NUM_BUILTIN_COMMENT_DIAGNOSTICS + }; + } // end namespace diag +} // end namespace clang + +#endif + diff --git a/include/clang/AST/CommentLexer.h b/include/clang/AST/CommentLexer.h new file mode 100644 index 000000000000..7a24b1163178 --- /dev/null +++ b/include/clang/AST/CommentLexer.h @@ -0,0 +1,353 @@ +//===--- CommentLexer.h - Lexer for structured comments ---------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines lexer for structured comments and supporting token class. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_AST_COMMENT_LEXER_H +#define LLVM_CLANG_AST_COMMENT_LEXER_H + +#include "clang/Basic/SourceManager.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/ADT/SmallString.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/Support/Allocator.h" +#include "llvm/Support/raw_ostream.h" + +namespace clang { +namespace comments { + +class Lexer; +class TextTokenRetokenizer; +class CommandTraits; + +namespace tok { +enum TokenKind { + eof, + newline, + text, + command, + verbatim_block_begin, + verbatim_block_line, + verbatim_block_end, + verbatim_line_name, + verbatim_line_text, + html_start_tag, // + html_slash_greater, // /> + html_end_tag // '. + LS_HTMLEndTag + }; + + /// Current lexing mode. + LexerState State; + + /// If State is LS_VerbatimBlock, contains the name of verbatim end + /// command, including command marker. + SmallString<16> VerbatimBlockEndCommandName; + + /// Given a character reference name (e.g., "lt"), return the character that + /// it stands for (e.g., "<"). + StringRef resolveHTMLNamedCharacterReference(StringRef Name) const; + + /// Given a Unicode codepoint as base-10 integer, return the character. + StringRef resolveHTMLDecimalCharacterReference(StringRef Name) const; + + /// Given a Unicode codepoint as base-16 integer, return the character. + StringRef resolveHTMLHexCharacterReference(StringRef Name) const; + + void formTokenWithChars(Token &Result, const char *TokEnd, + tok::TokenKind Kind) { + const unsigned TokLen = TokEnd - BufferPtr; + Result.setLocation(getSourceLocation(BufferPtr)); + Result.setKind(Kind); + Result.setLength(TokLen); +#ifndef NDEBUG + Result.TextPtr1 = ""; + Result.TextLen1 = 7; +#endif + BufferPtr = TokEnd; + } + + void formTextToken(Token &Result, const char *TokEnd) { + StringRef Text(BufferPtr, TokEnd - BufferPtr); + formTokenWithChars(Result, TokEnd, tok::text); + Result.setText(Text); + } + + SourceLocation getSourceLocation(const char *Loc) const { + assert(Loc >= BufferStart && Loc <= BufferEnd && + "Location out of range for this buffer!"); + + const unsigned CharNo = Loc - BufferStart; + return FileLoc.getLocWithOffset(CharNo); + } + + /// Eat string matching regexp \code \s*\* \endcode. + void skipLineStartingDecorations(); + + /// Lex stuff inside comments. CommentEnd should be set correctly. + void lexCommentText(Token &T); + + void setupAndLexVerbatimBlock(Token &T, + const char *TextBegin, + char Marker, StringRef EndName); + + void lexVerbatimBlockFirstLine(Token &T); + + void lexVerbatimBlockBody(Token &T); + + void setupAndLexVerbatimLine(Token &T, const char *TextBegin); + + void lexVerbatimLineText(Token &T); + + void lexHTMLCharacterReference(Token &T); + + void setupAndLexHTMLStartTag(Token &T); + + void lexHTMLStartTag(Token &T); + + void setupAndLexHTMLEndTag(Token &T); + + void lexHTMLEndTag(Token &T); + +public: + Lexer(llvm::BumpPtrAllocator &Allocator, const CommandTraits &Traits, + SourceLocation FileLoc, const CommentOptions &CommOpts, + const char *BufferStart, const char *BufferEnd); + + void lex(Token &T); + + StringRef getSpelling(const Token &Tok, + const SourceManager &SourceMgr, + bool *Invalid = NULL) const; +}; + +} // end namespace comments +} // end namespace clang + +#endif + diff --git a/include/clang/AST/CommentParser.h b/include/clang/AST/CommentParser.h new file mode 100644 index 000000000000..039079931c58 --- /dev/null +++ b/include/clang/AST/CommentParser.h @@ -0,0 +1,124 @@ +//===--- CommentParser.h - Doxygen comment parser ---------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the Doxygen comment parser. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_AST_COMMENT_PARSER_H +#define LLVM_CLANG_AST_COMMENT_PARSER_H + +#include "clang/Basic/Diagnostic.h" +#include "clang/AST/CommentLexer.h" +#include "clang/AST/Comment.h" +#include "clang/AST/CommentSema.h" +#include "llvm/Support/Allocator.h" + +namespace clang { +class SourceManager; + +namespace comments { +class CommandTraits; + +/// Doxygen comment parser. +class Parser { + Parser(const Parser&); // DO NOT IMPLEMENT + void operator=(const Parser&); // DO NOT IMPLEMENT + + friend class TextTokenRetokenizer; + + Lexer &L; + + Sema &S; + + /// Allocator for anything that goes into AST nodes. + llvm::BumpPtrAllocator &Allocator; + + /// Source manager for the comment being parsed. + const SourceManager &SourceMgr; + + DiagnosticsEngine &Diags; + + DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { + return Diags.Report(Loc, DiagID); + } + + const CommandTraits &Traits; + + /// Current lookahead token. We can safely assume that all tokens are from + /// a single source file. + Token Tok; + + /// A stack of additional lookahead tokens. + SmallVector MoreLATokens; + + void consumeToken() { + if (MoreLATokens.empty()) + L.lex(Tok); + else { + Tok = MoreLATokens.back(); + MoreLATokens.pop_back(); + } + } + + void putBack(const Token &OldTok) { + MoreLATokens.push_back(Tok); + Tok = OldTok; + } + + void putBack(ArrayRef Toks) { + if (Toks.empty()) + return; + + MoreLATokens.push_back(Tok); + for (const Token *I = &Toks.back(), + *B = &Toks.front(); + I != B; --I) { + MoreLATokens.push_back(*I); + } + + Tok = Toks[0]; + } + +public: + Parser(Lexer &L, Sema &S, llvm::BumpPtrAllocator &Allocator, + const SourceManager &SourceMgr, DiagnosticsEngine &Diags, + const CommandTraits &Traits); + + /// Parse arguments for \\param command. + void parseParamCommandArgs(ParamCommandComment *PC, + TextTokenRetokenizer &Retokenizer); + + /// Parse arguments for \\tparam command. + void parseTParamCommandArgs(TParamCommandComment *TPC, + TextTokenRetokenizer &Retokenizer); + + void parseBlockCommandArgs(BlockCommandComment *BC, + TextTokenRetokenizer &Retokenizer, + unsigned NumArgs); + + BlockCommandComment *parseBlockCommand(); + InlineCommandComment *parseInlineCommand(); + + HTMLStartTagComment *parseHTMLStartTag(); + HTMLEndTagComment *parseHTMLEndTag(); + + BlockContentComment *parseParagraphOrBlockCommand(); + + VerbatimBlockComment *parseVerbatimBlock(); + VerbatimLineComment *parseVerbatimLine(); + BlockContentComment *parseBlockContent(); + FullComment *parseFullComment(); +}; + +} // end namespace comments +} // end namespace clang + +#endif + diff --git a/include/clang/AST/CommentSema.h b/include/clang/AST/CommentSema.h new file mode 100644 index 000000000000..e1756ca3e2f1 --- /dev/null +++ b/include/clang/AST/CommentSema.h @@ -0,0 +1,230 @@ +//===--- CommentSema.h - Doxygen comment semantic analysis ------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the semantic analysis class for Doxygen comments. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_AST_COMMENT_SEMA_H +#define LLVM_CLANG_AST_COMMENT_SEMA_H + +#include "clang/Basic/Diagnostic.h" +#include "clang/Basic/SourceLocation.h" +#include "clang/AST/Comment.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/ADT/StringMap.h" +#include "llvm/Support/Allocator.h" + +namespace clang { +class Decl; +class SourceMgr; + +namespace comments { +class CommandTraits; + +class Sema { + Sema(const Sema&); // DO NOT IMPLEMENT + void operator=(const Sema&); // DO NOT IMPLEMENT + + /// Allocator for AST nodes. + llvm::BumpPtrAllocator &Allocator; + + /// Source manager for the comment being parsed. + const SourceManager &SourceMgr; + + DiagnosticsEngine &Diags; + + const CommandTraits &Traits; + + /// Information about the declaration this comment is attached to. + DeclInfo *ThisDeclInfo; + + /// Comment AST nodes that correspond to \c ParamVars for which we have + /// found a \\param command or NULL if no documentation was found so far. + /// + /// Has correct size and contains valid values if \c DeclInfo->IsFilled is + /// true. + llvm::SmallVector ParamVarDocs; + + /// Comment AST nodes that correspond to parameter names in + /// \c TemplateParameters. + /// + /// Contains a valid value if \c DeclInfo->IsFilled is true. + llvm::StringMap TemplateParameterDocs; + + /// AST node for the \\brief command and its aliases. + const BlockCommandComment *BriefCommand; + + /// AST node for the \\returns command and its aliases. + const BlockCommandComment *ReturnsCommand; + + DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { + return Diags.Report(Loc, DiagID); + } + + /// A stack of HTML tags that are currently open (not matched with closing + /// tags). + SmallVector HTMLOpenTags; + +public: + Sema(llvm::BumpPtrAllocator &Allocator, const SourceManager &SourceMgr, + DiagnosticsEngine &Diags, const CommandTraits &Traits); + + void setDecl(const Decl *D); + + /// Returns a copy of array, owned by Sema's allocator. + template + ArrayRef copyArray(ArrayRef Source) { + size_t Size = Source.size(); + if (Size != 0) { + T *Mem = Allocator.Allocate(Size); + std::uninitialized_copy(Source.begin(), Source.end(), Mem); + return llvm::makeArrayRef(Mem, Size); + } else + return llvm::makeArrayRef(static_cast(NULL), 0); + } + + ParagraphComment *actOnParagraphComment( + ArrayRef Content); + + BlockCommandComment *actOnBlockCommandStart(SourceLocation LocBegin, + SourceLocation LocEnd, + StringRef Name); + + void actOnBlockCommandArgs(BlockCommandComment *Command, + ArrayRef Args); + + void actOnBlockCommandFinish(BlockCommandComment *Command, + ParagraphComment *Paragraph); + + ParamCommandComment *actOnParamCommandStart(SourceLocation LocBegin, + SourceLocation LocEnd, + StringRef Name); + + void actOnParamCommandDirectionArg(ParamCommandComment *Command, + SourceLocation ArgLocBegin, + SourceLocation ArgLocEnd, + StringRef Arg); + + void actOnParamCommandParamNameArg(ParamCommandComment *Command, + SourceLocation ArgLocBegin, + SourceLocation ArgLocEnd, + StringRef Arg); + + void actOnParamCommandFinish(ParamCommandComment *Command, + ParagraphComment *Paragraph); + + TParamCommandComment *actOnTParamCommandStart(SourceLocation LocBegin, + SourceLocation LocEnd, + StringRef Name); + + void actOnTParamCommandParamNameArg(TParamCommandComment *Command, + SourceLocation ArgLocBegin, + SourceLocation ArgLocEnd, + StringRef Arg); + + void actOnTParamCommandFinish(TParamCommandComment *Command, + ParagraphComment *Paragraph); + + InlineCommandComment *actOnInlineCommand(SourceLocation CommandLocBegin, + SourceLocation CommandLocEnd, + StringRef CommandName); + + InlineCommandComment *actOnInlineCommand(SourceLocation CommandLocBegin, + SourceLocation CommandLocEnd, + StringRef CommandName, + SourceLocation ArgLocBegin, + SourceLocation ArgLocEnd, + StringRef Arg); + + InlineContentComment *actOnUnknownCommand(SourceLocation LocBegin, + SourceLocation LocEnd, + StringRef Name); + + TextComment *actOnText(SourceLocation LocBegin, + SourceLocation LocEnd, + StringRef Text); + + VerbatimBlockComment *actOnVerbatimBlockStart(SourceLocation Loc, + StringRef Name); + + VerbatimBlockLineComment *actOnVerbatimBlockLine(SourceLocation Loc, + StringRef Text); + + void actOnVerbatimBlockFinish(VerbatimBlockComment *Block, + SourceLocation CloseNameLocBegin, + StringRef CloseName, + ArrayRef Lines); + + VerbatimLineComment *actOnVerbatimLine(SourceLocation LocBegin, + StringRef Name, + SourceLocation TextBegin, + StringRef Text); + + HTMLStartTagComment *actOnHTMLStartTagStart(SourceLocation LocBegin, + StringRef TagName); + + void actOnHTMLStartTagFinish(HTMLStartTagComment *Tag, + ArrayRef Attrs, + SourceLocation GreaterLoc, + bool IsSelfClosing); + + HTMLEndTagComment *actOnHTMLEndTag(SourceLocation LocBegin, + SourceLocation LocEnd, + StringRef TagName); + + FullComment *actOnFullComment(ArrayRef Blocks); + + void checkBlockCommandEmptyParagraph(BlockCommandComment *Command); + + void checkReturnsCommand(const BlockCommandComment *Command); + + /// Emit diagnostics about duplicate block commands that should be + /// used only once per comment, e.g., \\brief and \\returns. + void checkBlockCommandDuplicate(const BlockCommandComment *Command); + + bool isFunctionDecl(); + bool isTemplateOrSpecialization(); + + ArrayRef getParamVars(); + + /// Extract all important semantic information from + /// \c ThisDeclInfo->ThisDecl into \c ThisDeclInfo members. + void inspectThisDecl(); + + /// Returns index of a function parameter with a given name. + unsigned resolveParmVarReference(StringRef Name, + ArrayRef ParamVars); + + /// Returns index of a function parameter with the name closest to a given + /// typo. + unsigned correctTypoInParmVarReference(StringRef Typo, + ArrayRef ParamVars); + + bool resolveTParamReference(StringRef Name, + const TemplateParameterList *TemplateParameters, + SmallVectorImpl *Position); + + StringRef correctTypoInTParamReference( + StringRef Typo, + const TemplateParameterList *TemplateParameters); + + InlineCommandComment::RenderKind + getInlineCommandRenderKind(StringRef Name) const; + + bool isHTMLEndTagOptional(StringRef Name); + bool isHTMLEndTagForbidden(StringRef Name); +}; + +} // end namespace comments +} // end namespace clang + +#endif + diff --git a/include/clang/AST/CommentVisitor.h b/include/clang/AST/CommentVisitor.h new file mode 100644 index 000000000000..47867a634fcc --- /dev/null +++ b/include/clang/AST/CommentVisitor.h @@ -0,0 +1,66 @@ +//===--- CommentVisitor.h - Visitor for Comment subclasses ------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "clang/AST/Comment.h" +#include "llvm/Support/ErrorHandling.h" + +namespace clang { +namespace comments { + +template struct make_ptr { typedef T *type; }; +template struct make_const_ptr { typedef const T *type; }; + +template