1 //===--- Quality.cpp ---------------------------------------------*- C++-*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "Quality.h"
10 #include "AST.h"
11 #include "CompletionModel.h"
12 #include "FileDistance.h"
13 #include "SourceCode.h"
14 #include "URI.h"
15 #include "index/Symbol.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/DeclVisitor.h"
21 #include "clang/Basic/CharInfo.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Sema/CodeCompleteConsumer.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/FormatVariadic.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <algorithm>
34 #include <cmath>
35
36 namespace clang {
37 namespace clangd {
isReserved(llvm::StringRef Name)38 static bool isReserved(llvm::StringRef Name) {
39 // FIXME: Should we exclude _Bool and others recognized by the standard?
40 return Name.size() >= 2 && Name[0] == '_' &&
41 (isUppercase(Name[1]) || Name[1] == '_');
42 }
43
hasDeclInMainFile(const Decl & D)44 static bool hasDeclInMainFile(const Decl &D) {
45 auto &SourceMgr = D.getASTContext().getSourceManager();
46 for (auto *Redecl : D.redecls()) {
47 if (isInsideMainFile(Redecl->getLocation(), SourceMgr))
48 return true;
49 }
50 return false;
51 }
52
hasUsingDeclInMainFile(const CodeCompletionResult & R)53 static bool hasUsingDeclInMainFile(const CodeCompletionResult &R) {
54 const auto &Context = R.Declaration->getASTContext();
55 const auto &SourceMgr = Context.getSourceManager();
56 if (R.ShadowDecl) {
57 if (isInsideMainFile(R.ShadowDecl->getLocation(), SourceMgr))
58 return true;
59 }
60 return false;
61 }
62
categorize(const NamedDecl & ND)63 static SymbolQualitySignals::SymbolCategory categorize(const NamedDecl &ND) {
64 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
65 if (FD->isOverloadedOperator())
66 return SymbolQualitySignals::Operator;
67 }
68 class Switch
69 : public ConstDeclVisitor<Switch, SymbolQualitySignals::SymbolCategory> {
70 public:
71 #define MAP(DeclType, Category) \
72 SymbolQualitySignals::SymbolCategory Visit##DeclType(const DeclType *) { \
73 return SymbolQualitySignals::Category; \
74 }
75 MAP(NamespaceDecl, Namespace);
76 MAP(NamespaceAliasDecl, Namespace);
77 MAP(TypeDecl, Type);
78 MAP(TypeAliasTemplateDecl, Type);
79 MAP(ClassTemplateDecl, Type);
80 MAP(CXXConstructorDecl, Constructor);
81 MAP(CXXDestructorDecl, Destructor);
82 MAP(ValueDecl, Variable);
83 MAP(VarTemplateDecl, Variable);
84 MAP(FunctionDecl, Function);
85 MAP(FunctionTemplateDecl, Function);
86 MAP(Decl, Unknown);
87 #undef MAP
88 };
89 return Switch().Visit(&ND);
90 }
91
92 static SymbolQualitySignals::SymbolCategory
categorize(const CodeCompletionResult & R)93 categorize(const CodeCompletionResult &R) {
94 if (R.Declaration)
95 return categorize(*R.Declaration);
96 if (R.Kind == CodeCompletionResult::RK_Macro)
97 return SymbolQualitySignals::Macro;
98 // Everything else is a keyword or a pattern. Patterns are mostly keywords
99 // too, except a few which we recognize by cursor kind.
100 switch (R.CursorKind) {
101 case CXCursor_CXXMethod:
102 return SymbolQualitySignals::Function;
103 case CXCursor_ModuleImportDecl:
104 return SymbolQualitySignals::Namespace;
105 case CXCursor_MacroDefinition:
106 return SymbolQualitySignals::Macro;
107 case CXCursor_TypeRef:
108 return SymbolQualitySignals::Type;
109 case CXCursor_MemberRef:
110 return SymbolQualitySignals::Variable;
111 case CXCursor_Constructor:
112 return SymbolQualitySignals::Constructor;
113 default:
114 return SymbolQualitySignals::Keyword;
115 }
116 }
117
118 static SymbolQualitySignals::SymbolCategory
categorize(const index::SymbolInfo & D)119 categorize(const index::SymbolInfo &D) {
120 switch (D.Kind) {
121 case index::SymbolKind::Namespace:
122 case index::SymbolKind::NamespaceAlias:
123 return SymbolQualitySignals::Namespace;
124 case index::SymbolKind::Macro:
125 return SymbolQualitySignals::Macro;
126 case index::SymbolKind::Enum:
127 case index::SymbolKind::Struct:
128 case index::SymbolKind::Class:
129 case index::SymbolKind::Protocol:
130 case index::SymbolKind::Extension:
131 case index::SymbolKind::Union:
132 case index::SymbolKind::TypeAlias:
133 case index::SymbolKind::TemplateTypeParm:
134 case index::SymbolKind::TemplateTemplateParm:
135 return SymbolQualitySignals::Type;
136 case index::SymbolKind::Function:
137 case index::SymbolKind::ClassMethod:
138 case index::SymbolKind::InstanceMethod:
139 case index::SymbolKind::StaticMethod:
140 case index::SymbolKind::InstanceProperty:
141 case index::SymbolKind::ClassProperty:
142 case index::SymbolKind::StaticProperty:
143 case index::SymbolKind::ConversionFunction:
144 return SymbolQualitySignals::Function;
145 case index::SymbolKind::Destructor:
146 return SymbolQualitySignals::Destructor;
147 case index::SymbolKind::Constructor:
148 return SymbolQualitySignals::Constructor;
149 case index::SymbolKind::Variable:
150 case index::SymbolKind::Field:
151 case index::SymbolKind::EnumConstant:
152 case index::SymbolKind::Parameter:
153 case index::SymbolKind::NonTypeTemplateParm:
154 return SymbolQualitySignals::Variable;
155 case index::SymbolKind::Using:
156 case index::SymbolKind::Module:
157 case index::SymbolKind::Unknown:
158 return SymbolQualitySignals::Unknown;
159 }
160 llvm_unreachable("Unknown index::SymbolKind");
161 }
162
isInstanceMember(const NamedDecl * ND)163 static bool isInstanceMember(const NamedDecl *ND) {
164 if (!ND)
165 return false;
166 if (const auto *TP = dyn_cast<FunctionTemplateDecl>(ND))
167 ND = TP->TemplateDecl::getTemplatedDecl();
168 if (const auto *CM = dyn_cast<CXXMethodDecl>(ND))
169 return !CM->isStatic();
170 return isa<FieldDecl>(ND); // Note that static fields are VarDecl.
171 }
172
isInstanceMember(const index::SymbolInfo & D)173 static bool isInstanceMember(const index::SymbolInfo &D) {
174 switch (D.Kind) {
175 case index::SymbolKind::InstanceMethod:
176 case index::SymbolKind::InstanceProperty:
177 case index::SymbolKind::Field:
178 return true;
179 default:
180 return false;
181 }
182 }
183
merge(const CodeCompletionResult & SemaCCResult)184 void SymbolQualitySignals::merge(const CodeCompletionResult &SemaCCResult) {
185 Deprecated |= (SemaCCResult.Availability == CXAvailability_Deprecated);
186 Category = categorize(SemaCCResult);
187
188 if (SemaCCResult.Declaration) {
189 ImplementationDetail |= isImplementationDetail(SemaCCResult.Declaration);
190 if (auto *ID = SemaCCResult.Declaration->getIdentifier())
191 ReservedName = ReservedName || isReserved(ID->getName());
192 } else if (SemaCCResult.Kind == CodeCompletionResult::RK_Macro)
193 ReservedName = ReservedName || isReserved(SemaCCResult.Macro->getName());
194 }
195
merge(const Symbol & IndexResult)196 void SymbolQualitySignals::merge(const Symbol &IndexResult) {
197 Deprecated |= (IndexResult.Flags & Symbol::Deprecated);
198 ImplementationDetail |= (IndexResult.Flags & Symbol::ImplementationDetail);
199 References = std::max(IndexResult.References, References);
200 Category = categorize(IndexResult.SymInfo);
201 ReservedName = ReservedName || isReserved(IndexResult.Name);
202 }
203
evaluateHeuristics() const204 float SymbolQualitySignals::evaluateHeuristics() const {
205 float Score = 1;
206
207 // This avoids a sharp gradient for tail symbols, and also neatly avoids the
208 // question of whether 0 references means a bad symbol or missing data.
209 if (References >= 10) {
210 // Use a sigmoid style boosting function, which flats out nicely for large
211 // numbers (e.g. 2.58 for 1M references).
212 // The following boosting function is equivalent to:
213 // m = 0.06
214 // f = 12.0
215 // boost = f * sigmoid(m * std::log(References)) - 0.5 * f + 0.59
216 // Sample data points: (10, 1.00), (100, 1.41), (1000, 1.82),
217 // (10K, 2.21), (100K, 2.58), (1M, 2.94)
218 float S = std::pow(References, -0.06);
219 Score *= 6.0 * (1 - S) / (1 + S) + 0.59;
220 }
221
222 if (Deprecated)
223 Score *= 0.1f;
224 if (ReservedName)
225 Score *= 0.1f;
226 if (ImplementationDetail)
227 Score *= 0.2f;
228
229 switch (Category) {
230 case Keyword: // Often relevant, but misses most signals.
231 Score *= 4; // FIXME: important keywords should have specific boosts.
232 break;
233 case Type:
234 case Function:
235 case Variable:
236 Score *= 1.1f;
237 break;
238 case Namespace:
239 Score *= 0.8f;
240 break;
241 case Macro:
242 case Destructor:
243 case Operator:
244 Score *= 0.5f;
245 break;
246 case Constructor: // No boost constructors so they are after class types.
247 case Unknown:
248 break;
249 }
250
251 return Score;
252 }
253
operator <<(llvm::raw_ostream & OS,const SymbolQualitySignals & S)254 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
255 const SymbolQualitySignals &S) {
256 OS << llvm::formatv("=== Symbol quality: {0}\n", S.evaluateHeuristics());
257 OS << llvm::formatv("\tReferences: {0}\n", S.References);
258 OS << llvm::formatv("\tDeprecated: {0}\n", S.Deprecated);
259 OS << llvm::formatv("\tReserved name: {0}\n", S.ReservedName);
260 OS << llvm::formatv("\tImplementation detail: {0}\n", S.ImplementationDetail);
261 OS << llvm::formatv("\tCategory: {0}\n", static_cast<int>(S.Category));
262 return OS;
263 }
264
265 static SymbolRelevanceSignals::AccessibleScope
computeScope(const NamedDecl * D)266 computeScope(const NamedDecl *D) {
267 // Injected "Foo" within the class "Foo" has file scope, not class scope.
268 const DeclContext *DC = D->getDeclContext();
269 if (auto *R = dyn_cast_or_null<RecordDecl>(D))
270 if (R->isInjectedClassName())
271 DC = DC->getParent();
272 // Class constructor should have the same scope as the class.
273 if (isa<CXXConstructorDecl>(D))
274 DC = DC->getParent();
275 bool InClass = false;
276 for (; !DC->isFileContext(); DC = DC->getParent()) {
277 if (DC->isFunctionOrMethod())
278 return SymbolRelevanceSignals::FunctionScope;
279 InClass = InClass || DC->isRecord();
280 }
281 if (InClass)
282 return SymbolRelevanceSignals::ClassScope;
283 // ExternalLinkage threshold could be tweaked, e.g. module-visible as global.
284 // Avoid caching linkage if it may change after enclosing code completion.
285 if (hasUnstableLinkage(D) || D->getLinkageInternal() < ExternalLinkage)
286 return SymbolRelevanceSignals::FileScope;
287 return SymbolRelevanceSignals::GlobalScope;
288 }
289
merge(const Symbol & IndexResult)290 void SymbolRelevanceSignals::merge(const Symbol &IndexResult) {
291 SymbolURI = IndexResult.CanonicalDeclaration.FileURI;
292 SymbolScope = IndexResult.Scope;
293 IsInstanceMember |= isInstanceMember(IndexResult.SymInfo);
294 if (!(IndexResult.Flags & Symbol::VisibleOutsideFile)) {
295 Scope = AccessibleScope::FileScope;
296 }
297 }
298
merge(const CodeCompletionResult & SemaCCResult)299 void SymbolRelevanceSignals::merge(const CodeCompletionResult &SemaCCResult) {
300 if (SemaCCResult.Availability == CXAvailability_NotAvailable ||
301 SemaCCResult.Availability == CXAvailability_NotAccessible)
302 Forbidden = true;
303
304 if (SemaCCResult.Declaration) {
305 SemaSaysInScope = true;
306 // We boost things that have decls in the main file. We give a fixed score
307 // for all other declarations in sema as they are already included in the
308 // translation unit.
309 float DeclProximity = (hasDeclInMainFile(*SemaCCResult.Declaration) ||
310 hasUsingDeclInMainFile(SemaCCResult))
311 ? 1.0
312 : 0.6;
313 SemaFileProximityScore = std::max(DeclProximity, SemaFileProximityScore);
314 IsInstanceMember |= isInstanceMember(SemaCCResult.Declaration);
315 InBaseClass |= SemaCCResult.InBaseClass;
316 }
317
318 // Declarations are scoped, others (like macros) are assumed global.
319 if (SemaCCResult.Declaration)
320 Scope = std::min(Scope, computeScope(SemaCCResult.Declaration));
321
322 NeedsFixIts = !SemaCCResult.FixIts.empty();
323 }
324
fileProximityScore(unsigned FileDistance)325 static float fileProximityScore(unsigned FileDistance) {
326 // Range: [0, 1]
327 // FileDistance = [0, 1, 2, 3, 4, .., FileDistance::Unreachable]
328 // Score = [1, 0.82, 0.67, 0.55, 0.45, .., 0]
329 if (FileDistance == FileDistance::Unreachable)
330 return 0;
331 // Assume approximately default options are used for sensible scoring.
332 return std::exp(FileDistance * -0.4f / FileDistanceOptions().UpCost);
333 }
334
scopeProximityScore(unsigned ScopeDistance)335 static float scopeProximityScore(unsigned ScopeDistance) {
336 // Range: [0.6, 2].
337 // ScopeDistance = [0, 1, 2, 3, 4, 5, 6, 7, .., FileDistance::Unreachable]
338 // Score = [2.0, 1.55, 1.2, 0.93, 0.72, 0.65, 0.65, 0.65, .., 0.6]
339 if (ScopeDistance == FileDistance::Unreachable)
340 return 0.6f;
341 return std::max(0.65, 2.0 * std::pow(0.6, ScopeDistance / 2.0));
342 }
343
344 static llvm::Optional<llvm::StringRef>
wordMatching(llvm::StringRef Name,const llvm::StringSet<> * ContextWords)345 wordMatching(llvm::StringRef Name, const llvm::StringSet<> *ContextWords) {
346 if (ContextWords)
347 for (const auto &Word : ContextWords->keys())
348 if (Name.contains_lower(Word))
349 return Word;
350 return llvm::None;
351 }
352
353 SymbolRelevanceSignals::DerivedSignals
calculateDerivedSignals() const354 SymbolRelevanceSignals::calculateDerivedSignals() const {
355 DerivedSignals Derived;
356 Derived.NameMatchesContext = wordMatching(Name, ContextWords).hasValue();
357 Derived.FileProximityDistance = !FileProximityMatch || SymbolURI.empty()
358 ? FileDistance::Unreachable
359 : FileProximityMatch->distance(SymbolURI);
360 if (ScopeProximityMatch) {
361 // For global symbol, the distance is 0.
362 Derived.ScopeProximityDistance =
363 SymbolScope ? ScopeProximityMatch->distance(*SymbolScope) : 0;
364 }
365 return Derived;
366 }
367
evaluateHeuristics() const368 float SymbolRelevanceSignals::evaluateHeuristics() const {
369 DerivedSignals Derived = calculateDerivedSignals();
370 float Score = 1;
371
372 if (Forbidden)
373 return 0;
374
375 Score *= NameMatch;
376
377 // File proximity scores are [0,1] and we translate them into a multiplier in
378 // the range from 1 to 3.
379 Score *= 1 + 2 * std::max(fileProximityScore(Derived.FileProximityDistance),
380 SemaFileProximityScore);
381
382 if (ScopeProximityMatch)
383 // Use a constant scope boost for sema results, as scopes of sema results
384 // can be tricky (e.g. class/function scope). Set to the max boost as we
385 // don't load top-level symbols from the preamble and sema results are
386 // always in the accessible scope.
387 Score *= SemaSaysInScope
388 ? 2.0
389 : scopeProximityScore(Derived.ScopeProximityDistance);
390
391 if (Derived.NameMatchesContext)
392 Score *= 1.5;
393
394 // Symbols like local variables may only be referenced within their scope.
395 // Conversely if we're in that scope, it's likely we'll reference them.
396 if (Query == CodeComplete) {
397 // The narrower the scope where a symbol is visible, the more likely it is
398 // to be relevant when it is available.
399 switch (Scope) {
400 case GlobalScope:
401 break;
402 case FileScope:
403 Score *= 1.5f;
404 break;
405 case ClassScope:
406 Score *= 2;
407 break;
408 case FunctionScope:
409 Score *= 4;
410 break;
411 }
412 } else {
413 // For non-completion queries, the wider the scope where a symbol is
414 // visible, the more likely it is to be relevant.
415 switch (Scope) {
416 case GlobalScope:
417 break;
418 case FileScope:
419 Score *= 0.5f;
420 break;
421 default:
422 // TODO: Handle other scopes as we start to use them for index results.
423 break;
424 }
425 }
426
427 if (TypeMatchesPreferred)
428 Score *= 5.0;
429
430 // Penalize non-instance members when they are accessed via a class instance.
431 if (!IsInstanceMember &&
432 (Context == CodeCompletionContext::CCC_DotMemberAccess ||
433 Context == CodeCompletionContext::CCC_ArrowMemberAccess)) {
434 Score *= 0.2f;
435 }
436
437 if (InBaseClass)
438 Score *= 0.5f;
439
440 // Penalize for FixIts.
441 if (NeedsFixIts)
442 Score *= 0.5f;
443
444 return Score;
445 }
446
operator <<(llvm::raw_ostream & OS,const SymbolRelevanceSignals & S)447 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
448 const SymbolRelevanceSignals &S) {
449 OS << llvm::formatv("=== Symbol relevance: {0}\n", S.evaluateHeuristics());
450 OS << llvm::formatv("\tName: {0}\n", S.Name);
451 OS << llvm::formatv("\tName match: {0}\n", S.NameMatch);
452 if (S.ContextWords)
453 OS << llvm::formatv(
454 "\tMatching context word: {0}\n",
455 wordMatching(S.Name, S.ContextWords).getValueOr("<none>"));
456 OS << llvm::formatv("\tForbidden: {0}\n", S.Forbidden);
457 OS << llvm::formatv("\tNeedsFixIts: {0}\n", S.NeedsFixIts);
458 OS << llvm::formatv("\tIsInstanceMember: {0}\n", S.IsInstanceMember);
459 OS << llvm::formatv("\tInBaseClass: {0}\n", S.InBaseClass);
460 OS << llvm::formatv("\tContext: {0}\n", getCompletionKindString(S.Context));
461 OS << llvm::formatv("\tQuery type: {0}\n", static_cast<int>(S.Query));
462 OS << llvm::formatv("\tScope: {0}\n", static_cast<int>(S.Scope));
463
464 OS << llvm::formatv("\tSymbol URI: {0}\n", S.SymbolURI);
465 OS << llvm::formatv("\tSymbol scope: {0}\n",
466 S.SymbolScope ? *S.SymbolScope : "<None>");
467
468 SymbolRelevanceSignals::DerivedSignals Derived = S.calculateDerivedSignals();
469 if (S.FileProximityMatch) {
470 unsigned Score = fileProximityScore(Derived.FileProximityDistance);
471 OS << llvm::formatv("\tIndex URI proximity: {0} (distance={1})\n", Score,
472 Derived.FileProximityDistance);
473 }
474 OS << llvm::formatv("\tSema file proximity: {0}\n", S.SemaFileProximityScore);
475
476 OS << llvm::formatv("\tSema says in scope: {0}\n", S.SemaSaysInScope);
477 if (S.ScopeProximityMatch)
478 OS << llvm::formatv("\tIndex scope boost: {0}\n",
479 scopeProximityScore(Derived.ScopeProximityDistance));
480
481 OS << llvm::formatv(
482 "\tType matched preferred: {0} (Context type: {1}, Symbol type: {2}\n",
483 S.TypeMatchesPreferred, S.HadContextType, S.HadSymbolType);
484
485 return OS;
486 }
487
evaluateSymbolAndRelevance(float SymbolQuality,float SymbolRelevance)488 float evaluateSymbolAndRelevance(float SymbolQuality, float SymbolRelevance) {
489 return SymbolQuality * SymbolRelevance;
490 }
491
492 DecisionForestScores
evaluateDecisionForest(const SymbolQualitySignals & Quality,const SymbolRelevanceSignals & Relevance,float Base)493 evaluateDecisionForest(const SymbolQualitySignals &Quality,
494 const SymbolRelevanceSignals &Relevance, float Base) {
495 Example E;
496 E.setIsDeprecated(Quality.Deprecated);
497 E.setIsReservedName(Quality.ReservedName);
498 E.setIsImplementationDetail(Quality.ImplementationDetail);
499 E.setNumReferences(Quality.References);
500 E.setSymbolCategory(Quality.Category);
501
502 SymbolRelevanceSignals::DerivedSignals Derived =
503 Relevance.calculateDerivedSignals();
504 E.setIsNameInContext(Derived.NameMatchesContext);
505 E.setIsForbidden(Relevance.Forbidden);
506 E.setIsInBaseClass(Relevance.InBaseClass);
507 E.setFileProximityDistance(Derived.FileProximityDistance);
508 E.setSemaFileProximityScore(Relevance.SemaFileProximityScore);
509 E.setSymbolScopeDistance(Derived.ScopeProximityDistance);
510 E.setSemaSaysInScope(Relevance.SemaSaysInScope);
511 E.setScope(Relevance.Scope);
512 E.setContextKind(Relevance.Context);
513 E.setIsInstanceMember(Relevance.IsInstanceMember);
514 E.setHadContextType(Relevance.HadContextType);
515 E.setHadSymbolType(Relevance.HadSymbolType);
516 E.setTypeMatchesPreferred(Relevance.TypeMatchesPreferred);
517 E.setFilterLength(Relevance.FilterLength);
518
519 DecisionForestScores Scores;
520 // Exponentiating DecisionForest prediction makes the score of each tree a
521 // multiplciative boost (like NameMatch). This allows us to weigh the
522 // prediciton score and NameMatch appropriately.
523 Scores.ExcludingName = pow(Base, Evaluate(E));
524 // NeedsFixIts is not part of the DecisionForest as generating training
525 // data that needs fixits is not-feasible.
526 if (Relevance.NeedsFixIts)
527 Scores.ExcludingName *= 0.5;
528 // NameMatch should be a multiplier on total score to support rescoring.
529 Scores.Total = Relevance.NameMatch * Scores.ExcludingName;
530 return Scores;
531 }
532
533 // Produces an integer that sorts in the same order as F.
534 // That is: a < b <==> encodeFloat(a) < encodeFloat(b).
encodeFloat(float F)535 static uint32_t encodeFloat(float F) {
536 static_assert(std::numeric_limits<float>::is_iec559, "");
537 constexpr uint32_t TopBit = ~(~uint32_t{0} >> 1);
538
539 // Get the bits of the float. Endianness is the same as for integers.
540 uint32_t U = llvm::FloatToBits(F);
541 // IEEE 754 floats compare like sign-magnitude integers.
542 if (U & TopBit) // Negative float.
543 return 0 - U; // Map onto the low half of integers, order reversed.
544 return U + TopBit; // Positive floats map onto the high half of integers.
545 }
546
sortText(float Score,llvm::StringRef Name)547 std::string sortText(float Score, llvm::StringRef Name) {
548 // We convert -Score to an integer, and hex-encode for readability.
549 // Example: [0.5, "foo"] -> "41000000foo"
550 std::string S;
551 llvm::raw_string_ostream OS(S);
552 llvm::write_hex(OS, encodeFloat(-Score), llvm::HexPrintStyle::Lower,
553 /*Width=*/2 * sizeof(Score));
554 OS << Name;
555 OS.flush();
556 return S;
557 }
558
operator <<(llvm::raw_ostream & OS,const SignatureQualitySignals & S)559 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
560 const SignatureQualitySignals &S) {
561 OS << llvm::formatv("=== Signature Quality:\n");
562 OS << llvm::formatv("\tNumber of parameters: {0}\n", S.NumberOfParameters);
563 OS << llvm::formatv("\tNumber of optional parameters: {0}\n",
564 S.NumberOfOptionalParameters);
565 OS << llvm::formatv("\tKind: {0}\n", S.Kind);
566 return OS;
567 }
568
569 } // namespace clangd
570 } // namespace clang
571