clang-tools 18.0.0git
SemanticHighlighting.cpp
Go to the documentation of this file.
1//===--- SemanticHighlighting.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
10#include "Config.h"
11#include "FindTarget.h"
12#include "HeuristicResolver.h"
13#include "ParsedAST.h"
14#include "Protocol.h"
15#include "SourceCode.h"
16#include "support/Logger.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/DeclarationName.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/RecursiveASTVisitor.h"
25#include "clang/AST/Type.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/Basic/LangOptions.h"
28#include "clang/Basic/SourceLocation.h"
29#include "clang/Basic/SourceManager.h"
30#include "clang/Tooling/Syntax/Tokens.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/StringRef.h"
33#include "llvm/Support/Casting.h"
34#include "llvm/Support/Error.h"
35#include <algorithm>
36#include <optional>
37
38namespace clang {
39namespace clangd {
40namespace {
41
42/// Get the last Position on a given line.
43llvm::Expected<Position> endOfLine(llvm::StringRef Code, int Line) {
44 auto StartOfLine = positionToOffset(Code, Position{Line, 0});
45 if (!StartOfLine)
46 return StartOfLine.takeError();
47 StringRef LineText = Code.drop_front(*StartOfLine).take_until([](char C) {
48 return C == '\n';
49 });
50 return Position{Line, static_cast<int>(lspLength(LineText))};
51}
52
53/// Some names are not written in the source code and cannot be highlighted,
54/// e.g. anonymous classes. This function detects those cases.
55bool canHighlightName(DeclarationName Name) {
56 switch (Name.getNameKind()) {
57 case DeclarationName::Identifier: {
58 auto *II = Name.getAsIdentifierInfo();
59 return II && !II->getName().empty();
60 }
61 case DeclarationName::CXXConstructorName:
62 case DeclarationName::CXXDestructorName:
63 return true;
64 case DeclarationName::ObjCZeroArgSelector:
65 case DeclarationName::ObjCOneArgSelector:
66 case DeclarationName::ObjCMultiArgSelector:
67 // Multi-arg selectors need special handling, and we handle 0/1 arg
68 // selectors there too.
69 return false;
70 case DeclarationName::CXXConversionFunctionName:
71 case DeclarationName::CXXOperatorName:
72 case DeclarationName::CXXDeductionGuideName:
73 case DeclarationName::CXXLiteralOperatorName:
74 case DeclarationName::CXXUsingDirective:
75 return false;
76 }
77 llvm_unreachable("invalid name kind");
78}
79
80bool isUniqueDefinition(const NamedDecl *Decl) {
81 if (auto *Func = dyn_cast<FunctionDecl>(Decl))
82 return Func->isThisDeclarationADefinition();
83 if (auto *Klass = dyn_cast<CXXRecordDecl>(Decl))
84 return Klass->isThisDeclarationADefinition();
85 if (auto *Iface = dyn_cast<ObjCInterfaceDecl>(Decl))
86 return Iface->isThisDeclarationADefinition();
87 if (auto *Proto = dyn_cast<ObjCProtocolDecl>(Decl))
88 return Proto->isThisDeclarationADefinition();
89 if (auto *Var = dyn_cast<VarDecl>(Decl))
90 return Var->isThisDeclarationADefinition();
91 return isa<TemplateTypeParmDecl>(Decl) ||
92 isa<NonTypeTemplateParmDecl>(Decl) ||
93 isa<TemplateTemplateParmDecl>(Decl) || isa<ObjCCategoryDecl>(Decl) ||
94 isa<ObjCImplDecl>(Decl);
95}
96
97std::optional<HighlightingKind> kindForType(const Type *TP,
98 const HeuristicResolver *Resolver);
99std::optional<HighlightingKind> kindForDecl(const NamedDecl *D,
100 const HeuristicResolver *Resolver) {
101 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) {
102 if (auto *Target = USD->getTargetDecl())
103 D = Target;
104 }
105 if (auto *TD = dyn_cast<TemplateDecl>(D)) {
106 if (auto *Templated = TD->getTemplatedDecl())
107 D = Templated;
108 }
109 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
110 // We try to highlight typedefs as their underlying type.
111 if (auto K =
112 kindForType(TD->getUnderlyingType().getTypePtrOrNull(), Resolver))
113 return K;
114 // And fallback to a generic kind if this fails.
116 }
117 // We highlight class decls, constructor decls and destructor decls as
118 // `Class` type. The destructor decls are handled in `VisitTagTypeLoc` (we
119 // will visit a TypeLoc where the underlying Type is a CXXRecordDecl).
120 if (auto *RD = llvm::dyn_cast<RecordDecl>(D)) {
121 // We don't want to highlight lambdas like classes.
122 if (RD->isLambda())
123 return std::nullopt;
125 }
126 if (isa<ClassTemplateDecl, RecordDecl, CXXConstructorDecl, ObjCInterfaceDecl,
127 ObjCImplementationDecl>(D))
129 if (isa<ObjCProtocolDecl>(D))
131 if (isa<ObjCCategoryDecl, ObjCCategoryImplDecl>(D))
133 if (auto *MD = dyn_cast<CXXMethodDecl>(D))
134 return MD->isStatic() ? HighlightingKind::StaticMethod
136 if (auto *OMD = dyn_cast<ObjCMethodDecl>(D))
137 return OMD->isClassMethod() ? HighlightingKind::StaticMethod
139 if (isa<FieldDecl, ObjCPropertyDecl>(D))
141 if (isa<EnumDecl>(D))
143 if (isa<EnumConstantDecl>(D))
145 if (isa<ParmVarDecl>(D))
147 if (auto *VD = dyn_cast<VarDecl>(D)) {
148 if (isa<ImplicitParamDecl>(VD)) // e.g. ObjC Self
149 return std::nullopt;
150 return VD->isStaticDataMember()
152 : VD->isLocalVarDecl() ? HighlightingKind::LocalVariable
154 }
155 if (const auto *BD = dyn_cast<BindingDecl>(D))
156 return BD->getDeclContext()->isFunctionOrMethod()
159 if (isa<FunctionDecl>(D))
161 if (isa<NamespaceDecl>(D) || isa<NamespaceAliasDecl>(D) ||
162 isa<UsingDirectiveDecl>(D))
164 if (isa<TemplateTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
165 isa<NonTypeTemplateParmDecl>(D))
167 if (isa<ConceptDecl>(D))
169 if (isa<LabelDecl>(D))
171 if (const auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(D)) {
172 auto Targets = Resolver->resolveUsingValueDecl(UUVD);
173 if (!Targets.empty() && Targets[0] != UUVD) {
174 return kindForDecl(Targets[0], Resolver);
175 }
177 }
178 return std::nullopt;
179}
180std::optional<HighlightingKind> kindForType(const Type *TP,
181 const HeuristicResolver *Resolver) {
182 if (!TP)
183 return std::nullopt;
184 if (TP->isBuiltinType()) // Builtins are special, they do not have decls.
186 if (auto *TD = dyn_cast<TemplateTypeParmType>(TP))
187 return kindForDecl(TD->getDecl(), Resolver);
188 if (isa<ObjCObjectPointerType>(TP))
190 if (auto *TD = TP->getAsTagDecl())
191 return kindForDecl(TD, Resolver);
192 return std::nullopt;
193}
194
195// Whether T is const in a loose sense - is a variable with this type readonly?
196bool isConst(QualType T) {
197 if (T.isNull())
198 return false;
199 T = T.getNonReferenceType();
200 if (T.isConstQualified())
201 return true;
202 if (const auto *AT = T->getAsArrayTypeUnsafe())
203 return isConst(AT->getElementType());
204 if (isConst(T->getPointeeType()))
205 return true;
206 return false;
207}
208
209// Whether D is const in a loose sense (should it be highlighted as such?)
210// FIXME: This is separate from whether *a particular usage* can mutate D.
211// We may want V in V.size() to be readonly even if V is mutable.
212bool isConst(const Decl *D) {
213 if (llvm::isa<EnumConstantDecl>(D) || llvm::isa<NonTypeTemplateParmDecl>(D))
214 return true;
215 if (llvm::isa<FieldDecl>(D) || llvm::isa<VarDecl>(D) ||
216 llvm::isa<MSPropertyDecl>(D) || llvm::isa<BindingDecl>(D)) {
217 if (isConst(llvm::cast<ValueDecl>(D)->getType()))
218 return true;
219 }
220 if (const auto *OCPD = llvm::dyn_cast<ObjCPropertyDecl>(D)) {
221 if (OCPD->isReadOnly())
222 return true;
223 }
224 if (const auto *MPD = llvm::dyn_cast<MSPropertyDecl>(D)) {
225 if (!MPD->hasSetter())
226 return true;
227 }
228 if (const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(D)) {
229 if (CMD->isConst())
230 return true;
231 }
232 return false;
233}
234
235// "Static" means many things in C++, only some get the "static" modifier.
236//
237// Meanings that do:
238// - Members associated with the class rather than the instance.
239// This is what 'static' most often means across languages.
240// - static local variables
241// These are similarly "detached from their context" by the static keyword.
242// In practice, these are rarely used inside classes, reducing confusion.
243//
244// Meanings that don't:
245// - Namespace-scoped variables, which have static storage class.
246// This is implicit, so the keyword "static" isn't so strongly associated.
247// If we want a modifier for these, "global scope" is probably the concept.
248// - Namespace-scoped variables/functions explicitly marked "static".
249// There the keyword changes *linkage* , which is a totally different concept.
250// If we want to model this, "file scope" would be a nice modifier.
251//
252// This is confusing, and maybe we should use another name, but because "static"
253// is a standard LSP modifier, having one with that name has advantages.
254bool isStatic(const Decl *D) {
255 if (const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(D))
256 return CMD->isStatic();
257 if (const VarDecl *VD = llvm::dyn_cast<VarDecl>(D))
258 return VD->isStaticDataMember() || VD->isStaticLocal();
259 if (const auto *OPD = llvm::dyn_cast<ObjCPropertyDecl>(D))
260 return OPD->isClassProperty();
261 if (const auto *OMD = llvm::dyn_cast<ObjCMethodDecl>(D))
262 return OMD->isClassMethod();
263 return false;
264}
265
266bool isAbstract(const Decl *D) {
267 if (const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(D))
268 return CMD->isPure();
269 if (const auto *CRD = llvm::dyn_cast<CXXRecordDecl>(D))
270 return CRD->hasDefinition() && CRD->isAbstract();
271 return false;
272}
273
274bool isVirtual(const Decl *D) {
275 if (const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(D))
276 return CMD->isVirtual();
277 return false;
278}
279
280bool isDependent(const Decl *D) {
281 if (isa<UnresolvedUsingValueDecl>(D))
282 return true;
283 return false;
284}
285
286/// Returns true if `Decl` is considered to be from a default/system library.
287/// This currently checks the systemness of the file by include type, although
288/// different heuristics may be used in the future (e.g. sysroot paths).
289bool isDefaultLibrary(const Decl *D) {
290 SourceLocation Loc = D->getLocation();
291 if (!Loc.isValid())
292 return false;
293 return D->getASTContext().getSourceManager().isInSystemHeader(Loc);
294}
295
296bool isDefaultLibrary(const Type *T) {
297 if (!T)
298 return false;
299 const Type *Underlying = T->getPointeeOrArrayElementType();
300 if (Underlying->isBuiltinType())
301 return true;
302 if (auto *TD = dyn_cast<TemplateTypeParmType>(Underlying))
303 return isDefaultLibrary(TD->getDecl());
304 if (auto *TD = Underlying->getAsTagDecl())
305 return isDefaultLibrary(TD);
306 return false;
307}
308
309// For a macro usage `DUMP(foo)`, we want:
310// - DUMP --> "macro"
311// - foo --> "variable".
312SourceLocation getHighlightableSpellingToken(SourceLocation L,
313 const SourceManager &SM) {
314 if (L.isFileID())
315 return SM.isWrittenInMainFile(L) ? L : SourceLocation{};
316 // Tokens expanded from the macro body contribute no highlightings.
317 if (!SM.isMacroArgExpansion(L))
318 return {};
319 // Tokens expanded from macro args are potentially highlightable.
320 return getHighlightableSpellingToken(SM.getImmediateSpellingLoc(L), SM);
321}
322
323unsigned evaluateHighlightPriority(const HighlightingToken &Tok) {
324 enum HighlightPriority { Dependent = 0, Resolved = 1 };
325 return (Tok.Modifiers & (1 << uint32_t(HighlightingModifier::DependentName)))
326 ? Dependent
327 : Resolved;
328}
329
330// Sometimes we get multiple tokens at the same location:
331//
332// - findExplicitReferences() returns a heuristic result for a dependent name
333// (e.g. Method) and CollectExtraHighlighting returning a fallback dependent
334// highlighting (e.g. Unknown+Dependent).
335// - macro arguments are expanded multiple times and have different roles
336// - broken code recovery produces several AST nodes at the same location
337//
338// We should either resolve these to a single token, or drop them all.
339// Our heuristics are:
340//
341// - token kinds that come with "dependent-name" modifiers are less reliable
342// (these tend to be vague, like Type or Unknown)
343// - if we have multiple equally reliable kinds, drop token rather than guess
344// - take the union of modifiers from all tokens
345//
346// In particular, heuristically resolved dependent names get their heuristic
347// kind, plus the dependent modifier.
348std::optional<HighlightingToken> resolveConflict(const HighlightingToken &A,
349 const HighlightingToken &B) {
350 unsigned Priority1 = evaluateHighlightPriority(A);
351 unsigned Priority2 = evaluateHighlightPriority(B);
352 if (Priority1 == Priority2 && A.Kind != B.Kind)
353 return std::nullopt;
354 auto Result = Priority1 > Priority2 ? A : B;
355 Result.Modifiers = A.Modifiers | B.Modifiers;
356 return Result;
357}
358std::optional<HighlightingToken>
359resolveConflict(ArrayRef<HighlightingToken> Tokens) {
360 if (Tokens.size() == 1)
361 return Tokens[0];
362
363 assert(Tokens.size() >= 2);
364 std::optional<HighlightingToken> Winner =
365 resolveConflict(Tokens[0], Tokens[1]);
366 for (size_t I = 2; Winner && I < Tokens.size(); ++I)
367 Winner = resolveConflict(*Winner, Tokens[I]);
368 return Winner;
369}
370
371/// Filter to remove particular kinds of highlighting tokens and modifiers from
372/// the output.
373class HighlightingFilter {
374public:
375 HighlightingFilter() {
376 for (auto &Active : ActiveKindLookup)
377 Active = true;
378
379 ActiveModifiersMask = ~0;
380 }
381
382 void disableKind(HighlightingKind Kind) {
383 ActiveKindLookup[static_cast<size_t>(Kind)] = false;
384 }
385
386 void disableModifier(HighlightingModifier Modifier) {
387 ActiveModifiersMask &= ~(1 << static_cast<uint32_t>(Modifier));
388 }
389
390 bool isHighlightKindActive(HighlightingKind Kind) const {
391 return ActiveKindLookup[static_cast<size_t>(Kind)];
392 }
393
394 uint32_t maskModifiers(uint32_t Modifiers) const {
395 return Modifiers & ActiveModifiersMask;
396 }
397
398 static HighlightingFilter fromCurrentConfig() {
399 const Config &C = Config::current();
400 HighlightingFilter Filter;
401 for (const auto &Kind : C.SemanticTokens.DisabledKinds)
403 Filter.disableKind(*K);
404 for (const auto &Modifier : C.SemanticTokens.DisabledModifiers)
406 Filter.disableModifier(*M);
407
408 return Filter;
409 }
410
411private:
412 bool ActiveKindLookup[static_cast<size_t>(HighlightingKind::LastKind) + 1];
413 uint32_t ActiveModifiersMask;
414};
415
416/// Consumes source locations and maps them to text ranges for highlightings.
417class HighlightingsBuilder {
418public:
419 HighlightingsBuilder(const ParsedAST &AST, const HighlightingFilter &Filter)
420 : TB(AST.getTokens()), SourceMgr(AST.getSourceManager()),
421 LangOpts(AST.getLangOpts()), Filter(Filter) {}
422
423 HighlightingToken &addToken(SourceLocation Loc, HighlightingKind Kind) {
424 auto Range = getRangeForSourceLocation(Loc);
425 if (!Range)
426 return InvalidHighlightingToken;
427
428 return addToken(*Range, Kind);
429 }
430
431 // Most of this function works around
432 // https://github.com/clangd/clangd/issues/871.
433 void addAngleBracketTokens(SourceLocation LLoc, SourceLocation RLoc) {
434 if (!LLoc.isValid() || !RLoc.isValid())
435 return;
436
437 auto LRange = getRangeForSourceLocation(LLoc);
438 if (!LRange)
439 return;
440
441 // RLoc might be pointing at a virtual buffer when it's part of a `>>`
442 // token.
443 RLoc = SourceMgr.getFileLoc(RLoc);
444 // Make sure token is part of the main file.
445 RLoc = getHighlightableSpellingToken(RLoc, SourceMgr);
446 if (!RLoc.isValid())
447 return;
448
449 const auto *RTok = TB.spelledTokenAt(RLoc);
450 // Handle `>>`. RLoc is always pointing at the right location, just change
451 // the end to be offset by 1.
452 // We'll either point at the beginning of `>>`, hence get a proper spelled
453 // or point in the middle of `>>` hence get no spelled tok.
454 if (!RTok || RTok->kind() == tok::greatergreater) {
455 Position Begin = sourceLocToPosition(SourceMgr, RLoc);
456 Position End = sourceLocToPosition(SourceMgr, RLoc.getLocWithOffset(1));
457 addToken(*LRange, HighlightingKind::Bracket);
458 addToken({Begin, End}, HighlightingKind::Bracket);
459 return;
460 }
461
462 // Easy case, we have the `>` token directly available.
463 if (RTok->kind() == tok::greater) {
464 if (auto RRange = getRangeForSourceLocation(RLoc)) {
465 addToken(*LRange, HighlightingKind::Bracket);
466 addToken(*RRange, HighlightingKind::Bracket);
467 }
468 return;
469 }
470 }
471
472 HighlightingToken &addToken(Range R, HighlightingKind Kind) {
473 if (!Filter.isHighlightKindActive(Kind))
474 return InvalidHighlightingToken;
475
476 HighlightingToken HT;
477 HT.R = std::move(R);
478 HT.Kind = Kind;
479 Tokens.push_back(std::move(HT));
480 return Tokens.back();
481 }
482
483 void addExtraModifier(SourceLocation Loc, HighlightingModifier Modifier) {
484 if (auto Range = getRangeForSourceLocation(Loc))
485 ExtraModifiers[*Range].push_back(Modifier);
486 }
487
488 std::vector<HighlightingToken> collect(ParsedAST &AST) && {
489 // Initializer lists can give duplicates of tokens, therefore all tokens
490 // must be deduplicated.
491 llvm::sort(Tokens);
492 auto Last = std::unique(Tokens.begin(), Tokens.end());
493 Tokens.erase(Last, Tokens.end());
494
495 // Macros can give tokens that have the same source range but conflicting
496 // kinds. In this case all tokens sharing this source range should be
497 // removed.
498 std::vector<HighlightingToken> NonConflicting;
499 NonConflicting.reserve(Tokens.size());
500 for (ArrayRef<HighlightingToken> TokRef = Tokens; !TokRef.empty();) {
501 ArrayRef<HighlightingToken> Conflicting =
502 TokRef.take_while([&](const HighlightingToken &T) {
503 // TokRef is guaranteed at least one element here because otherwise
504 // this predicate would never fire.
505 return T.R == TokRef.front().R;
506 });
507 if (auto Resolved = resolveConflict(Conflicting)) {
508 // Apply extra collected highlighting modifiers
509 auto Modifiers = ExtraModifiers.find(Resolved->R);
510 if (Modifiers != ExtraModifiers.end()) {
511 for (HighlightingModifier Mod : Modifiers->second) {
512 Resolved->addModifier(Mod);
513 }
514 }
515
516 Resolved->Modifiers = Filter.maskModifiers(Resolved->Modifiers);
517 NonConflicting.push_back(*Resolved);
518 }
519 // TokRef[Conflicting.size()] is the next token with a different range (or
520 // the end of the Tokens).
521 TokRef = TokRef.drop_front(Conflicting.size());
522 }
523
524 if (!Filter.isHighlightKindActive(HighlightingKind::InactiveCode))
525 return NonConflicting;
526
527 const auto &SM = AST.getSourceManager();
528 StringRef MainCode = SM.getBufferOrFake(SM.getMainFileID()).getBuffer();
529
530 // Merge token stream with "inactive line" markers.
531 std::vector<HighlightingToken> WithInactiveLines;
532 auto SortedInactiveRegions = getInactiveRegions(AST);
533 llvm::sort(SortedInactiveRegions);
534 auto It = NonConflicting.begin();
535 for (const Range &R : SortedInactiveRegions) {
536 // Create one token for each line in the inactive range, so it works
537 // with line-based diffing.
538 assert(R.start.line <= R.end.line);
539 for (int Line = R.start.line; Line <= R.end.line; ++Line) {
540 // Copy tokens before the inactive line
541 for (; It != NonConflicting.end() && It->R.start.line < Line; ++It)
542 WithInactiveLines.push_back(std::move(*It));
543 // Add a token for the inactive line itself.
544 auto EndOfLine = endOfLine(MainCode, Line);
545 if (EndOfLine) {
546 HighlightingToken HT;
547 WithInactiveLines.emplace_back();
548 WithInactiveLines.back().Kind = HighlightingKind::InactiveCode;
549 WithInactiveLines.back().R.start.line = Line;
550 WithInactiveLines.back().R.end = *EndOfLine;
551 } else {
552 elog("Failed to determine end of line: {0}", EndOfLine.takeError());
553 }
554
555 // Skip any other tokens on the inactive line. e.g.
556 // `#ifndef Foo` is considered as part of an inactive region when Foo is
557 // defined, and there is a Foo macro token.
558 // FIXME: we should reduce the scope of the inactive region to not
559 // include the directive itself.
560 while (It != NonConflicting.end() && It->R.start.line == Line)
561 ++It;
562 }
563 }
564 // Copy tokens after the last inactive line
565 for (; It != NonConflicting.end(); ++It)
566 WithInactiveLines.push_back(std::move(*It));
567 return WithInactiveLines;
568 }
569
570 const HeuristicResolver *getResolver() const { return Resolver; }
571
572private:
573 std::optional<Range> getRangeForSourceLocation(SourceLocation Loc) {
574 Loc = getHighlightableSpellingToken(Loc, SourceMgr);
575 if (Loc.isInvalid())
576 return std::nullopt;
577 // We might have offsets in the main file that don't correspond to any
578 // spelled tokens.
579 const auto *Tok = TB.spelledTokenAt(Loc);
580 if (!Tok)
581 return std::nullopt;
582 return halfOpenToRange(SourceMgr,
583 Tok->range(SourceMgr).toCharRange(SourceMgr));
584 }
585
586 const syntax::TokenBuffer &TB;
587 const SourceManager &SourceMgr;
588 const LangOptions &LangOpts;
589 HighlightingFilter Filter;
590 std::vector<HighlightingToken> Tokens;
591 std::map<Range, llvm::SmallVector<HighlightingModifier, 1>> ExtraModifiers;
592 const HeuristicResolver *Resolver = nullptr;
593 // returned from addToken(InvalidLoc)
594 HighlightingToken InvalidHighlightingToken;
595};
596
597std::optional<HighlightingModifier> scopeModifier(const NamedDecl *D) {
598 const DeclContext *DC = D->getDeclContext();
599 // Injected "Foo" within the class "Foo" has file scope, not class scope.
600 if (auto *R = dyn_cast_or_null<RecordDecl>(D))
601 if (R->isInjectedClassName())
602 DC = DC->getParent();
603 // Lambda captures are considered function scope, not class scope.
604 if (llvm::isa<FieldDecl>(D))
605 if (const auto *RD = llvm::dyn_cast<RecordDecl>(DC))
606 if (RD->isLambda())
608 // Walk up the DeclContext hierarchy until we find something interesting.
609 for (; !DC->isFileContext(); DC = DC->getParent()) {
610 if (DC->isFunctionOrMethod())
612 if (DC->isRecord())
614 }
615 // Some template parameters (e.g. those for variable templates) don't have
616 // meaningful DeclContexts. That doesn't mean they're global!
617 if (DC->isTranslationUnit() && D->isTemplateParameter())
618 return std::nullopt;
619 // ExternalLinkage threshold could be tweaked, e.g. module-visible as global.
620 if (D->getLinkageInternal() < ExternalLinkage)
623}
624
625std::optional<HighlightingModifier> scopeModifier(const Type *T) {
626 if (!T)
627 return std::nullopt;
628 if (T->isBuiltinType())
630 if (auto *TD = dyn_cast<TemplateTypeParmType>(T))
631 return scopeModifier(TD->getDecl());
632 if (auto *TD = T->getAsTagDecl())
633 return scopeModifier(TD);
634 return std::nullopt;
635}
636
637/// Produces highlightings, which are not captured by findExplicitReferences,
638/// e.g. highlights dependent names and 'auto' as the underlying type.
639class CollectExtraHighlightings
640 : public RecursiveASTVisitor<CollectExtraHighlightings> {
642
643public:
644 CollectExtraHighlightings(HighlightingsBuilder &H) : H(H) {}
645
646 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
647 highlightMutableReferenceArguments(E->getConstructor(),
648 {E->getArgs(), E->getNumArgs()});
649
650 return true;
651 }
652
653 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
654 if (Init->isMemberInitializer())
655 if (auto *Member = Init->getMember())
656 highlightMutableReferenceArgument(Member->getType(), Init->getInit());
657 return Base::TraverseConstructorInitializer(Init);
658 }
659
660 bool TraverseTypeConstraint(const TypeConstraint *C) {
661 if (auto *Args = C->getTemplateArgsAsWritten())
662 H.addAngleBracketTokens(Args->getLAngleLoc(), Args->getRAngleLoc());
663 return Base::TraverseTypeConstraint(C);
664 }
665
666 bool VisitPredefinedExpr(PredefinedExpr *E) {
667 H.addToken(E->getLocation(), HighlightingKind::LocalVariable)
668 .addModifier(HighlightingModifier::Static)
671 return true;
672 }
673
674 bool VisitConceptSpecializationExpr(ConceptSpecializationExpr *E) {
675 if (auto *Args = E->getTemplateArgsAsWritten())
676 H.addAngleBracketTokens(Args->getLAngleLoc(), Args->getRAngleLoc());
677 return true;
678 }
679
680 bool VisitTemplateDecl(TemplateDecl *D) {
681 if (auto *TPL = D->getTemplateParameters())
682 H.addAngleBracketTokens(TPL->getLAngleLoc(), TPL->getRAngleLoc());
683 return true;
684 }
685
686 bool VisitTagDecl(TagDecl *D) {
687 for (unsigned i = 0; i < D->getNumTemplateParameterLists(); ++i) {
688 if (auto *TPL = D->getTemplateParameterList(i))
689 H.addAngleBracketTokens(TPL->getLAngleLoc(), TPL->getRAngleLoc());
690 }
691 return true;
692 }
693
694 bool VisitClassTemplatePartialSpecializationDecl(
695 ClassTemplatePartialSpecializationDecl *D) {
696 if (auto *TPL = D->getTemplateParameters())
697 H.addAngleBracketTokens(TPL->getLAngleLoc(), TPL->getRAngleLoc());
698 if (auto *Args = D->getTemplateArgsAsWritten())
699 H.addAngleBracketTokens(Args->getLAngleLoc(), Args->getRAngleLoc());
700 return true;
701 }
702
703 bool VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D) {
704 if (auto *Args = D->getTemplateArgsInfo())
705 H.addAngleBracketTokens(Args->getLAngleLoc(), Args->getRAngleLoc());
706 return true;
707 }
708
709 bool VisitVarTemplatePartialSpecializationDecl(
710 VarTemplatePartialSpecializationDecl *D) {
711 if (auto *TPL = D->getTemplateParameters())
712 H.addAngleBracketTokens(TPL->getLAngleLoc(), TPL->getRAngleLoc());
713 if (auto *Args = D->getTemplateArgsAsWritten())
714 H.addAngleBracketTokens(Args->getLAngleLoc(), Args->getRAngleLoc());
715 return true;
716 }
717
718 bool VisitClassScopeFunctionSpecializationDecl(
719 ClassScopeFunctionSpecializationDecl *D) {
720 if (auto *Args = D->getTemplateArgsAsWritten())
721 H.addAngleBracketTokens(Args->getLAngleLoc(), Args->getRAngleLoc());
722 return true;
723 }
724
725 bool VisitDeclRefExpr(DeclRefExpr *E) {
726 H.addAngleBracketTokens(E->getLAngleLoc(), E->getRAngleLoc());
727 return true;
728 }
729 bool VisitMemberExpr(MemberExpr *E) {
730 H.addAngleBracketTokens(E->getLAngleLoc(), E->getRAngleLoc());
731 return true;
732 }
733
734 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc L) {
735 H.addAngleBracketTokens(L.getLAngleLoc(), L.getRAngleLoc());
736 return true;
737 }
738
739 bool VisitFunctionDecl(FunctionDecl *D) {
740 if (D->isOverloadedOperator()) {
741 const auto AddOpDeclToken = [&](SourceLocation Loc) {
742 auto &Token = H.addToken(Loc, HighlightingKind::Operator)
744 if (D->isThisDeclarationADefinition())
745 Token.addModifier(HighlightingModifier::Definition);
746 };
747 const auto Range = D->getNameInfo().getCXXOperatorNameRange();
748 AddOpDeclToken(Range.getBegin());
749 const auto Kind = D->getOverloadedOperator();
750 if (Kind == OO_Call || Kind == OO_Subscript)
751 AddOpDeclToken(Range.getEnd());
752 }
753 if (auto *Args = D->getTemplateSpecializationArgsAsWritten())
754 H.addAngleBracketTokens(Args->getLAngleLoc(), Args->getRAngleLoc());
755 if (auto *I = D->getDependentSpecializationInfo())
756 H.addAngleBracketTokens(I->getLAngleLoc(), I->getRAngleLoc());
757 return true;
758 }
759
760 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
761 const auto AddOpToken = [&](SourceLocation Loc) {
764 };
765 AddOpToken(E->getOperatorLoc());
766 const auto Kind = E->getOperator();
767 if (Kind == OO_Call || Kind == OO_Subscript) {
768 if (auto *Callee = E->getCallee())
769 AddOpToken(Callee->getBeginLoc());
770 }
771 return true;
772 }
773
774 bool VisitUnaryOperator(UnaryOperator *Op) {
775 auto &Token = H.addToken(Op->getOperatorLoc(), HighlightingKind::Operator);
776 if (Op->getSubExpr()->isTypeDependent())
777 Token.addModifier(HighlightingModifier::UserDefined);
778 return true;
779 }
780
781 bool VisitBinaryOperator(BinaryOperator *Op) {
782 auto &Token = H.addToken(Op->getOperatorLoc(), HighlightingKind::Operator);
783 if (Op->getLHS()->isTypeDependent() || Op->getRHS()->isTypeDependent())
784 Token.addModifier(HighlightingModifier::UserDefined);
785 return true;
786 }
787
788 bool VisitConditionalOperator(ConditionalOperator *Op) {
789 H.addToken(Op->getQuestionLoc(), HighlightingKind::Operator);
790 H.addToken(Op->getColonLoc(), HighlightingKind::Operator);
791 return true;
792 }
793
794 bool VisitCXXNewExpr(CXXNewExpr *E) {
795 auto &Token = H.addToken(E->getBeginLoc(), HighlightingKind::Operator);
796 if (isa_and_present<CXXMethodDecl>(E->getOperatorNew()))
797 Token.addModifier(HighlightingModifier::UserDefined);
798 return true;
799 }
800
801 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
802 auto &Token = H.addToken(E->getBeginLoc(), HighlightingKind::Operator);
803 if (isa_and_present<CXXMethodDecl>(E->getOperatorDelete()))
804 Token.addModifier(HighlightingModifier::UserDefined);
805 return true;
806 }
807
808 bool VisitCXXNamedCastExpr(CXXNamedCastExpr *E) {
809 const auto &B = E->getAngleBrackets();
810 H.addAngleBracketTokens(B.getBegin(), B.getEnd());
811 return true;
812 }
813
814 bool VisitCallExpr(CallExpr *E) {
815 // Highlighting parameters passed by non-const reference does not really
816 // make sense for literals...
817 if (isa<UserDefinedLiteral>(E))
818 return true;
819
820 // FIXME: consider highlighting parameters of some other overloaded
821 // operators as well
822 llvm::ArrayRef<const Expr *> Args = {E->getArgs(), E->getNumArgs()};
823 if (auto *CallOp = dyn_cast<CXXOperatorCallExpr>(E)) {
824 switch (CallOp->getOperator()) {
825 case OO_Call:
826 case OO_Subscript:
827 Args = Args.drop_front(); // Drop object parameter
828 break;
829 default:
830 return true;
831 }
832 }
833
834 highlightMutableReferenceArguments(
835 dyn_cast_or_null<FunctionDecl>(E->getCalleeDecl()), Args);
836
837 return true;
838 }
839
840 void highlightMutableReferenceArgument(QualType T, const Expr *Arg) {
841 if (!Arg)
842 return;
843
844 // Is this parameter passed by non-const pointer or reference?
845 // FIXME The condition T->idDependentType() could be relaxed a bit,
846 // e.g. std::vector<T>& is dependent but we would want to highlight it
847 bool IsRef = T->isLValueReferenceType();
848 bool IsPtr = T->isPointerType();
849 if ((!IsRef && !IsPtr) || T->getPointeeType().isConstQualified() ||
850 T->isDependentType()) {
851 return;
852 }
853
854 std::optional<SourceLocation> Location;
855
856 // FIXME Add "unwrapping" for ArraySubscriptExpr,
857 // e.g. highlight `a` in `a[i]`
858 // FIXME Handle dependent expression types
859 if (auto *IC = dyn_cast<ImplicitCastExpr>(Arg))
860 Arg = IC->getSubExprAsWritten();
861 if (auto *UO = dyn_cast<UnaryOperator>(Arg)) {
862 if (UO->getOpcode() == UO_AddrOf)
863 Arg = UO->getSubExpr();
864 }
865 if (auto *DR = dyn_cast<DeclRefExpr>(Arg))
866 Location = DR->getLocation();
867 else if (auto *M = dyn_cast<MemberExpr>(Arg))
868 Location = M->getMemberLoc();
869
870 if (Location)
871 H.addExtraModifier(*Location,
874 }
875
876 void
877 highlightMutableReferenceArguments(const FunctionDecl *FD,
878 llvm::ArrayRef<const Expr *const> Args) {
879 if (!FD)
880 return;
881
882 if (auto *ProtoType = FD->getType()->getAs<FunctionProtoType>()) {
883 // Iterate over the types of the function parameters.
884 // If any of them are non-const reference paramteres, add it as a
885 // highlighting modifier to the corresponding expression
886 for (size_t I = 0;
887 I < std::min(size_t(ProtoType->getNumParams()), Args.size()); ++I) {
888 highlightMutableReferenceArgument(ProtoType->getParamType(I), Args[I]);
889 }
890 }
891 }
892
893 bool VisitDecltypeTypeLoc(DecltypeTypeLoc L) {
894 if (auto K = kindForType(L.getTypePtr(), H.getResolver())) {
895 auto &Tok = H.addToken(L.getBeginLoc(), *K)
896 .addModifier(HighlightingModifier::Deduced);
897 if (auto Mod = scopeModifier(L.getTypePtr()))
898 Tok.addModifier(*Mod);
899 if (isDefaultLibrary(L.getTypePtr()))
901 }
902 return true;
903 }
904
905 bool VisitCXXDestructorDecl(CXXDestructorDecl *D) {
906 if (auto *TI = D->getNameInfo().getNamedTypeInfo()) {
907 SourceLocation Loc = TI->getTypeLoc().getBeginLoc();
909 H.addExtraModifier(Loc, HighlightingModifier::Declaration);
910 if (D->isThisDeclarationADefinition())
911 H.addExtraModifier(Loc, HighlightingModifier::Definition);
912 }
913 return true;
914 }
915
916 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *CE) {
917 // getMethodDecl can return nullptr with member pointers, e.g.
918 // `(foo.*pointer_to_member_fun)(arg);`
919 if (auto *D = CE->getMethodDecl()) {
920 if (isa<CXXDestructorDecl>(D)) {
921 if (auto *ME = dyn_cast<MemberExpr>(CE->getCallee())) {
922 if (auto *TI = ME->getMemberNameInfo().getNamedTypeInfo()) {
923 H.addExtraModifier(TI->getTypeLoc().getBeginLoc(),
925 }
926 }
927 } else if (D->isOverloadedOperator()) {
928 if (auto *ME = dyn_cast<MemberExpr>(CE->getCallee()))
929 H.addToken(
930 ME->getMemberNameInfo().getCXXOperatorNameRange().getBegin(),
933 }
934 }
935 return true;
936 }
937
938 bool VisitDeclaratorDecl(DeclaratorDecl *D) {
939 for (unsigned i = 0; i < D->getNumTemplateParameterLists(); ++i) {
940 if (auto *TPL = D->getTemplateParameterList(i))
941 H.addAngleBracketTokens(TPL->getLAngleLoc(), TPL->getRAngleLoc());
942 }
943 auto *AT = D->getType()->getContainedAutoType();
944 if (!AT)
945 return true;
946 auto K =
947 kindForType(AT->getDeducedType().getTypePtrOrNull(), H.getResolver());
948 if (!K)
949 return true;
950 auto *TSI = D->getTypeSourceInfo();
951 if (!TSI)
952 return true;
953 SourceLocation StartLoc =
954 TSI->getTypeLoc().getContainedAutoTypeLoc().getNameLoc();
955 // The AutoType may not have a corresponding token, e.g. in the case of
956 // init-captures. In this case, StartLoc overlaps with the location
957 // of the decl itself, and producing a token for the type here would result
958 // in both it and the token for the decl being dropped due to conflict.
959 if (StartLoc == D->getLocation())
960 return true;
961
962 auto &Tok =
963 H.addToken(StartLoc, *K).addModifier(HighlightingModifier::Deduced);
964 const Type *Deduced = AT->getDeducedType().getTypePtrOrNull();
965 if (auto Mod = scopeModifier(Deduced))
966 Tok.addModifier(*Mod);
967 if (isDefaultLibrary(Deduced))
969 return true;
970 }
971
972 // We handle objective-C selectors specially, because one reference can
973 // cover several non-contiguous tokens.
974 void highlightObjCSelector(const ArrayRef<SourceLocation> &Locs, bool Decl,
975 bool Def, bool Class, bool DefaultLibrary) {
978 for (SourceLocation Part : Locs) {
979 auto &Tok =
980 H.addToken(Part, Kind).addModifier(HighlightingModifier::ClassScope);
981 if (Decl)
982 Tok.addModifier(HighlightingModifier::Declaration);
983 if (Def)
984 Tok.addModifier(HighlightingModifier::Definition);
985 if (Class)
986 Tok.addModifier(HighlightingModifier::Static);
987 if (DefaultLibrary)
989 }
990 }
991
992 bool VisitObjCMethodDecl(ObjCMethodDecl *OMD) {
993 llvm::SmallVector<SourceLocation> Locs;
994 OMD->getSelectorLocs(Locs);
995 highlightObjCSelector(Locs, /*Decl=*/true,
996 OMD->isThisDeclarationADefinition(),
997 OMD->isClassMethod(), isDefaultLibrary(OMD));
998 return true;
999 }
1000
1001 bool VisitObjCMessageExpr(ObjCMessageExpr *OME) {
1002 llvm::SmallVector<SourceLocation> Locs;
1003 OME->getSelectorLocs(Locs);
1004 bool DefaultLibrary = false;
1005 if (ObjCMethodDecl *OMD = OME->getMethodDecl())
1006 DefaultLibrary = isDefaultLibrary(OMD);
1007 highlightObjCSelector(Locs, /*Decl=*/false, /*Def=*/false,
1008 OME->isClassMessage(), DefaultLibrary);
1009 return true;
1010 }
1011
1012 // Objective-C allows you to use property syntax `self.prop` as sugar for
1013 // `[self prop]` and `[self setProp:]` when there's no explicit `@property`
1014 // for `prop` as well as for class properties. We treat this like a property
1015 // even though semantically it's equivalent to a method expression.
1016 void highlightObjCImplicitPropertyRef(const ObjCMethodDecl *OMD,
1017 SourceLocation Loc) {
1018 auto &Tok = H.addToken(Loc, HighlightingKind::Field)
1020 if (OMD->isClassMethod())
1021 Tok.addModifier(HighlightingModifier::Static);
1022 if (isDefaultLibrary(OMD))
1023 Tok.addModifier(HighlightingModifier::DefaultLibrary);
1024 }
1025
1026 bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *OPRE) {
1027 // We need to handle implicit properties here since they will appear to
1028 // reference `ObjCMethodDecl` via an implicit `ObjCMessageExpr`, so normal
1029 // highlighting will not work.
1030 if (!OPRE->isImplicitProperty())
1031 return true;
1032 // A single property expr can reference both a getter and setter, but we can
1033 // only provide a single semantic token, so prefer the getter. In most cases
1034 // the end result should be the same, although it's technically possible
1035 // that the user defines a setter for a system SDK.
1036 if (OPRE->isMessagingGetter()) {
1037 highlightObjCImplicitPropertyRef(OPRE->getImplicitPropertyGetter(),
1038 OPRE->getLocation());
1039 return true;
1040 }
1041 if (OPRE->isMessagingSetter()) {
1042 highlightObjCImplicitPropertyRef(OPRE->getImplicitPropertySetter(),
1043 OPRE->getLocation());
1044 }
1045 return true;
1046 }
1047
1048 bool VisitOverloadExpr(OverloadExpr *E) {
1049 H.addAngleBracketTokens(E->getLAngleLoc(), E->getRAngleLoc());
1050 if (!E->decls().empty())
1051 return true; // handled by findExplicitReferences.
1052 auto &Tok = H.addToken(E->getNameLoc(), HighlightingKind::Unknown)
1054 if (llvm::isa<UnresolvedMemberExpr>(E))
1055 Tok.addModifier(HighlightingModifier::ClassScope);
1056 // other case is UnresolvedLookupExpr, scope is unknown.
1057 return true;
1058 }
1059
1060 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1061 H.addToken(E->getMemberNameInfo().getLoc(), HighlightingKind::Unknown)
1064 H.addAngleBracketTokens(E->getLAngleLoc(), E->getRAngleLoc());
1065 return true;
1066 }
1067
1068 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1069 H.addToken(E->getNameInfo().getLoc(), HighlightingKind::Unknown)
1072 H.addAngleBracketTokens(E->getLAngleLoc(), E->getRAngleLoc());
1073 return true;
1074 }
1075
1076 bool VisitAttr(Attr *A) {
1077 switch (A->getKind()) {
1078 case attr::Override:
1079 case attr::Final:
1080 H.addToken(A->getLocation(), HighlightingKind::Modifier);
1081 break;
1082 default:
1083 break;
1084 }
1085 return true;
1086 }
1087
1088 bool VisitDependentNameTypeLoc(DependentNameTypeLoc L) {
1089 H.addToken(L.getNameLoc(), HighlightingKind::Type)
1092 return true;
1093 }
1094
1095 bool VisitDependentTemplateSpecializationTypeLoc(
1096 DependentTemplateSpecializationTypeLoc L) {
1097 H.addToken(L.getTemplateNameLoc(), HighlightingKind::Type)
1100 H.addAngleBracketTokens(L.getLAngleLoc(), L.getRAngleLoc());
1101 return true;
1102 }
1103
1104 bool TraverseTemplateArgumentLoc(TemplateArgumentLoc L) {
1105 // Handle template template arguments only (other arguments are handled by
1106 // their Expr, TypeLoc etc values).
1107 if (L.getArgument().getKind() != TemplateArgument::Template &&
1108 L.getArgument().getKind() != TemplateArgument::TemplateExpansion)
1109 return RecursiveASTVisitor::TraverseTemplateArgumentLoc(L);
1110
1111 TemplateName N = L.getArgument().getAsTemplateOrTemplatePattern();
1112 switch (N.getKind()) {
1113 case TemplateName::OverloadedTemplate:
1114 // Template template params must always be class templates.
1115 // Don't bother to try to work out the scope here.
1116 H.addToken(L.getTemplateNameLoc(), HighlightingKind::Class);
1117 break;
1118 case TemplateName::DependentTemplate:
1119 case TemplateName::AssumedTemplate:
1120 H.addToken(L.getTemplateNameLoc(), HighlightingKind::Class)
1122 break;
1123 case TemplateName::Template:
1124 case TemplateName::QualifiedTemplate:
1125 case TemplateName::SubstTemplateTemplateParm:
1126 case TemplateName::SubstTemplateTemplateParmPack:
1127 case TemplateName::UsingTemplate:
1128 // Names that could be resolved to a TemplateDecl are handled elsewhere.
1129 break;
1130 }
1131 return RecursiveASTVisitor::TraverseTemplateArgumentLoc(L);
1132 }
1133
1134 // findExplicitReferences will walk nested-name-specifiers and
1135 // find anything that can be resolved to a Decl. However, non-leaf
1136 // components of nested-name-specifiers which are dependent names
1137 // (kind "Identifier") cannot be resolved to a decl, so we visit
1138 // them here.
1139 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc Q) {
1140 if (NestedNameSpecifier *NNS = Q.getNestedNameSpecifier()) {
1141 if (NNS->getKind() == NestedNameSpecifier::Identifier)
1142 H.addToken(Q.getLocalBeginLoc(), HighlightingKind::Type)
1145 }
1146 return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(Q);
1147 }
1148
1149private:
1150 HighlightingsBuilder &H;
1151};
1152} // namespace
1153
1154std::vector<HighlightingToken>
1155getSemanticHighlightings(ParsedAST &AST, bool IncludeInactiveRegionTokens) {
1156 auto &C = AST.getASTContext();
1157 HighlightingFilter Filter = HighlightingFilter::fromCurrentConfig();
1158 if (!IncludeInactiveRegionTokens)
1159 Filter.disableKind(HighlightingKind::InactiveCode);
1160 // Add highlightings for AST nodes.
1161 HighlightingsBuilder Builder(AST, Filter);
1162 // Highlight 'decltype' and 'auto' as their underlying types.
1163 CollectExtraHighlightings(Builder).TraverseAST(C);
1164 // Highlight all decls and references coming from the AST.
1166 C,
1167 [&](ReferenceLoc R) {
1168 for (const NamedDecl *Decl : R.Targets) {
1169 if (!canHighlightName(Decl->getDeclName()))
1170 continue;
1171 auto Kind = kindForDecl(Decl, AST.getHeuristicResolver());
1172 if (!Kind)
1173 continue;
1174 auto &Tok = Builder.addToken(R.NameLoc, *Kind);
1175
1176 // The attribute tests don't want to look at the template.
1177 if (auto *TD = dyn_cast<TemplateDecl>(Decl)) {
1178 if (auto *Templated = TD->getTemplatedDecl())
1179 Decl = Templated;
1180 }
1181 if (auto Mod = scopeModifier(Decl))
1182 Tok.addModifier(*Mod);
1183 if (isConst(Decl))
1184 Tok.addModifier(HighlightingModifier::Readonly);
1185 if (isStatic(Decl))
1186 Tok.addModifier(HighlightingModifier::Static);
1187 if (isAbstract(Decl))
1188 Tok.addModifier(HighlightingModifier::Abstract);
1189 if (isVirtual(Decl))
1190 Tok.addModifier(HighlightingModifier::Virtual);
1191 if (isDependent(Decl))
1192 Tok.addModifier(HighlightingModifier::DependentName);
1193 if (isDefaultLibrary(Decl))
1194 Tok.addModifier(HighlightingModifier::DefaultLibrary);
1195 if (Decl->isDeprecated())
1196 Tok.addModifier(HighlightingModifier::Deprecated);
1197 if (isa<CXXConstructorDecl>(Decl))
1199 if (R.IsDecl) {
1200 // Do not treat an UnresolvedUsingValueDecl as a declaration.
1201 // It's more common to think of it as a reference to the
1202 // underlying declaration.
1203 if (!isa<UnresolvedUsingValueDecl>(Decl))
1204 Tok.addModifier(HighlightingModifier::Declaration);
1205 if (isUniqueDefinition(Decl))
1206 Tok.addModifier(HighlightingModifier::Definition);
1207 }
1208 }
1209 },
1210 AST.getHeuristicResolver());
1211 // Add highlightings for macro references.
1212 auto AddMacro = [&](const MacroOccurrence &M) {
1213 auto &T = Builder.addToken(M.toRange(C.getSourceManager()),
1215 T.addModifier(HighlightingModifier::GlobalScope);
1216 if (M.IsDefinition)
1217 T.addModifier(HighlightingModifier::Declaration);
1218 };
1219 for (const auto &SIDToRefs : AST.getMacros().MacroRefs)
1220 for (const auto &M : SIDToRefs.second)
1221 AddMacro(M);
1222 for (const auto &M : AST.getMacros().UnknownMacros)
1223 AddMacro(M);
1224
1225 return std::move(Builder).collect(AST);
1226}
1227
1228llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, HighlightingKind K) {
1229 switch (K) {
1230 case HighlightingKind::Variable:
1231 return OS << "Variable";
1232 case HighlightingKind::LocalVariable:
1233 return OS << "LocalVariable";
1234 case HighlightingKind::Parameter:
1235 return OS << "Parameter";
1236 case HighlightingKind::Function:
1237 return OS << "Function";
1238 case HighlightingKind::Method:
1239 return OS << "Method";
1240 case HighlightingKind::StaticMethod:
1241 return OS << "StaticMethod";
1242 case HighlightingKind::Field:
1243 return OS << "Field";
1244 case HighlightingKind::StaticField:
1245 return OS << "StaticField";
1246 case HighlightingKind::Class:
1247 return OS << "Class";
1248 case HighlightingKind::Interface:
1249 return OS << "Interface";
1250 case HighlightingKind::Enum:
1251 return OS << "Enum";
1252 case HighlightingKind::EnumConstant:
1253 return OS << "EnumConstant";
1254 case HighlightingKind::Typedef:
1255 return OS << "Typedef";
1256 case HighlightingKind::Type:
1257 return OS << "Type";
1258 case HighlightingKind::Unknown:
1259 return OS << "Unknown";
1260 case HighlightingKind::Namespace:
1261 return OS << "Namespace";
1262 case HighlightingKind::TemplateParameter:
1263 return OS << "TemplateParameter";
1264 case HighlightingKind::Concept:
1265 return OS << "Concept";
1266 case HighlightingKind::Primitive:
1267 return OS << "Primitive";
1268 case HighlightingKind::Macro:
1269 return OS << "Macro";
1270 case HighlightingKind::Modifier:
1271 return OS << "Modifier";
1272 case HighlightingKind::Operator:
1273 return OS << "Operator";
1274 case HighlightingKind::Bracket:
1275 return OS << "Bracket";
1276 case HighlightingKind::Label:
1277 return OS << "Label";
1278 case HighlightingKind::InactiveCode:
1279 return OS << "InactiveCode";
1280 }
1281 llvm_unreachable("invalid HighlightingKind");
1282}
1283std::optional<HighlightingKind>
1285 static llvm::StringMap<HighlightingKind> Lookup = {
1286 {"Variable", HighlightingKind::Variable},
1287 {"LocalVariable", HighlightingKind::LocalVariable},
1288 {"Parameter", HighlightingKind::Parameter},
1289 {"Function", HighlightingKind::Function},
1290 {"Method", HighlightingKind::Method},
1291 {"StaticMethod", HighlightingKind::StaticMethod},
1292 {"Field", HighlightingKind::Field},
1293 {"StaticField", HighlightingKind::StaticField},
1294 {"Class", HighlightingKind::Class},
1295 {"Interface", HighlightingKind::Interface},
1296 {"Enum", HighlightingKind::Enum},
1297 {"EnumConstant", HighlightingKind::EnumConstant},
1298 {"Typedef", HighlightingKind::Typedef},
1299 {"Type", HighlightingKind::Type},
1300 {"Unknown", HighlightingKind::Unknown},
1301 {"Namespace", HighlightingKind::Namespace},
1302 {"TemplateParameter", HighlightingKind::TemplateParameter},
1303 {"Concept", HighlightingKind::Concept},
1304 {"Primitive", HighlightingKind::Primitive},
1305 {"Macro", HighlightingKind::Macro},
1306 {"Modifier", HighlightingKind::Modifier},
1307 {"Operator", HighlightingKind::Operator},
1308 {"Bracket", HighlightingKind::Bracket},
1309 {"InactiveCode", HighlightingKind::InactiveCode},
1310 };
1311
1312 auto It = Lookup.find(Name);
1313 return It != Lookup.end() ? std::make_optional(It->getValue()) : std::nullopt;
1314}
1315llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, HighlightingModifier K) {
1316 switch (K) {
1317 case HighlightingModifier::Declaration:
1318 return OS << "decl"; // abbreviation for common case
1319 case HighlightingModifier::Definition:
1320 return OS << "def"; // abbrevation for common case
1321 case HighlightingModifier::ConstructorOrDestructor:
1322 return OS << "constrDestr";
1323 default:
1324 return OS << toSemanticTokenModifier(K);
1325 }
1326}
1327std::optional<HighlightingModifier>
1329 static llvm::StringMap<HighlightingModifier> Lookup = {
1330 {"Declaration", HighlightingModifier::Declaration},
1331 {"Definition", HighlightingModifier::Definition},
1332 {"Deprecated", HighlightingModifier::Deprecated},
1333 {"Deduced", HighlightingModifier::Deduced},
1334 {"Readonly", HighlightingModifier::Readonly},
1335 {"Static", HighlightingModifier::Static},
1336 {"Abstract", HighlightingModifier::Abstract},
1337 {"Virtual", HighlightingModifier::Virtual},
1338 {"DependentName", HighlightingModifier::DependentName},
1339 {"DefaultLibrary", HighlightingModifier::DefaultLibrary},
1340 {"UsedAsMutableReference", HighlightingModifier::UsedAsMutableReference},
1341 {"UsedAsMutablePointer", HighlightingModifier::UsedAsMutablePointer},
1342 {"ConstructorOrDestructor",
1343 HighlightingModifier::ConstructorOrDestructor},
1344 {"UserDefined", HighlightingModifier::UserDefined},
1345 {"FunctionScope", HighlightingModifier::FunctionScope},
1346 {"ClassScope", HighlightingModifier::ClassScope},
1347 {"FileScope", HighlightingModifier::FileScope},
1348 {"GlobalScope", HighlightingModifier::GlobalScope},
1349 };
1350
1351 auto It = Lookup.find(Name);
1352 return It != Lookup.end() ? std::make_optional(It->getValue()) : std::nullopt;
1353}
1354
1356 return std::tie(L.R, L.Kind, L.Modifiers) ==
1357 std::tie(R.R, R.Kind, R.Modifiers);
1358}
1360 return std::tie(L.R, L.Kind, L.Modifiers) <
1361 std::tie(R.R, R.Kind, R.Modifiers);
1362}
1363
1364std::vector<SemanticToken>
1365toSemanticTokens(llvm::ArrayRef<HighlightingToken> Tokens,
1366 llvm::StringRef Code) {
1367 assert(llvm::is_sorted(Tokens));
1368 std::vector<SemanticToken> Result;
1369 // In case we split a HighlightingToken into multiple tokens (e.g. because it
1370 // was spanning multiple lines), this tracks the last one. This prevents
1371 // having a copy all the time.
1372 HighlightingToken Scratch;
1373 const HighlightingToken *Last = nullptr;
1374 for (const HighlightingToken &Tok : Tokens) {
1375 Result.emplace_back();
1376 SemanticToken *Out = &Result.back();
1377 // deltaStart/deltaLine are relative if possible.
1378 if (Last) {
1379 assert(Tok.R.start.line >= Last->R.end.line);
1380 Out->deltaLine = Tok.R.start.line - Last->R.end.line;
1381 if (Out->deltaLine == 0) {
1382 assert(Tok.R.start.character >= Last->R.start.character);
1383 Out->deltaStart = Tok.R.start.character - Last->R.start.character;
1384 } else {
1385 Out->deltaStart = Tok.R.start.character;
1386 }
1387 } else {
1388 Out->deltaLine = Tok.R.start.line;
1389 Out->deltaStart = Tok.R.start.character;
1390 }
1391 Out->tokenType = static_cast<unsigned>(Tok.Kind);
1392 Out->tokenModifiers = Tok.Modifiers;
1393 Last = &Tok;
1394
1395 if (Tok.R.end.line == Tok.R.start.line) {
1396 Out->length = Tok.R.end.character - Tok.R.start.character;
1397 } else {
1398 // If the token spans a line break, split it into multiple pieces for each
1399 // line.
1400 // This is slow, but multiline tokens are rare.
1401 // FIXME: There's a client capability for supporting multiline tokens,
1402 // respect that.
1403 auto TokStartOffset = llvm::cantFail(positionToOffset(Code, Tok.R.start));
1404 // Note that the loop doesn't cover the last line, which has a special
1405 // length.
1406 for (int I = Tok.R.start.line; I < Tok.R.end.line; ++I) {
1407 auto LineEnd = Code.find('\n', TokStartOffset);
1408 assert(LineEnd != Code.npos);
1409 Out->length = LineEnd - TokStartOffset;
1410 // Token continues on next line, right after the line break.
1411 TokStartOffset = LineEnd + 1;
1412 Result.emplace_back();
1413 Out = &Result.back();
1414 *Out = Result[Result.size() - 2];
1415 // New token starts at the first column of the next line.
1416 Out->deltaLine = 1;
1417 Out->deltaStart = 0;
1418 }
1419 // This is the token on last line.
1420 Out->length = Tok.R.end.character;
1421 // Update the start location for last token, as that's used in the
1422 // relative delta calculation for following tokens.
1423 Scratch = *Last;
1424 Scratch.R.start.line = Tok.R.end.line;
1425 Scratch.R.start.character = 0;
1426 Last = &Scratch;
1427 }
1428 }
1429 return Result;
1430}
1432 switch (Kind) {
1433 case HighlightingKind::Variable:
1434 case HighlightingKind::LocalVariable:
1435 case HighlightingKind::StaticField:
1436 return "variable";
1437 case HighlightingKind::Parameter:
1438 return "parameter";
1439 case HighlightingKind::Function:
1440 return "function";
1441 case HighlightingKind::Method:
1442 return "method";
1443 case HighlightingKind::StaticMethod:
1444 // FIXME: better method with static modifier?
1445 return "function";
1446 case HighlightingKind::Field:
1447 return "property";
1448 case HighlightingKind::Class:
1449 return "class";
1450 case HighlightingKind::Interface:
1451 return "interface";
1452 case HighlightingKind::Enum:
1453 return "enum";
1454 case HighlightingKind::EnumConstant:
1455 return "enumMember";
1456 case HighlightingKind::Typedef:
1457 case HighlightingKind::Type:
1458 return "type";
1459 case HighlightingKind::Unknown:
1460 return "unknown"; // nonstandard
1461 case HighlightingKind::Namespace:
1462 return "namespace";
1463 case HighlightingKind::TemplateParameter:
1464 return "typeParameter";
1465 case HighlightingKind::Concept:
1466 return "concept"; // nonstandard
1467 case HighlightingKind::Primitive:
1468 return "type";
1469 case HighlightingKind::Macro:
1470 return "macro";
1471 case HighlightingKind::Modifier:
1472 return "modifier";
1473 case HighlightingKind::Operator:
1474 return "operator";
1475 case HighlightingKind::Bracket:
1476 return "bracket";
1477 case HighlightingKind::Label:
1478 return "label";
1479 case HighlightingKind::InactiveCode:
1480 return "comment";
1481 }
1482 llvm_unreachable("unhandled HighlightingKind");
1483}
1484
1486 switch (Modifier) {
1487 case HighlightingModifier::Declaration:
1488 return "declaration";
1489 case HighlightingModifier::Definition:
1490 return "definition";
1491 case HighlightingModifier::Deprecated:
1492 return "deprecated";
1493 case HighlightingModifier::Readonly:
1494 return "readonly";
1495 case HighlightingModifier::Static:
1496 return "static";
1497 case HighlightingModifier::Deduced:
1498 return "deduced"; // nonstandard
1499 case HighlightingModifier::Abstract:
1500 return "abstract";
1501 case HighlightingModifier::Virtual:
1502 return "virtual";
1503 case HighlightingModifier::DependentName:
1504 return "dependentName"; // nonstandard
1505 case HighlightingModifier::DefaultLibrary:
1506 return "defaultLibrary";
1507 case HighlightingModifier::UsedAsMutableReference:
1508 return "usedAsMutableReference"; // nonstandard
1509 case HighlightingModifier::UsedAsMutablePointer:
1510 return "usedAsMutablePointer"; // nonstandard
1511 case HighlightingModifier::ConstructorOrDestructor:
1512 return "constructorOrDestructor"; // nonstandard
1513 case HighlightingModifier::UserDefined:
1514 return "userDefined"; // nonstandard
1515 case HighlightingModifier::FunctionScope:
1516 return "functionScope"; // nonstandard
1517 case HighlightingModifier::ClassScope:
1518 return "classScope"; // nonstandard
1519 case HighlightingModifier::FileScope:
1520 return "fileScope"; // nonstandard
1521 case HighlightingModifier::GlobalScope:
1522 return "globalScope"; // nonstandard
1523 }
1524 llvm_unreachable("unhandled HighlightingModifier");
1525}
1526
1527std::vector<SemanticTokensEdit>
1528diffTokens(llvm::ArrayRef<SemanticToken> Old,
1529 llvm::ArrayRef<SemanticToken> New) {
1530 // For now, just replace everything from the first-last modification.
1531 // FIXME: use a real diff instead, this is bad with include-insertion.
1532
1533 unsigned Offset = 0;
1534 while (!Old.empty() && !New.empty() && Old.front() == New.front()) {
1535 ++Offset;
1536 Old = Old.drop_front();
1537 New = New.drop_front();
1538 }
1539 while (!Old.empty() && !New.empty() && Old.back() == New.back()) {
1540 Old = Old.drop_back();
1541 New = New.drop_back();
1542 }
1543
1544 if (Old.empty() && New.empty())
1545 return {};
1547 Edit.startToken = Offset;
1548 Edit.deleteTokens = Old.size();
1549 Edit.tokens = New;
1550 return {std::move(Edit)};
1551}
1552
1553std::vector<Range> getInactiveRegions(ParsedAST &AST) {
1554 std::vector<Range> SkippedRanges(std::move(AST.getMacros().SkippedRanges));
1555 const auto &SM = AST.getSourceManager();
1556 StringRef MainCode = SM.getBufferOrFake(SM.getMainFileID()).getBuffer();
1557 std::vector<Range> InactiveRegions;
1558 for (const Range &Skipped : SkippedRanges) {
1559 Range Inactive = Skipped;
1560 // Sometimes, SkippedRanges contains a range ending at position 0
1561 // of a line. Clients that apply whole-line styles will treat that
1562 // line as inactive which is not desirable, so adjust the ending
1563 // position to be the end of the previous line.
1564 if (Inactive.end.character == 0 && Inactive.end.line > 0) {
1565 --Inactive.end.line;
1566 }
1567 // Exclude the directive lines themselves from the range.
1568 if (Inactive.end.line >= Inactive.start.line + 2) {
1569 ++Inactive.start.line;
1570 --Inactive.end.line;
1571 } else {
1572 // range would be empty, e.g. #endif on next line after #ifdef
1573 continue;
1574 }
1575 // Since we've adjusted the ending line, we need to recompute the
1576 // column to reflect the end of that line.
1577 if (auto EndOfLine = endOfLine(MainCode, Inactive.end.line)) {
1578 Inactive.end = *EndOfLine;
1579 } else {
1580 elog("Failed to determine end of line: {0}", EndOfLine.takeError());
1581 continue;
1582 }
1583 InactiveRegions.push_back(Inactive);
1584 }
1585 return InactiveRegions;
1586}
1587
1588} // namespace clangd
1589} // namespace clang
const Expr * E
const FunctionDecl * Decl
BindArgumentKind Kind
CaptureExpr CE
size_t Offset
CodeCompletionBuilder Builder
CompiledFragmentImpl & Out
std::string Code
const Criteria C
llvm::StringRef Name
CharSourceRange Range
SourceRange for the file name.
SourceLocation Loc
Kind K
Definition: Rename.cpp:469
const google::protobuf::Message & M
Definition: Server.cpp:309
llvm::raw_string_ostream OS
Definition: TraceTests.cpp:160
llvm::json::Object Args
Definition: Trace.cpp:138
std::vector< const NamedDecl * > resolveUsingValueDecl(const UnresolvedUsingValueDecl *UUVD) const
Stores and provides access to parsed AST.
Definition: ParsedAST.h:46
std::optional< HighlightingModifier > highlightingModifierFromString(llvm::StringRef Name)
llvm::StringRef toSemanticTokenModifier(HighlightingModifier Modifier)
std::vector< HighlightingToken > getSemanticHighlightings(ParsedAST &AST, bool IncludeInactiveRegionTokens)
std::optional< HighlightingKind > highlightingKindFromString(llvm::StringRef Name)
Range halfOpenToRange(const SourceManager &SM, CharSourceRange R)
Definition: SourceCode.cpp:468
llvm::StringRef toSemanticTokenType(HighlightingKind Kind)
size_t lspLength(llvm::StringRef Code)
Definition: SourceCode.cpp:149
std::vector< SemanticToken > toSemanticTokens(llvm::ArrayRef< HighlightingToken > Tokens, llvm::StringRef Code)
std::vector< SemanticTokensEdit > diffTokens(llvm::ArrayRef< SemanticToken > Old, llvm::ArrayRef< SemanticToken > New)
void findExplicitReferences(const Stmt *S, llvm::function_ref< void(ReferenceLoc)> Out, const HeuristicResolver *Resolver)
Recursively traverse S and report all references explicitly written in the code.
bool operator==(const Inclusion &LHS, const Inclusion &RHS)
Definition: Headers.cpp:330
llvm::raw_ostream & operator<<(llvm::raw_ostream &OS, const CodeCompletion &C)
Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc)
Turn a SourceLocation into a [line, column] pair.
Definition: SourceCode.cpp:214
llvm::Expected< size_t > positionToOffset(llvm::StringRef Code, Position P, bool AllowColumnsBeyondLineLength)
Turn a [line, column] pair into an offset in Code.
Definition: SourceCode.cpp:173
bool operator<(const Ref &L, const Ref &R)
Definition: Ref.h:95
@ Type
An inlay hint that for a type annotation.
std::vector< Range > getInactiveRegions(ParsedAST &AST)
void elog(const char *Fmt, Ts &&... Vals)
Definition: Logger.h:61
@ Underlying
This is the underlying declaration for a renaming-alias, decltype etc.
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
static const Config & current()
Returns the Config of the current Context, or an empty configuration.
Definition: Config.cpp:17
A set of edits generated for a single file.
Definition: SourceCode.h:185
int line
Line position in a document (zero-based).
Definition: Protocol.h:158
int character
Character offset on a line in a document (zero-based).
Definition: Protocol.h:163
Position start
The range's start position.
Definition: Protocol.h:187
Position end
The range's end position.
Definition: Protocol.h:190
Information about a reference written in the source code, independent of the actual AST node that thi...
Definition: FindTarget.h:126
bool IsDecl
True if the reference is a declaration or definition;.
Definition: FindTarget.h:132
llvm::SmallVector< const NamedDecl *, 1 > Targets
A list of targets referenced by this name.
Definition: FindTarget.h:138
Specifies a single semantic token in the document.
Definition: Protocol.h:1749
Describes a replacement of a contiguous range of semanticTokens.
Definition: Protocol.h:1797