diff --git a/clang-tools-extra/clangd/CodeComplete.h b/clang-tools-extra/clangd/CodeComplete.h --- a/clang-tools-extra/clangd/CodeComplete.h +++ b/clang-tools-extra/clangd/CodeComplete.h @@ -147,6 +147,22 @@ std::function RecordCCResult; + + /// Model to use for ranking code completion candidates. + enum CodeCompletionRankingModel { + Heuristics, + DecisionForest, + } RankingModel = Heuristics; + + /// Weight for combining NameMatch and Prediction of DecisionForest. + /// CompletionScore is NameMatch * pow(Base, Prediction). + /// The optimal value of Base largely depends on the semantics of the model + /// and prediction score (e.g. algorithm used during training, number of + /// trees, etc.). Usually if the range of Prediciton is [-20, 20] then a Base + /// in [1.2, 1.7] works fine. + /// Semantics: E.g. the completion score reduces by 50% if the Prediciton + /// score is reduced by 2.6 points for Base = 1.3. + float DecisionForestBase = 1.3f; }; // Semi-structured representation of a code-complete suggestion for our C++ API. diff --git a/clang-tools-extra/clangd/CodeComplete.cpp b/clang-tools-extra/clangd/CodeComplete.cpp --- a/clang-tools-extra/clangd/CodeComplete.cpp +++ b/clang-tools-extra/clangd/CodeComplete.cpp @@ -1625,6 +1625,43 @@ return Filter->match(C.Name); } + CodeCompletion::Scores + evaluateCompletion(const SymbolQualitySignals &Quality, + const SymbolRelevanceSignals &Relevance) { + using RM = CodeCompleteOptions::CodeCompletionRankingModel; + CodeCompletion::Scores Scores; + switch (Opts.RankingModel) { + case RM::Heuristics: + Scores.Quality = Quality.evaluate(); + Scores.Relevance = Relevance.evaluate(); + Scores.Total = + evaluateSymbolAndRelevance(Scores.Quality, Scores.Relevance); + // NameMatch is in fact a multiplier on total score, so rescoring is + // sound. + Scores.ExcludingName = Relevance.NameMatch + ? Scores.Total / Relevance.NameMatch + : Scores.Quality; + return Scores; + + case RM::DecisionForest: + Scores.Quality = 0; + Scores.Relevance = 0; + // Exponentiating DecisionForest prediction makes the score of each tree a + // multiplciative boost (like NameMatch). This allows us to weigh the + // prediciton score and NameMatch appropriately. + Scores.ExcludingName = pow(Opts.DecisionForestBase, + evaluateDecisionForest(Quality, Relevance)); + // NeedsFixIts is not part of the DecisionForest as generating training + // data that needs fixits is not-feasible. + if (Relevance.NeedsFixIts) + Scores.ExcludingName *= 0.5; + // NameMatch should be a multiplier on total score to support rescoring. + Scores.Total = Relevance.NameMatch * Scores.ExcludingName; + return Scores; + } + llvm_unreachable("Unhandled CodeCompletion ranking model."); + } + // Scores a candidate and adds it to the TopN structure. void addCandidate(TopN &Candidates, CompletionCandidate::Bundle Bundle) { @@ -1632,6 +1669,7 @@ SymbolRelevanceSignals Relevance; Relevance.Context = CCContextKind; Relevance.Name = Bundle.front().Name; + Relevance.FilterLength = HeuristicPrefix.Name.size(); Relevance.Query = SymbolRelevanceSignals::CodeComplete; Relevance.FileProximityMatch = FileProximity.getPointer(); if (ScopeProximity) @@ -1680,15 +1718,7 @@ } } - CodeCompletion::Scores Scores; - Scores.Quality = Quality.evaluate(); - Scores.Relevance = Relevance.evaluate(); - Scores.Total = evaluateSymbolAndRelevance(Scores.Quality, Scores.Relevance); - // NameMatch is in fact a multiplier on total score, so rescoring is sound. - Scores.ExcludingName = Relevance.NameMatch - ? Scores.Total / Relevance.NameMatch - : Scores.Quality; - + CodeCompletion::Scores Scores = evaluateCompletion(Quality, Relevance); if (Opts.RecordCCResult) Opts.RecordCCResult(toCodeCompletion(Bundle), Quality, Relevance, Scores.Total); diff --git a/clang-tools-extra/clangd/Quality.h b/clang-tools-extra/clangd/Quality.h --- a/clang-tools-extra/clangd/Quality.h +++ b/clang-tools-extra/clangd/Quality.h @@ -77,6 +77,7 @@ void merge(const CodeCompletionResult &SemaCCResult); void merge(const Symbol &IndexResult); + // FIXME(usx): Rename to evaluateHeuristics(). // Condense these signals down to a single number, higher is better. float evaluate() const; }; @@ -136,6 +137,10 @@ // Whether the item matches the type expected in the completion context. bool TypeMatchesPreferred = false; + /// Length of the unqualified partial name of Symbol typed in + /// CompletionPrefix. + unsigned FilterLength = 0; + /// Set of derived signals computed by calculateDerivedSignals(). Must not be /// set explicitly. struct DerivedSignals { @@ -161,6 +166,8 @@ /// Combine symbol quality and relevance into a single score. float evaluateSymbolAndRelevance(float SymbolQuality, float SymbolRelevance); +float evaluateDecisionForest(const SymbolQualitySignals &Quality, + const SymbolRelevanceSignals &Relevance); /// TopN is a lossy container that preserves only the "best" N elements. template > class TopN { public: diff --git a/clang-tools-extra/clangd/Quality.cpp b/clang-tools-extra/clangd/Quality.cpp --- a/clang-tools-extra/clangd/Quality.cpp +++ b/clang-tools-extra/clangd/Quality.cpp @@ -8,6 +8,7 @@ #include "Quality.h" #include "AST.h" +#include "CompletionModel.h" #include "FileDistance.h" #include "SourceCode.h" #include "URI.h" @@ -486,6 +487,34 @@ return SymbolQuality * SymbolRelevance; } +float evaluateDecisionForest(const SymbolQualitySignals &Quality, + const SymbolRelevanceSignals &Relevance) { + Example E; + E.setIsDeprecated(Quality.Deprecated); + E.setIsReservedName(Quality.ReservedName); + E.setIsImplementationDetail(Quality.ImplementationDetail); + E.setNumReferences(Quality.References); + E.setSymbolCategory(Quality.Category); + + SymbolRelevanceSignals::DerivedSignals Derived = + Relevance.calculateDerivedSignals(); + E.setIsNameInContext(Derived.NameMatchesContext); + E.setIsForbidden(Relevance.Forbidden); + E.setIsInBaseClass(Relevance.InBaseClass); + E.setFileProximityDistance(Derived.FileProximityDistance); + E.setSemaFileProximityScore(Relevance.SemaFileProximityScore); + E.setSymbolScopeDistance(Derived.ScopeProximityDistance); + E.setSemaSaysInScope(Relevance.SemaSaysInScope); + E.setScope(Relevance.Scope); + E.setContextKind(Relevance.Context); + E.setIsInstanceMember(Relevance.IsInstanceMember); + E.setHadContextType(Relevance.HadContextType); + E.setHadSymbolType(Relevance.HadSymbolType); + E.setTypeMatchesPreferred(Relevance.TypeMatchesPreferred); + E.setFilterLength(Relevance.FilterLength); + return Evaluate(E); +} + // Produces an integer that sorts in the same order as F. // That is: a < b <==> encodeFloat(a) < encodeFloat(b). static uint32_t encodeFloat(float F) { diff --git a/clang-tools-extra/clangd/tool/ClangdMain.cpp b/clang-tools-extra/clangd/tool/ClangdMain.cpp --- a/clang-tools-extra/clangd/tool/ClangdMain.cpp +++ b/clang-tools-extra/clangd/tool/ClangdMain.cpp @@ -167,6 +167,26 @@ Hidden, }; +opt RankingModel{ + "ranking-model", + cat(Features), + desc("Model to use to rank code-completion items"), + values(clEnumValN(CodeCompleteOptions::Heuristics, "heuristics", + "Use hueristics to rank code completion items"), + clEnumValN(CodeCompleteOptions::DecisionForest, "decision_forest", + "Use Decision Forest model to rank completion items")), + init(CodeCompleteOptions().RankingModel), + Hidden, +}; + +opt DecisionForestBase{ + "decision-forest-base", + cat(Features), + desc("Base for exponentiating the prediction from DecisionForest."), + init(CodeCompleteOptions().DecisionForestBase), + Hidden, +}; + // FIXME: also support "plain" style where signatures are always omitted. enum CompletionStyleFlag { Detailed, Bundled }; opt CompletionStyle{ @@ -739,6 +759,8 @@ CCOpts.EnableFunctionArgSnippets = EnableFunctionArgSnippets; CCOpts.AllScopes = AllScopesCompletion; CCOpts.RunParser = CodeCompletionParse; + CCOpts.RankingModel = RankingModel; + CCOpts.DecisionForestBase = DecisionForestBase; RealThreadsafeFS TFS; std::vector> ProviderStack; diff --git a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp --- a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp +++ b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp @@ -10,7 +10,6 @@ #include "ClangdServer.h" #include "CodeComplete.h" #include "Compiler.h" -#include "CompletionModel.h" #include "Matchers.h" #include "Protocol.h" #include "Quality.h" @@ -163,14 +162,38 @@ return S; } -TEST(DecisionForestRuntime, SanityTest) { - using Example = clangd::Example; - using clangd::Evaluate; - Example E1; - E1.setContextKind(ContextKind::CCC_ArrowMemberAccess); - Example E2; - E2.setContextKind(ContextKind::CCC_SymbolOrNewName); - EXPECT_GT(Evaluate(E1), Evaluate(E2)); +TEST(DecisionForestRankingModel, NameMatchSanityTest) { + clangd::CodeCompleteOptions Opts; + Opts.RankingModel = CodeCompleteOptions::DecisionForest; + auto Results = completions( + R"cpp( +struct MemberAccess { + int ABG(); + int AlphaBetaGamma(); +}; +int func() { MemberAccess().ABG^ } +)cpp", + /*IndexSymbols=*/{}, Opts); + EXPECT_THAT(Results.Completions, + ElementsAre(Named("ABG"), Named("AlphaBetaGamma"))); +} + +TEST(DecisionForestRankingModel, ReferencesAffectRanking) { + clangd::CodeCompleteOptions Opts; + Opts.RankingModel = CodeCompleteOptions::DecisionForest; + constexpr int NumReferences = 100000; + EXPECT_THAT( + completions("int main() { clang^ }", + {ns("clangA"), withReferences(NumReferences, func("clangD"))}, + Opts) + .Completions, + ElementsAre(Named("clangD"), Named("clangA"))); + EXPECT_THAT( + completions("int main() { clang^ }", + {withReferences(NumReferences, ns("clangA")), func("clangD")}, + Opts) + .Completions, + ElementsAre(Named("clangA"), Named("clangD"))); } TEST(CompletionTest, Limit) {