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"
43llvm::Expected<Position> endOfLine(llvm::StringRef
Code,
int Line) {
46 return StartOfLine.takeError();
47 StringRef LineText =
Code.drop_front(*StartOfLine).take_until([](
char C) {
55bool canHighlightName(DeclarationName
Name) {
56 switch (
Name.getNameKind()) {
57 case DeclarationName::Identifier: {
58 auto *II =
Name.getAsIdentifierInfo();
59 return II && !II->getName().empty();
61 case DeclarationName::CXXConstructorName:
62 case DeclarationName::CXXDestructorName:
64 case DeclarationName::ObjCZeroArgSelector:
65 case DeclarationName::ObjCOneArgSelector:
66 case DeclarationName::ObjCMultiArgSelector:
70 case DeclarationName::CXXConversionFunctionName:
71 case DeclarationName::CXXOperatorName:
72 case DeclarationName::CXXDeductionGuideName:
73 case DeclarationName::CXXLiteralOperatorName:
74 case DeclarationName::CXXUsingDirective:
77 llvm_unreachable(
"invalid name kind");
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);
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())
105 if (
auto *TD = dyn_cast<TemplateDecl>(D)) {
106 if (
auto *Templated = TD->getTemplatedDecl())
109 if (
auto *TD = dyn_cast<TypedefNameDecl>(D)) {
112 kindForType(TD->getUnderlyingType().getTypePtrOrNull(), Resolver))
120 if (
auto *RD = llvm::dyn_cast<RecordDecl>(D)) {
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))
136 if (
auto *OMD = dyn_cast<ObjCMethodDecl>(D))
139 if (isa<FieldDecl, IndirectFieldDecl, 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))
150 return VD->isStaticDataMember()
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)) {
173 if (!Targets.empty() && Targets[0] != UUVD) {
174 return kindForDecl(Targets[0], Resolver);
180std::optional<HighlightingKind> kindForType(
const Type *TP,
181 const HeuristicResolver *Resolver) {
184 if (TP->isBuiltinType())
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);
196bool isConst(QualType T) {
199 T =
T.getNonReferenceType();
200 if (
T.isConstQualified())
202 if (
const auto *AT =
T->getAsArrayTypeUnsafe())
203 return isConst(AT->getElementType());
204 if (isConst(
T->getPointeeType()))
212bool isConst(
const Decl *D) {
213 if (llvm::isa<EnumConstantDecl>(D) || llvm::isa<NonTypeTemplateParmDecl>(D))
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()))
220 if (
const auto *OCPD = llvm::dyn_cast<ObjCPropertyDecl>(D)) {
221 if (OCPD->isReadOnly())
224 if (
const auto *MPD = llvm::dyn_cast<MSPropertyDecl>(D)) {
225 if (!MPD->hasSetter())
228 if (
const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(D)) {
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();
266bool isAbstract(
const Decl *D) {
267 if (
const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(D))
268 return CMD->isPureVirtual();
269 if (
const auto *CRD = llvm::dyn_cast<CXXRecordDecl>(D))
270 return CRD->hasDefinition() && CRD->isAbstract();
274bool isVirtual(
const Decl *D) {
275 if (
const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(D))
276 return CMD->isVirtual();
280bool isDependent(
const Decl *D) {
281 if (isa<UnresolvedUsingValueDecl>(D))
289bool isDefaultLibrary(
const Decl *D) {
290 SourceLocation
Loc = D->getLocation();
293 return D->getASTContext().getSourceManager().isInSystemHeader(
Loc);
296bool isDefaultLibrary(
const Type *T) {
302 if (
auto *TD = dyn_cast<TemplateTypeParmType>(
Underlying))
303 return isDefaultLibrary(TD->getDecl());
305 return isDefaultLibrary(TD);
312SourceLocation getHighlightableSpellingToken(SourceLocation L,
313 const SourceManager &SM) {
315 return SM.isWrittenInMainFile(L) ? L : SourceLocation{};
317 if (!SM.isMacroArgExpansion(L))
320 return getHighlightableSpellingToken(SM.getImmediateSpellingLoc(L), SM);
323unsigned evaluateHighlightPriority(
const HighlightingToken &Tok) {
324 enum HighlightPriority { Dependent = 0, Resolved = 1 };
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)
354 auto Result = Priority1 > Priority2 ?
A :
B;
355 Result.Modifiers =
A.Modifiers |
B.Modifiers;
358std::optional<HighlightingToken>
359resolveConflict(ArrayRef<HighlightingToken> Tokens) {
360 if (Tokens.size() == 1)
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]);
373class HighlightingFilter {
375 HighlightingFilter() {
376 for (
auto &Active : ActiveKindLookup)
379 ActiveModifiersMask = ~0;
383 ActiveKindLookup[
static_cast<size_t>(
Kind)] =
false;
387 ActiveModifiersMask &= ~(1 <<
static_cast<uint32_t
>(
Modifier));
391 return ActiveKindLookup[
static_cast<size_t>(
Kind)];
394 uint32_t maskModifiers(uint32_t Modifiers)
const {
395 return Modifiers & ActiveModifiersMask;
398 static HighlightingFilter fromCurrentConfig() {
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);
413 uint32_t ActiveModifiersMask;
417class HighlightingsBuilder {
419 HighlightingsBuilder(
const ParsedAST &
AST,
const HighlightingFilter &Filter)
420 : TB(
AST.getTokens()), SourceMgr(
AST.getSourceManager()),
421 LangOpts(
AST.getLangOpts()), Filter(Filter),
422 Resolver(
AST.getHeuristicResolver()) {}
425 auto Range = getRangeForSourceLocation(
Loc);
427 return InvalidHighlightingToken;
429 return addToken(*Range,
Kind);
434 void addAngleBracketTokens(SourceLocation LLoc, SourceLocation RLoc) {
435 if (!LLoc.isValid() || !RLoc.isValid())
438 auto LRange = getRangeForSourceLocation(LLoc);
444 RLoc = SourceMgr.getFileLoc(RLoc);
446 RLoc = getHighlightableSpellingToken(RLoc, SourceMgr);
450 const auto *RTok = TB.spelledTokenContaining(RLoc);
454 if (!RTok || RTok->kind() == tok::greatergreater) {
463 if (RTok->kind() == tok::greater) {
464 if (
auto RRange = getRangeForSourceLocation(RLoc)) {
473 if (!Filter.isHighlightKindActive(
Kind))
474 return InvalidHighlightingToken;
476 HighlightingToken HT;
479 Tokens.push_back(std::move(HT));
480 return Tokens.back();
484 if (
auto Range = getRangeForSourceLocation(
Loc))
488 std::vector<HighlightingToken> collect(ParsedAST &
AST) && {
492 auto Last = std::unique(Tokens.begin(), Tokens.end());
493 Tokens.erase(Last, Tokens.end());
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) {
505 return T.R == TokRef.front().R;
507 if (
auto Resolved = resolveConflict(Conflicting)) {
509 auto Modifiers = ExtraModifiers.find(Resolved->R);
510 if (Modifiers != ExtraModifiers.end()) {
512 Resolved->addModifier(Mod);
516 Resolved->Modifiers = Filter.maskModifiers(Resolved->Modifiers);
517 NonConflicting.push_back(*Resolved);
521 TokRef = TokRef.drop_front(Conflicting.size());
525 return NonConflicting;
527 const auto &SM =
AST.getSourceManager();
528 StringRef MainCode = SM.getBufferOrFake(SM.getMainFileID()).getBuffer();
531 std::vector<HighlightingToken> WithInactiveLines;
533 llvm::sort(SortedInactiveRegions);
534 auto It = NonConflicting.begin();
535 for (
const Range &R : SortedInactiveRegions) {
538 assert(R.start.line <= R.end.line);
539 for (
int Line = R.start.line; Line <= R.end.line; ++Line) {
541 for (; It != NonConflicting.end() && It->R.start.line < Line; ++It)
542 WithInactiveLines.push_back(std::move(*It));
544 auto EndOfLine = endOfLine(MainCode, Line);
546 HighlightingToken HT;
547 WithInactiveLines.emplace_back();
549 WithInactiveLines.back().R.start.line =
Line;
550 WithInactiveLines.back().R.end = *EndOfLine;
552 elog(
"Failed to determine end of line: {0}", EndOfLine.takeError());
560 while (It != NonConflicting.end() && It->R.start.line == Line)
565 for (; It != NonConflicting.end(); ++It)
566 WithInactiveLines.push_back(std::move(*It));
567 return WithInactiveLines;
570 const HeuristicResolver *getResolver()
const {
return Resolver; }
573 std::optional<Range> getRangeForSourceLocation(SourceLocation
Loc) {
574 Loc = getHighlightableSpellingToken(
Loc, SourceMgr);
579 const auto *Tok = TB.spelledTokenContaining(
Loc);
583 Tok->range(SourceMgr).toCharRange(SourceMgr));
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;
594 HighlightingToken InvalidHighlightingToken;
597std::optional<HighlightingModifier> scopeModifier(
const NamedDecl *D) {
598 const DeclContext *DC = D->getDeclContext();
600 if (
auto *R = dyn_cast_or_null<RecordDecl>(D))
601 if (R->isInjectedClassName())
602 DC = DC->getParent();
604 if (llvm::isa<FieldDecl>(D))
605 if (
const auto *RD = llvm::dyn_cast<RecordDecl>(DC))
609 for (; !DC->isFileContext(); DC = DC->getParent()) {
610 if (DC->isFunctionOrMethod())
617 if (DC->isTranslationUnit() && D->isTemplateParameter())
620 if (llvm::to_underlying(D->getLinkageInternal()) <
621 llvm::to_underlying(Linkage::External))
626std::optional<HighlightingModifier> scopeModifier(
const Type *T) {
629 if (
T->isBuiltinType())
631 if (
auto *TD = dyn_cast<TemplateTypeParmType>(T))
632 return scopeModifier(TD->getDecl());
633 if (
auto *TD =
T->getAsTagDecl())
634 return scopeModifier(TD);
640class CollectExtraHighlightings
645 CollectExtraHighlightings(HighlightingsBuilder &H) : H(H) {}
647 bool VisitCXXConstructExpr(CXXConstructExpr *
E) {
648 highlightMutableReferenceArguments(
E->getConstructor(),
649 {E->getArgs(), E->getNumArgs()});
654 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
655 if (Init->isMemberInitializer())
656 if (
auto *Member = Init->getMember())
657 highlightMutableReferenceArgument(Member->getType(), Init->getInit());
658 return Base::TraverseConstructorInitializer(Init);
661 bool TraverseTypeConstraint(
const TypeConstraint *
C) {
662 if (
auto *
Args =
C->getTemplateArgsAsWritten())
663 H.addAngleBracketTokens(
Args->getLAngleLoc(),
Args->getRAngleLoc());
664 return Base::TraverseTypeConstraint(
C);
667 bool VisitPredefinedExpr(PredefinedExpr *
E) {
675 bool VisitConceptSpecializationExpr(ConceptSpecializationExpr *
E) {
676 if (
auto *
Args =
E->getTemplateArgsAsWritten())
677 H.addAngleBracketTokens(
Args->getLAngleLoc(),
Args->getRAngleLoc());
681 bool VisitTemplateDecl(TemplateDecl *D) {
682 if (
auto *TPL = D->getTemplateParameters())
683 H.addAngleBracketTokens(TPL->getLAngleLoc(), TPL->getRAngleLoc());
687 bool VisitTagDecl(TagDecl *D) {
688 for (
unsigned i = 0; i < D->getNumTemplateParameterLists(); ++i) {
689 if (
auto *TPL = D->getTemplateParameterList(i))
690 H.addAngleBracketTokens(TPL->getLAngleLoc(), TPL->getRAngleLoc());
696 VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D) {
697 if (
auto *
Args = D->getTemplateArgsAsWritten())
698 H.addAngleBracketTokens(
Args->getLAngleLoc(),
Args->getRAngleLoc());
702 bool VisitClassTemplatePartialSpecializationDecl(
703 ClassTemplatePartialSpecializationDecl *D) {
704 if (
auto *TPL = D->getTemplateParameters())
705 H.addAngleBracketTokens(TPL->getLAngleLoc(), TPL->getRAngleLoc());
709 bool VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D) {
710 if (
auto *
Args = D->getTemplateArgsAsWritten())
711 H.addAngleBracketTokens(
Args->getLAngleLoc(),
Args->getRAngleLoc());
715 bool VisitVarTemplatePartialSpecializationDecl(
716 VarTemplatePartialSpecializationDecl *D) {
717 if (
auto *TPL = D->getTemplateParameters())
718 H.addAngleBracketTokens(TPL->getLAngleLoc(), TPL->getRAngleLoc());
722 bool VisitDeclRefExpr(DeclRefExpr *
E) {
723 H.addAngleBracketTokens(
E->getLAngleLoc(),
E->getRAngleLoc());
726 bool VisitMemberExpr(MemberExpr *
E) {
727 H.addAngleBracketTokens(
E->getLAngleLoc(),
E->getRAngleLoc());
731 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc L) {
732 H.addAngleBracketTokens(L.getLAngleLoc(), L.getRAngleLoc());
736 bool VisitFunctionDecl(FunctionDecl *D) {
737 if (D->isOverloadedOperator()) {
738 const auto AddOpDeclToken = [&](SourceLocation
Loc) {
741 if (D->isThisDeclarationADefinition())
744 const auto Range = D->getNameInfo().getCXXOperatorNameRange();
745 AddOpDeclToken(
Range.getBegin());
746 const auto Kind = D->getOverloadedOperator();
747 if (
Kind == OO_Call ||
Kind == OO_Subscript)
748 AddOpDeclToken(
Range.getEnd());
750 if (
auto *
Args = D->getTemplateSpecializationArgsAsWritten())
751 H.addAngleBracketTokens(
Args->getLAngleLoc(),
Args->getRAngleLoc());
755 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *
E) {
756 const auto AddOpToken = [&](SourceLocation
Loc) {
760 AddOpToken(
E->getOperatorLoc());
761 const auto Kind =
E->getOperator();
762 if (
Kind == OO_Call ||
Kind == OO_Subscript) {
763 if (
auto *Callee =
E->getCallee())
764 AddOpToken(Callee->getBeginLoc());
769 bool VisitUnaryOperator(UnaryOperator *Op) {
771 if (Op->getSubExpr()->isTypeDependent())
776 bool VisitBinaryOperator(BinaryOperator *Op) {
778 if (Op->getLHS()->isTypeDependent() || Op->getRHS()->isTypeDependent())
783 bool VisitConditionalOperator(ConditionalOperator *Op) {
789 bool VisitCXXNewExpr(CXXNewExpr *
E) {
791 if (isa_and_present<CXXMethodDecl>(
E->getOperatorNew()))
796 bool VisitCXXDeleteExpr(CXXDeleteExpr *
E) {
798 if (isa_and_present<CXXMethodDecl>(
E->getOperatorDelete()))
803 bool VisitCXXNamedCastExpr(CXXNamedCastExpr *
E) {
804 const auto &
B =
E->getAngleBrackets();
805 H.addAngleBracketTokens(
B.getBegin(),
B.getEnd());
809 bool VisitCallExpr(CallExpr *
E) {
812 if (isa<UserDefinedLiteral>(
E))
817 llvm::ArrayRef<const Expr *>
Args = {
E->getArgs(),
E->getNumArgs()};
818 if (
auto *CallOp = dyn_cast<CXXOperatorCallExpr>(
E)) {
819 switch (CallOp->getOperator()) {
829 highlightMutableReferenceArguments(
830 dyn_cast_or_null<FunctionDecl>(
E->getCalleeDecl()),
Args);
835 void highlightMutableReferenceArgument(QualType T,
const Expr *Arg) {
842 bool IsRef =
T->isLValueReferenceType();
843 bool IsPtr =
T->isPointerType();
844 if ((!IsRef && !IsPtr) ||
T->getPointeeType().isConstQualified() ||
845 T->isDependentType()) {
849 std::optional<SourceLocation>
Location;
854 if (
auto *IC = dyn_cast<ImplicitCastExpr>(Arg))
855 Arg = IC->getSubExprAsWritten();
856 if (
auto *UO = dyn_cast<UnaryOperator>(Arg)) {
857 if (UO->getOpcode() == UO_AddrOf)
858 Arg = UO->getSubExpr();
860 if (
auto *DR = dyn_cast<DeclRefExpr>(Arg))
862 else if (
auto *
M = dyn_cast<MemberExpr>(Arg))
872 highlightMutableReferenceArguments(
const FunctionDecl *FD,
873 llvm::ArrayRef<const Expr *const>
Args) {
877 if (
auto *ProtoType = FD->getType()->getAs<FunctionProtoType>()) {
882 I < std::min(
size_t(ProtoType->getNumParams()),
Args.size()); ++I) {
883 highlightMutableReferenceArgument(ProtoType->getParamType(I),
Args[I]);
888 bool VisitDecltypeTypeLoc(DecltypeTypeLoc L) {
889 if (
auto K = kindForType(L.getTypePtr(), H.getResolver())) {
890 auto &Tok = H.addToken(L.getBeginLoc(), *
K)
892 if (
auto Mod = scopeModifier(L.getTypePtr()))
893 Tok.addModifier(*Mod);
894 if (isDefaultLibrary(L.getTypePtr()))
900 bool VisitCXXDestructorDecl(CXXDestructorDecl *D) {
901 if (
auto *TI = D->getNameInfo().getNamedTypeInfo()) {
902 SourceLocation
Loc = TI->getTypeLoc().getBeginLoc();
905 if (D->isThisDeclarationADefinition())
911 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *
CE) {
914 if (
auto *D =
CE->getMethodDecl()) {
915 if (isa<CXXDestructorDecl>(D)) {
916 if (
auto *ME = dyn_cast<MemberExpr>(
CE->getCallee())) {
917 if (
auto *TI = ME->getMemberNameInfo().getNamedTypeInfo()) {
918 H.addExtraModifier(TI->getTypeLoc().getBeginLoc(),
922 }
else if (D->isOverloadedOperator()) {
923 if (
auto *ME = dyn_cast<MemberExpr>(
CE->getCallee()))
925 ME->getMemberNameInfo().getCXXOperatorNameRange().getBegin(),
933 bool VisitDeclaratorDecl(DeclaratorDecl *D) {
934 for (
unsigned i = 0; i < D->getNumTemplateParameterLists(); ++i) {
935 if (
auto *TPL = D->getTemplateParameterList(i))
936 H.addAngleBracketTokens(TPL->getLAngleLoc(), TPL->getRAngleLoc());
938 auto *AT = D->getType()->getContainedAutoType();
942 kindForType(AT->getDeducedType().getTypePtrOrNull(), H.getResolver());
945 auto *TSI = D->getTypeSourceInfo();
948 SourceLocation StartLoc =
949 TSI->getTypeLoc().getContainedAutoTypeLoc().getNameLoc();
954 if (StartLoc == D->getLocation())
959 const Type *
Deduced = AT->getDeducedType().getTypePtrOrNull();
960 if (
auto Mod = scopeModifier(
Deduced))
961 Tok.addModifier(*Mod);
969 void highlightObjCSelector(
const ArrayRef<SourceLocation> &Locs,
bool Decl,
973 for (SourceLocation Part : Locs) {
987 bool VisitObjCMethodDecl(ObjCMethodDecl *OMD) {
988 llvm::SmallVector<SourceLocation> Locs;
989 OMD->getSelectorLocs(Locs);
990 highlightObjCSelector(Locs,
true,
991 OMD->isThisDeclarationADefinition(),
992 OMD->isClassMethod(), isDefaultLibrary(OMD));
996 bool VisitObjCMessageExpr(ObjCMessageExpr *OME) {
997 llvm::SmallVector<SourceLocation> Locs;
998 OME->getSelectorLocs(Locs);
1000 if (ObjCMethodDecl *OMD = OME->getMethodDecl())
1002 highlightObjCSelector(Locs,
false,
false,
1011 void highlightObjCImplicitPropertyRef(
const ObjCMethodDecl *OMD,
1012 SourceLocation
Loc) {
1015 if (OMD->isClassMethod())
1017 if (isDefaultLibrary(OMD))
1021 bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *OPRE) {
1025 if (!OPRE->isImplicitProperty())
1031 if (OPRE->isMessagingGetter()) {
1032 highlightObjCImplicitPropertyRef(OPRE->getImplicitPropertyGetter(),
1033 OPRE->getLocation());
1036 if (OPRE->isMessagingSetter()) {
1037 highlightObjCImplicitPropertyRef(OPRE->getImplicitPropertySetter(),
1038 OPRE->getLocation());
1043 bool VisitOverloadExpr(OverloadExpr *
E) {
1044 H.addAngleBracketTokens(
E->getLAngleLoc(),
E->getRAngleLoc());
1045 if (!
E->decls().empty())
1049 if (llvm::isa<UnresolvedMemberExpr>(
E))
1055 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *
E) {
1059 H.addAngleBracketTokens(
E->getLAngleLoc(),
E->getRAngleLoc());
1063 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *
E) {
1067 H.addAngleBracketTokens(
E->getLAngleLoc(),
E->getRAngleLoc());
1071 bool VisitAttr(Attr *A) {
1072 switch (
A->getKind()) {
1073 case attr::Override:
1083 bool VisitDependentNameTypeLoc(DependentNameTypeLoc L) {
1090 bool VisitDependentTemplateSpecializationTypeLoc(
1091 DependentTemplateSpecializationTypeLoc L) {
1095 H.addAngleBracketTokens(L.getLAngleLoc(), L.getRAngleLoc());
1099 bool TraverseTemplateArgumentLoc(TemplateArgumentLoc L) {
1102 if (L.getArgument().getKind() != TemplateArgument::Template &&
1103 L.getArgument().getKind() != TemplateArgument::TemplateExpansion)
1104 return RecursiveASTVisitor::TraverseTemplateArgumentLoc(L);
1106 TemplateName N = L.getArgument().getAsTemplateOrTemplatePattern();
1107 switch (N.getKind()) {
1108 case TemplateName::OverloadedTemplate:
1113 case TemplateName::DependentTemplate:
1114 case TemplateName::AssumedTemplate:
1118 case TemplateName::Template:
1119 case TemplateName::QualifiedTemplate:
1120 case TemplateName::SubstTemplateTemplateParm:
1121 case TemplateName::SubstTemplateTemplateParmPack:
1122 case TemplateName::UsingTemplate:
1126 return RecursiveASTVisitor::TraverseTemplateArgumentLoc(L);
1134 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc Q) {
1135 if (NestedNameSpecifier *NNS = Q.getNestedNameSpecifier()) {
1136 if (NNS->getKind() == NestedNameSpecifier::Identifier)
1141 return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(Q);
1145 HighlightingsBuilder &H;
1149std::vector<HighlightingToken>
1151 auto &
C =
AST.getASTContext();
1152 HighlightingFilter Filter = HighlightingFilter::fromCurrentConfig();
1153 if (!IncludeInactiveRegionTokens)
1158 CollectExtraHighlightings(
Builder).TraverseAST(
C);
1164 if (!canHighlightName(Decl->getDeclName()))
1166 auto Kind = kindForDecl(Decl, AST.getHeuristicResolver());
1169 auto &Tok = Builder.addToken(R.NameLoc, *Kind);
1172 if (auto *TD = dyn_cast<TemplateDecl>(Decl)) {
1173 if (auto *Templated = TD->getTemplatedDecl())
1176 if (
auto Mod = scopeModifier(
Decl))
1177 Tok.addModifier(*Mod);
1182 if (isAbstract(
Decl))
1184 if (isVirtual(
Decl))
1186 if (isDependent(
Decl))
1188 if (isDefaultLibrary(
Decl))
1190 if (
Decl->isDeprecated())
1192 if (isa<CXXConstructorDecl>(
Decl))
1198 if (!isa<UnresolvedUsingValueDecl>(Decl))
1199 Tok.addModifier(HighlightingModifier::Declaration);
1200 if (isUniqueDefinition(Decl))
1201 Tok.addModifier(HighlightingModifier::Definition);
1205 AST.getHeuristicResolver());
1207 auto AddMacro = [&](
const MacroOccurrence &
M) {
1208 auto &T =
Builder.addToken(
M.toRange(
C.getSourceManager()),
1214 for (
const auto &SIDToRefs :
AST.getMacros().MacroRefs)
1215 for (
const auto &
M : SIDToRefs.second)
1217 for (
const auto &
M :
AST.getMacros().UnknownMacros)
1225 case HighlightingKind::Variable:
1226 return OS <<
"Variable";
1227 case HighlightingKind::LocalVariable:
1228 return OS <<
"LocalVariable";
1229 case HighlightingKind::Parameter:
1230 return OS <<
"Parameter";
1231 case HighlightingKind::Function:
1232 return OS <<
"Function";
1233 case HighlightingKind::Method:
1234 return OS <<
"Method";
1235 case HighlightingKind::StaticMethod:
1236 return OS <<
"StaticMethod";
1237 case HighlightingKind::Field:
1238 return OS <<
"Field";
1239 case HighlightingKind::StaticField:
1240 return OS <<
"StaticField";
1241 case HighlightingKind::Class:
1242 return OS <<
"Class";
1243 case HighlightingKind::Interface:
1244 return OS <<
"Interface";
1245 case HighlightingKind::Enum:
1246 return OS <<
"Enum";
1247 case HighlightingKind::EnumConstant:
1248 return OS <<
"EnumConstant";
1249 case HighlightingKind::Typedef:
1250 return OS <<
"Typedef";
1251 case HighlightingKind::Type:
1252 return OS <<
"Type";
1253 case HighlightingKind::Unknown:
1254 return OS <<
"Unknown";
1255 case HighlightingKind::Namespace:
1256 return OS <<
"Namespace";
1257 case HighlightingKind::TemplateParameter:
1258 return OS <<
"TemplateParameter";
1259 case HighlightingKind::Concept:
1260 return OS <<
"Concept";
1261 case HighlightingKind::Primitive:
1262 return OS <<
"Primitive";
1263 case HighlightingKind::Macro:
1264 return OS <<
"Macro";
1265 case HighlightingKind::Modifier:
1266 return OS <<
"Modifier";
1267 case HighlightingKind::Operator:
1268 return OS <<
"Operator";
1269 case HighlightingKind::Bracket:
1270 return OS <<
"Bracket";
1271 case HighlightingKind::Label:
1272 return OS <<
"Label";
1273 case HighlightingKind::InactiveCode:
1274 return OS <<
"InactiveCode";
1276 llvm_unreachable(
"invalid HighlightingKind");
1278std::optional<HighlightingKind>
1280 static llvm::StringMap<HighlightingKind> Lookup = {
1281 {
"Variable", HighlightingKind::Variable},
1282 {
"LocalVariable", HighlightingKind::LocalVariable},
1283 {
"Parameter", HighlightingKind::Parameter},
1284 {
"Function", HighlightingKind::Function},
1285 {
"Method", HighlightingKind::Method},
1286 {
"StaticMethod", HighlightingKind::StaticMethod},
1287 {
"Field", HighlightingKind::Field},
1288 {
"StaticField", HighlightingKind::StaticField},
1289 {
"Class", HighlightingKind::Class},
1290 {
"Interface", HighlightingKind::Interface},
1291 {
"Enum", HighlightingKind::Enum},
1292 {
"EnumConstant", HighlightingKind::EnumConstant},
1293 {
"Typedef", HighlightingKind::Typedef},
1294 {
"Type", HighlightingKind::Type},
1295 {
"Unknown", HighlightingKind::Unknown},
1296 {
"Namespace", HighlightingKind::Namespace},
1297 {
"TemplateParameter", HighlightingKind::TemplateParameter},
1298 {
"Concept", HighlightingKind::Concept},
1299 {
"Primitive", HighlightingKind::Primitive},
1300 {
"Macro", HighlightingKind::Macro},
1301 {
"Modifier", HighlightingKind::Modifier},
1302 {
"Operator", HighlightingKind::Operator},
1303 {
"Bracket", HighlightingKind::Bracket},
1304 {
"InactiveCode", HighlightingKind::InactiveCode},
1307 auto It = Lookup.find(
Name);
1308 return It != Lookup.end() ? std::make_optional(It->getValue()) : std::nullopt;
1312 case HighlightingModifier::Declaration:
1313 return OS <<
"decl";
1314 case HighlightingModifier::Definition:
1316 case HighlightingModifier::ConstructorOrDestructor:
1317 return OS <<
"constrDestr";
1322std::optional<HighlightingModifier>
1324 static llvm::StringMap<HighlightingModifier> Lookup = {
1325 {
"Declaration", HighlightingModifier::Declaration},
1326 {
"Definition", HighlightingModifier::Definition},
1327 {
"Deprecated", HighlightingModifier::Deprecated},
1328 {
"Deduced", HighlightingModifier::Deduced},
1329 {
"Readonly", HighlightingModifier::Readonly},
1330 {
"Static", HighlightingModifier::Static},
1331 {
"Abstract", HighlightingModifier::Abstract},
1332 {
"Virtual", HighlightingModifier::Virtual},
1333 {
"DependentName", HighlightingModifier::DependentName},
1334 {
"DefaultLibrary", HighlightingModifier::DefaultLibrary},
1335 {
"UsedAsMutableReference", HighlightingModifier::UsedAsMutableReference},
1336 {
"UsedAsMutablePointer", HighlightingModifier::UsedAsMutablePointer},
1337 {
"ConstructorOrDestructor",
1338 HighlightingModifier::ConstructorOrDestructor},
1339 {
"UserDefined", HighlightingModifier::UserDefined},
1340 {
"FunctionScope", HighlightingModifier::FunctionScope},
1341 {
"ClassScope", HighlightingModifier::ClassScope},
1342 {
"FileScope", HighlightingModifier::FileScope},
1343 {
"GlobalScope", HighlightingModifier::GlobalScope},
1346 auto It = Lookup.find(
Name);
1347 return It != Lookup.end() ? std::make_optional(It->getValue()) : std::nullopt;
1351 return std::tie(L.R, L.Kind, L.Modifiers) ==
1355 return std::tie(L.R, L.Kind, L.Modifiers) <
1359std::vector<SemanticToken>
1361 llvm::StringRef
Code) {
1362 assert(llvm::is_sorted(Tokens));
1363 std::vector<SemanticToken> Result;
1370 Result.emplace_back();
1374 assert(Tok.R.start.line >= Last->
R.
end.
line);
1375 Out->deltaLine = Tok.R.start.line - Last->
R.
end.
line;
1376 if (
Out->deltaLine == 0) {
1380 Out->deltaStart = Tok.R.start.character;
1383 Out->deltaLine = Tok.R.start.line;
1384 Out->deltaStart = Tok.R.start.character;
1386 Out->tokenType =
static_cast<unsigned>(Tok.Kind);
1387 Out->tokenModifiers = Tok.Modifiers;
1390 if (Tok.R.end.line == Tok.R.start.line) {
1391 Out->length = Tok.R.end.character - Tok.R.start.character;
1401 for (
int I = Tok.R.start.line; I < Tok.R.end.line; ++I) {
1402 auto LineEnd =
Code.find(
'\n', TokStartOffset);
1403 assert(LineEnd !=
Code.npos);
1404 Out->length = LineEnd - TokStartOffset;
1406 TokStartOffset = LineEnd + 1;
1407 Result.emplace_back();
1408 Out = &Result.back();
1409 *
Out = Result[Result.size() - 2];
1412 Out->deltaStart = 0;
1415 Out->length = Tok.R.end.character;
1428 case HighlightingKind::Variable:
1429 case HighlightingKind::LocalVariable:
1430 case HighlightingKind::StaticField:
1432 case HighlightingKind::Parameter:
1434 case HighlightingKind::Function:
1436 case HighlightingKind::Method:
1438 case HighlightingKind::StaticMethod:
1441 case HighlightingKind::Field:
1443 case HighlightingKind::Class:
1445 case HighlightingKind::Interface:
1447 case HighlightingKind::Enum:
1449 case HighlightingKind::EnumConstant:
1450 return "enumMember";
1451 case HighlightingKind::Typedef:
1452 case HighlightingKind::Type:
1454 case HighlightingKind::Unknown:
1456 case HighlightingKind::Namespace:
1458 case HighlightingKind::TemplateParameter:
1459 return "typeParameter";
1460 case HighlightingKind::Concept:
1462 case HighlightingKind::Primitive:
1464 case HighlightingKind::Macro:
1466 case HighlightingKind::Modifier:
1468 case HighlightingKind::Operator:
1470 case HighlightingKind::Bracket:
1472 case HighlightingKind::Label:
1474 case HighlightingKind::InactiveCode:
1477 llvm_unreachable(
"unhandled HighlightingKind");
1482 case HighlightingModifier::Declaration:
1483 return "declaration";
1484 case HighlightingModifier::Definition:
1485 return "definition";
1486 case HighlightingModifier::Deprecated:
1487 return "deprecated";
1488 case HighlightingModifier::Readonly:
1490 case HighlightingModifier::Static:
1492 case HighlightingModifier::Deduced:
1494 case HighlightingModifier::Abstract:
1496 case HighlightingModifier::Virtual:
1498 case HighlightingModifier::DependentName:
1499 return "dependentName";
1500 case HighlightingModifier::DefaultLibrary:
1501 return "defaultLibrary";
1502 case HighlightingModifier::UsedAsMutableReference:
1503 return "usedAsMutableReference";
1504 case HighlightingModifier::UsedAsMutablePointer:
1505 return "usedAsMutablePointer";
1506 case HighlightingModifier::ConstructorOrDestructor:
1507 return "constructorOrDestructor";
1508 case HighlightingModifier::UserDefined:
1509 return "userDefined";
1510 case HighlightingModifier::FunctionScope:
1511 return "functionScope";
1512 case HighlightingModifier::ClassScope:
1513 return "classScope";
1514 case HighlightingModifier::FileScope:
1516 case HighlightingModifier::GlobalScope:
1517 return "globalScope";
1519 llvm_unreachable(
"unhandled HighlightingModifier");
1522std::vector<SemanticTokensEdit>
1524 llvm::ArrayRef<SemanticToken> New) {
1529 while (!Old.empty() && !New.empty() && Old.front() == New.front()) {
1531 Old = Old.drop_front();
1532 New = New.drop_front();
1534 while (!Old.empty() && !New.empty() && Old.back() == New.back()) {
1535 Old = Old.drop_back();
1536 New = New.drop_back();
1539 if (Old.empty() && New.empty())
1543 Edit.deleteTokens = Old.size();
1545 return {std::move(
Edit)};
1549 std::vector<Range> SkippedRanges(std::move(AST.getMacros().SkippedRanges));
1550 const auto &SM = AST.getSourceManager();
1551 StringRef MainCode = SM.getBufferOrFake(SM.getMainFileID()).getBuffer();
1552 std::vector<Range> InactiveRegions;
1553 for (
const Range &Skipped : SkippedRanges) {
1554 Range Inactive = Skipped;
1572 if (
auto EndOfLine = endOfLine(MainCode, Inactive.
end.
line)) {
1573 Inactive.
end = *EndOfLine;
1575 elog(
"Failed to determine end of line: {0}", EndOfLine.takeError());
1578 InactiveRegions.push_back(Inactive);
1580 return InactiveRegions;
const FunctionDecl * Decl
llvm::SmallString< 256U > Name
CodeCompletionBuilder Builder
CompiledFragmentImpl & Out
CharSourceRange Range
SourceRange for the file name.
const google::protobuf::Message & M
llvm::raw_string_ostream OS
std::vector< const NamedDecl * > resolveUsingValueDecl(const UnresolvedUsingValueDecl *UUVD) const
Stores and provides access to parsed AST.
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)
llvm::StringRef toSemanticTokenType(HighlightingKind Kind)
size_t lspLength(llvm::StringRef Code)
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)
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.
llvm::Expected< size_t > positionToOffset(llvm::StringRef Code, Position P, bool AllowColumnsBeyondLineLength)
Turn a [line, column] pair into an offset in Code.
bool operator<(const Ref &L, const Ref &R)
@ Type
An inlay hint that for a type annotation.
std::vector< Range > getInactiveRegions(ParsedAST &AST)
void elog(const char *Fmt, Ts &&... Vals)
@ Underlying
This is the underlying declaration for a renaming-alias, decltype etc.
@ ConstructorOrDestructor
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
static const Config & current()
Returns the Config of the current Context, or an empty configuration.
A set of edits generated for a single file.
int line
Line position in a document (zero-based).
int character
Character offset on a line in a document (zero-based).
Position start
The range's start position.
Position end
The range's end position.
Information about a reference written in the source code, independent of the actual AST node that thi...
bool IsDecl
True if the reference is a declaration or definition;.
llvm::SmallVector< const NamedDecl *, 1 > Targets
A list of targets referenced by this name.
Specifies a single semantic token in the document.
Describes a replacement of a contiguous range of semanticTokens.