From d55fb3d6d2f4471d5d56aebb921311b91c22136e Mon Sep 17 00:00:00 2001 From: ykiko Date: Mon, 4 May 2026 16:22:29 +0800 Subject: [PATCH 1/3] refactor(hover): fix doxygen rendering and rewrite Markup (formerly StructedText) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Parse documentation through strip_doxygen_info() to render \param, \return, \brief and other doxygen commands as structured markdown instead of raw text - Fix markdown block separation: add newline between blocks so paragraphs, bullet lists, and code blocks no longer merge on the same line - Fix CodeBlock closing fence not on its own line when code lacks trailing newline - Fix Heading::clone() slicing to Paragraph (lost heading level on copy) - Fix BulletList multi-line items missing continuation indentation - Fix double backtick in hover heading (name wrapped manually + InlineCode) - Rename StructedText → Markup, fix Strikethough → Strikethrough typo - Add DoxygenInfo::get_param_command_comments() for param iteration - Rewrite Markup tests from 3 assertion-less smoke tests to 27 proper tests - Add 6 doxygen-specific hover tests Co-Authored-By: Claude Opus 4.6 --- src/feature/hover.cpp | 983 +++++++++++++++++- src/support/doxygen.cpp | 9 + src/support/doxygen.h | 3 + src/support/{structed_text.cpp => markup.cpp} | 76 +- src/support/{structed_text.h => markup.h} | 26 +- tests/unit/feature/hover_tests.cpp | 940 +++++++++++++++-- tests/unit/support/markup_tests.cpp | 248 +++++ tests/unit/support/structed_text_tests.cpp | 121 --- 8 files changed, 2116 insertions(+), 290 deletions(-) rename src/support/{structed_text.cpp => markup.cpp} (74%) rename src/support/{structed_text.h => markup.h} (79%) create mode 100644 tests/unit/support/markup_tests.cpp delete mode 100644 tests/unit/support/structed_text_tests.cpp diff --git a/src/feature/hover.cpp b/src/feature/hover.cpp index 8c52d6a910..5f4e0f537a 100644 --- a/src/feature/hover.cpp +++ b/src/feature/hover.cpp @@ -1,19 +1,73 @@ +// Hover information for C++ symbols. +// Logic adapted from clangd's Hover.cpp (llvm-project/clang-tools-extra/clangd/Hover.cpp). + +#include #include #include #include +#include #include "feature/feature.h" #include "semantic/ast_utility.h" #include "semantic/selection.h" #include "semantic/symbol_kind.h" +#include "support/doxygen.h" +#include "support/markup.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/Support/Casting.h" +#include "llvm/Support/Format.h" +#include "llvm/Support/ScopedPrinter.h" +#include "llvm/Support/raw_ostream.h" +#include "clang/AST/ASTContext.h" +#include "clang/AST/ASTDiagnostic.h" #include "clang/AST/Decl.h" +#include "clang/AST/DeclCXX.h" +#include "clang/AST/DeclTemplate.h" #include "clang/AST/Expr.h" +#include "clang/AST/ExprCXX.h" +#include "clang/AST/PrettyPrinter.h" +#include "clang/AST/RecordLayout.h" +#include "clang/AST/RecursiveASTVisitor.h" +#include "clang/AST/Type.h" +#include "clang/Basic/Specifiers.h" +#include "clang/Lex/Lexer.h" namespace clice::feature { namespace { +struct PrintedType { + std::string type; + std::optional aka; +}; + +struct Param { + std::optional type; + std::optional name; + std::optional default_value; +}; + +struct HoverInfo { + std::optional namespace_scope; + std::string local_scope; + std::string name; + SymbolKind kind = SymbolKind::Invalid; + std::string documentation; + std::string definition; + std::string access_specifier; + std::optional type; + std::optional return_type; + std::optional> parameters; + std::optional> template_parameters; + std::optional value; + std::optional size; + std::optional offset; + std::optional padding; + std::optional align; +}; + auto symbol_name(SymbolKind kind) -> llvm::StringRef { switch(kind) { case SymbolKind::Module: return "module"; @@ -35,19 +89,734 @@ auto symbol_name(SymbolKind kind) -> llvm::StringRef { } } -auto hover_markdown(const clang::NamedDecl& decl) -> std::string { - auto kind = SymbolKind::from(&decl); - auto name = ast::name_of(&decl); - return std::format("{}: {}", symbol_name(kind), name); +auto get_printing_policy(clang::ASTContext& ctx) -> clang::PrintingPolicy { + clang::PrintingPolicy pp(ctx.getPrintingPolicy()); + pp.SuppressScope = true; + pp.AnonymousTagLocations = false; + pp.PolishForDeclaration = true; + pp.ConstantsAsWritten = true; + pp.SuppressTemplateArgsInCXXConstructors = true; + pp.SuppressDefaultTemplateArgs = true; + return pp; +} + +auto get_namespace_scope(const clang::Decl* D) -> std::string { + const clang::DeclContext* DC = D->getDeclContext(); + + if(const auto* TD = llvm::dyn_cast(DC)) + return get_namespace_scope(TD); + if(const auto* FD = llvm::dyn_cast(DC)) + return get_namespace_scope(FD); + if(const auto* NSD = llvm::dyn_cast(DC)) { + if(NSD->isInline() || NSD->isAnonymousNamespace()) + return get_namespace_scope(NSD); + } + if(const auto* ND = llvm::dyn_cast(DC)) { + std::string result; + llvm::raw_string_ostream os(result); + ND->printQualifiedName(os); + return result; + } + + return ""; +} + +auto get_local_scope(const clang::Decl* D) -> std::string { + std::vector scopes; + const clang::DeclContext* DC = D->getDeclContext(); + + auto get_name = [](const clang::TypeDecl* TD) -> std::string { + if(!TD->getDeclName().isEmpty()) { + clang::PrintingPolicy policy = TD->getASTContext().getPrintingPolicy(); + policy.SuppressScope = true; + return clang::QualType(TD->getTypeForDecl(), 0).getAsString(policy); + } + if(auto* RD = llvm::dyn_cast(TD)) + return std::format("(anonymous {})", RD->getKindName().str()); + return ""; + }; + + while(DC) { + if(const auto* TD = llvm::dyn_cast(DC)) + scopes.push_back(get_name(TD)); + else if(const auto* FD = llvm::dyn_cast(DC)) + scopes.push_back(FD->getNameAsString()); + DC = DC->getParent(); + } + + std::string result; + for(auto it = scopes.rbegin(); it != scopes.rend(); ++it) { + if(!it->empty()) { + result += *it; + result += "::"; + } + } + return result; +} + +auto print_definition(const clang::Decl* D, clang::PrintingPolicy pp, CompilationUnitRef unit) + -> std::string { + if(auto* VD = llvm::dyn_cast(D)) { + if(auto* IE = VD->getInit()) { + if(200 < unit.expanded_tokens(IE->getSourceRange()).size()) + pp.SuppressInitializers = true; + } + } + std::string definition; + llvm::raw_string_ostream os(definition); + D->print(os, pp); + return definition; +} + +auto print_type(clang::QualType QT, + clang::ASTContext& ctx, + const clang::PrintingPolicy& pp, + bool show_aka) -> PrintedType { + while(!QT.isNull() && QT->isDecltypeType()) + QT = QT->castAs()->getUnderlyingType(); + + PrintedType result; + llvm::raw_string_ostream os(result.type); + + if(!QT.isNull() && !QT.hasQualifiers() && pp.SuppressTagKeyword) { + if(auto* TT = llvm::dyn_cast(QT.getTypePtr())) + os << TT->getDecl()->getKindName() << " "; + } + QT.print(os, pp); + + if(!QT.isNull() && show_aka) { + bool should_aka = false; + clang::QualType desugared = clang::desugarForDiagnostic(ctx, QT, should_aka); + if(should_aka) + result.aka = desugared.getAsString(pp); + } + + return result; +} + +auto print_type(const clang::TemplateTypeParmDecl* TTP) -> PrintedType { + PrintedType result; + result.type = TTP->wasDeclaredWithTypename() ? "typename" : "class"; + if(TTP->isParameterPack()) + result.type += "..."; + return result; +} + +auto print_type(const clang::NonTypeTemplateParmDecl* NTTP, + const clang::PrintingPolicy& pp, + bool show_aka) -> PrintedType { + auto result = print_type(NTTP->getType(), NTTP->getASTContext(), pp, show_aka); + if(NTTP->isParameterPack()) { + result.type += "..."; + if(result.aka) + *result.aka += "..."; + } + return result; +} + +auto print_type(const clang::TemplateTemplateParmDecl* TTP, + const clang::PrintingPolicy& pp, + bool show_aka) -> PrintedType { + PrintedType result; + llvm::raw_string_ostream os(result.type); + os << "template <"; + llvm::StringRef sep = ""; + for(const clang::Decl* param: *TTP->getTemplateParameters()) { + os << sep; + sep = ", "; + if(const auto* ttp = llvm::dyn_cast(param)) + os << print_type(ttp).type; + else if(const auto* nttp = llvm::dyn_cast(param)) + os << print_type(nttp, pp, show_aka).type; + else if(const auto* ttpd = llvm::dyn_cast(param)) + os << print_type(ttpd, pp, show_aka).type; + } + os << "> class"; + return result; +} + +auto fetch_template_parameters(const clang::TemplateParameterList* params, + const clang::PrintingPolicy& pp, + bool show_aka) -> std::vector { + std::vector result; + + for(const clang::Decl* param: *params) { + Param p; + if(const auto* TTP = llvm::dyn_cast(param)) { + p.type = print_type(TTP); + if(!TTP->getName().empty()) + p.name = TTP->getNameAsString(); + if(TTP->hasDefaultArgument()) { + p.default_value.emplace(); + llvm::raw_string_ostream os(*p.default_value); + TTP->getDefaultArgument().getArgument().print(pp, os, false); + } + } else if(const auto* NTTP = llvm::dyn_cast(param)) { + p.type = print_type(NTTP, pp, show_aka); + if(clang::IdentifierInfo* II = NTTP->getIdentifier()) + p.name = II->getName().str(); + if(NTTP->hasDefaultArgument()) { + p.default_value.emplace(); + llvm::raw_string_ostream os(*p.default_value); + NTTP->getDefaultArgument().getArgument().print(pp, os, false); + } + } else if(const auto* TTPD = llvm::dyn_cast(param)) { + p.type = print_type(TTPD, pp, show_aka); + if(!TTPD->getName().empty()) + p.name = TTPD->getNameAsString(); + if(TTPD->hasDefaultArgument()) { + p.default_value.emplace(); + llvm::raw_string_ostream os(*p.default_value); + TTPD->getDefaultArgument().getArgument().print(pp, os, false); + } + } + result.push_back(std::move(p)); + } + + return result; +} + +auto get_default_arg(const clang::ParmVarDecl* PVD) -> const clang::Expr* { + if(!PVD->hasDefaultArg() || PVD->hasUnparsedDefaultArg()) + return nullptr; + return PVD->hasUninstantiatedDefaultArg() ? PVD->getUninstantiatedDefaultArg() + : PVD->getDefaultArg(); +} + +auto to_param(const clang::ParmVarDecl* PVD, const clang::PrintingPolicy& pp, bool show_aka) + -> Param { + Param out; + out.type = print_type(PVD->getType(), PVD->getASTContext(), pp, show_aka); + if(!PVD->getName().empty()) + out.name = PVD->getNameAsString(); + if(const clang::Expr* def_arg = get_default_arg(PVD)) { + out.default_value.emplace(); + llvm::raw_string_ostream os(*out.default_value); + def_arg->printPretty(os, nullptr, pp); + } + return out; +} + +auto get_underlying_function(const clang::Decl* D) -> const clang::FunctionDecl* { + if(const auto* VD = llvm::dyn_cast(D)) { + auto QT = VD->getType(); + if(!QT.isNull()) { + while(!QT->getPointeeType().isNull()) + QT = QT->getPointeeType(); + if(const auto* CD = QT->getAsCXXRecordDecl()) + return CD->getLambdaCallOperator(); + } + } + return D->getAsFunction(); +} + +void fill_function_type_and_params(HoverInfo& hi, + const clang::Decl* D, + const clang::FunctionDecl* FD, + const clang::PrintingPolicy& pp, + bool show_aka) { + hi.parameters.emplace(); + for(const clang::ParmVarDecl* PVD: FD->parameters()) + hi.parameters->emplace_back(to_param(PVD, pp, show_aka)); + + auto NK = FD->getDeclName().getNameKind(); + if(NK == clang::DeclarationName::CXXConstructorName || + NK == clang::DeclarationName::CXXDestructorName || + NK == clang::DeclarationName::CXXConversionFunctionName) + return; + + hi.return_type = print_type(FD->getReturnType(), FD->getASTContext(), pp, show_aka); + clang::QualType QT = FD->getType(); + if(const auto* VD = llvm::dyn_cast(D)) + QT = VD->getType().getDesugaredType(D->getASTContext()); + hi.type = print_type(QT, D->getASTContext(), pp, show_aka); +} + +auto print_hex(const llvm::APSInt& V) -> llvm::FormattedNumber { + uint64_t bits = V.getBitWidth() > 64 ? V.trunc(64).getZExtValue() : V.getZExtValue(); + if(V.isNegative() && V.getSignificantBits() <= 32) + return llvm::format_hex(uint32_t(bits), 0); + return llvm::format_hex(bits, 0); +} + +auto print_expr_value(const clang::Expr* E, const clang::ASTContext& ctx) + -> std::optional { + if(const auto* ILE = llvm::dyn_cast(E)) { + if(!ILE->isSemanticForm()) + E = ILE->getSemanticForm(); + } + + clang::QualType T = E->getType(); + if(T.isNull() || T->isFunctionType() || T->isFunctionPointerType() || + T->isFunctionReferenceType() || T->isVoidType()) + return std::nullopt; + + clang::Expr::EvalResult constant; + if(E->isValueDependent() || !E->EvaluateAsRValue(constant, ctx) || constant.Val.isStruct() || + constant.Val.isUnion()) + return std::nullopt; + + if(T->isEnumeralType() && constant.Val.isInt() && + constant.Val.getInt().getSignificantBits() <= 64) { + int64_t val = constant.Val.getInt().getExtValue(); + for(const clang::EnumConstantDecl* ECD: + T->castAs()->getDecl()->enumerators()) { + if(ECD->getInitVal() == val) { + std::string result; + llvm::raw_string_ostream os(result); + os << ECD->getNameAsString() << " (" << print_hex(constant.Val.getInt()) << ")"; + return result; + } + } + } + + if(T->isIntegralOrEnumerationType() && constant.Val.isInt() && + constant.Val.getInt().getSignificantBits() <= 64 && constant.Val.getInt().uge(10)) { + std::string result; + llvm::raw_string_ostream os(result); + os << constant.Val.getAsString(ctx, T) << " (" << print_hex(constant.Val.getInt()) << ")"; + return result; + } + + return constant.Val.getAsString(ctx, T); +} + +auto get_decl_for_comment(const clang::NamedDecl* D) -> const clang::NamedDecl* { + const clang::NamedDecl* result = D; + if(const auto* TSD = llvm::dyn_cast(D)) { + if(TSD->getTemplateSpecializationKind() == clang::TSK_Undeclared) + result = TSD->getSpecializedTemplate(); + else if(const auto* TIP = TSD->getTemplateInstantiationPattern()) + result = TIP; + } else if(const auto* TSD = llvm::dyn_cast(D)) { + if(TSD->getTemplateSpecializationKind() == clang::TSK_Undeclared) + result = TSD->getSpecializedTemplate(); + else if(const auto* TIP = TSD->getTemplateInstantiationPattern()) + result = TIP; + } else if(const auto* FD = D->getAsFunction()) { + if(const auto* TIP = FD->getTemplateInstantiationPattern()) + result = TIP; + } + if(D != result) + result = get_decl_for_comment(result); + return result; +} + +auto get_documentation(const clang::NamedDecl* D, clang::ASTContext& ctx) -> std::string { + const clang::NamedDecl* comment_decl = get_decl_for_comment(D); + const clang::RawComment* raw = ctx.getRawCommentForDeclNoCache(comment_decl); + if(!raw) + return ""; + return raw->getFormattedText(ctx.getSourceManager(), ctx.getDiagnostics()); +} + +void add_layout_info(const clang::NamedDecl& ND, HoverInfo& hi) { + if(ND.isInvalidDecl()) + return; + + const auto& ctx = ND.getASTContext(); + + if(auto* RD = llvm::dyn_cast(&ND)) { + if(auto size = ctx.getTypeSizeInCharsIfKnown(RD->getTypeForDecl())) + hi.size = size->getQuantity() * 8; + if(!RD->isDependentType() && RD->isCompleteDefinition()) + hi.align = ctx.getTypeAlign(RD->getTypeForDecl()); + return; + } + + if(const auto* FD = llvm::dyn_cast(&ND)) { + const auto* record = FD->getParent(); + if(record) + record = record->getDefinition(); + if(record && !record->isInvalidDecl() && !record->isDependentType()) { + hi.align = ctx.getTypeAlign(FD->getType()); + const clang::ASTRecordLayout& layout = ctx.getASTRecordLayout(record); + hi.offset = layout.getFieldOffset(FD->getFieldIndex()); + if(FD->isBitField()) + hi.size = FD->getBitWidthValue(); + else if(auto size = ctx.getTypeSizeInCharsIfKnown(FD->getType())) + hi.size = FD->isZeroSize(ctx) ? 0 : size->getQuantity() * 8; + if(hi.size) { + unsigned end_of_field = *hi.offset + *hi.size; + if(!record->isUnion() && FD->getFieldIndex() + 1 < layout.getFieldCount()) { + unsigned next_offset = layout.getFieldOffset(FD->getFieldIndex() + 1); + if(next_offset >= end_of_field) + hi.padding = next_offset - end_of_field; + } else { + hi.padding = layout.getSize().getQuantity() * 8 - end_of_field; + } + } + if(record->isUnion()) + hi.offset.reset(); + } + } +} + +auto hover_decl(const clang::NamedDecl* D, + CompilationUnitRef unit, + const clang::PrintingPolicy& pp, + const HoverOptions& options) -> HoverInfo { + HoverInfo hi; + auto& ctx = D->getASTContext(); + + hi.access_specifier = clang::getAccessSpelling(D->getAccess()).str(); + hi.namespace_scope = get_namespace_scope(D); + if(!hi.namespace_scope->empty()) + hi.namespace_scope->append("::"); + hi.local_scope = get_local_scope(D); + if(!hi.local_scope.empty()) + hi.local_scope.append("::"); + + hi.name = ast::name_of(D); + hi.documentation = get_documentation(D, ctx); + hi.kind = SymbolKind::from(D); + + if(const clang::TemplateDecl* TD = D->getDescribedTemplate()) { + hi.template_parameters = + fetch_template_parameters(TD->getTemplateParameters(), pp, options.show_aka); + D = TD; + } else if(const clang::FunctionDecl* FD = D->getAsFunction()) { + if(const auto* FTD = FD->getDescribedTemplate()) { + hi.template_parameters = + fetch_template_parameters(FTD->getTemplateParameters(), pp, options.show_aka); + D = FTD; + } + } + + if(const clang::FunctionDecl* FD = get_underlying_function(D)) + fill_function_type_and_params(hi, D, FD, pp, options.show_aka); + else if(const auto* VD = llvm::dyn_cast(D)) + hi.type = print_type(VD->getType(), ctx, pp, options.show_aka); + else if(const auto* TTP = llvm::dyn_cast(D)) + hi.type = PrintedType{TTP->wasDeclaredWithTypename() ? "typename" : "class"}; + else if(const auto* TTP = llvm::dyn_cast(D)) + hi.type = print_type(TTP, pp, options.show_aka); + else if(const auto* VT = llvm::dyn_cast(D)) + hi.type = print_type(VT->getTemplatedDecl()->getType(), ctx, pp, options.show_aka); + else if(const auto* TN = llvm::dyn_cast(D)) + hi.type = + print_type(TN->getUnderlyingType().getDesugaredType(ctx), ctx, pp, options.show_aka); + else if(const auto* TAT = llvm::dyn_cast(D)) + hi.type = + print_type(TAT->getTemplatedDecl()->getUnderlyingType(), ctx, pp, options.show_aka); + + if(const auto* var = llvm::dyn_cast(D); var && !var->isInvalidDecl()) { + if(const clang::Expr* init = var->getInit()) + hi.value = print_expr_value(init, ctx); + } else if(const auto* ECD = llvm::dyn_cast(D)) { + if(!ECD->getType()->isDependentType()) + hi.value = llvm::toString(ECD->getInitVal(), 10); + } + + hi.definition = print_definition(D, pp, unit); + return hi; +} + +auto hover_macro(CompilationUnitRef unit, clang::SourceLocation loc) -> std::optional { + auto fid = unit.interested_file(); + auto& directives = unit.directives(); + auto it = directives.find(fid); + if(it == directives.end()) + return std::nullopt; + + auto offset = unit.file_offset(loc); + + const MacroRef* found = nullptr; + for(auto& macro: it->second.macros) { + if(macro.kind != MacroRef::Ref && macro.kind != MacroRef::Def) + continue; + auto [macro_fid, macro_offset] = unit.decompose_location(macro.loc); + if(macro_fid != fid) + continue; + auto spelling = unit.token_spelling(macro.loc); + if(offset >= macro_offset && offset < macro_offset + spelling.size()) { + found = ¯o; + break; + } + } + + if(!found) + return std::nullopt; + + HoverInfo hi; + hi.name = unit.token_spelling(found->loc).str(); + hi.kind = SymbolKind::Macro; + + const clang::MacroInfo* MI = found->macro; + if(!MI) + return hi; + + auto& SM = unit.context().getSourceManager(); + clang::SourceLocation start_loc = MI->getDefinitionLoc(); + clang::SourceLocation end_loc = MI->getDefinitionEndLoc(); + + if(SM.getPresumedLoc(end_loc, false).isValid()) { + end_loc = clang::Lexer::getLocForEndOfToken(end_loc, 0, SM, unit.lang_options()); + bool invalid = false; + llvm::StringRef buffer = SM.getBufferData(SM.getFileID(start_loc), &invalid); + if(!invalid) { + unsigned start_offset = SM.getFileOffset(start_loc); + unsigned end_offset = SM.getFileOffset(end_loc); + if(end_offset <= buffer.size() && start_offset < end_offset) + hi.definition = + ("#define " + buffer.substr(start_offset, end_offset - start_offset)).str(); + } + } + + return hi; +} + +auto type_as_definition(const PrintedType& ptype) -> std::string { + std::string result; + llvm::raw_string_ostream os(result); + os << ptype.type; + if(ptype.aka) + os << " // aka: " << *ptype.aka; + return result; +} + +auto hover_this_expr(const clang::CXXThisExpr* CTE, + clang::ASTContext& ctx, + const clang::PrintingPolicy& pp, + bool show_aka) -> HoverInfo { + clang::QualType origin_type = CTE->getType()->getPointeeType(); + clang::QualType class_type = clang::QualType(origin_type->getAsTagDecl()->getTypeForDecl(), 0); + clang::QualType pretty_type = ctx.getPointerType( + clang::QualType(class_type.getTypePtr(), origin_type.getCVRQualifiers())); + + HoverInfo hi; + hi.name = "this"; + hi.definition = type_as_definition(print_type(pretty_type, ctx, pp, show_aka)); + return hi; +} + +auto hover_deduced_type(clang::QualType QT, + const clang::syntax::Token& tok, + clang::ASTContext& ctx, + const clang::PrintingPolicy& pp, + bool show_aka) -> HoverInfo { + HoverInfo hi; + hi.name = clang::tok::getTokenName(tok.kind()); + hi.kind = SymbolKind::Type; + + if(QT->isUndeducedAutoType()) { + hi.definition = "/* not deduced */"; + } else { + hi.definition = type_as_definition(print_type(QT, ctx, pp, show_aka)); + if(const auto* D = QT->getAsTagDecl()) { + const auto* comment_decl = get_decl_for_comment(D); + hi.documentation = get_documentation(comment_decl, ctx); + } + } + + return hi; +} + +auto format_size(std::uint64_t size_in_bits) -> std::string { + std::uint64_t value = size_in_bits % 8 == 0 ? size_in_bits / 8 : size_in_bits; + const char* unit = value != 0 && value == size_in_bits ? "bit" : "byte"; + return std::format("{} {}{}", value, unit, value == 1 ? "" : "s"); +} + +auto format_offset(std::uint64_t offset_in_bits) -> std::string { + auto bytes = offset_in_bits / 8; + auto bits = offset_in_bits % 8; + auto result = format_size(bytes * 8); + if(bits != 0) + result += " and " + format_size(bits); + return result; +} + +auto format_param(const Param& p) -> std::string { + std::string result; + if(p.type) + result += p.type->type; + if(p.name) { + if(!result.empty()) + result += " "; + result += *p.name; + } + if(p.default_value) { + result += " = "; + result += *p.default_value; + } + return result; +} + +auto present(const HoverInfo& hi) -> std::string { + Markup output; + + Paragraph& header = output.add_heading(3); + if(hi.kind != SymbolKind::Invalid) + header.append_text(symbol_name(hi.kind).str()) + .append_text(hi.name, Paragraph::Kind::InlineCode); + else + header.append_text(hi.name, Paragraph::Kind::InlineCode); + + output.add_ruler(); + + if(hi.return_type) { + std::string ret_str = hi.return_type->type; + if(hi.return_type->aka) + ret_str += " (aka " + *hi.return_type->aka + ")"; + output.add_paragraph() + .append_text("\xe2\x86\x92") + .append_text(ret_str, Paragraph::Kind::InlineCode); + } + + if(hi.parameters && !hi.parameters->empty()) { + output.add_paragraph().append_text("Parameters:"); + auto& list = output.add_bullet_list(); + for(auto& param: *hi.parameters) + list.add_item().add_paragraph().append_text(format_param(param), + Paragraph::Kind::InlineCode); + } + + if(hi.type && !hi.return_type && !hi.parameters) { + std::string type_str = hi.type->type; + if(hi.type->aka) + type_str += " (aka " + *hi.type->aka + ")"; + output.add_paragraph().append_text("Type:").append_text(type_str, + Paragraph::Kind::InlineCode); + } + + if(hi.value) + output.add_paragraph().append_text("Value =").append_text(*hi.value, + Paragraph::Kind::InlineCode); + + if(hi.offset) + output.add_paragraph().append_text("Offset: " + format_offset(*hi.offset)); + + if(hi.size) { + std::string size_text = "Size: " + format_size(*hi.size); + if(hi.padding && *hi.padding != 0) + size_text += std::format(" (+{} padding)", format_size(*hi.padding)); + if(hi.align) + size_text += ", alignment " + format_size(*hi.align); + output.add_paragraph().append_text(size_text); + } + + if(!hi.documentation.empty()) { + output.add_ruler(); + auto [doxygen, rest] = strip_doxygen_info(hi.documentation); + + std::string doc; + + for(auto& [tag, contents]: doxygen.get_block_command_comments()) { + if(tag == "brief") { + for(auto& c: contents) { + auto text = llvm::StringRef(c.content).trim(); + if(!text.empty()) { + doc += text; + doc += "\n\n"; + } + } + } + } + + auto trimmed = llvm::StringRef(rest).trim(); + if(!trimmed.empty()) { + doc += trimmed; + doc += "\n\n"; + } + + auto param_docs = doxygen.get_param_command_comments(); + if(!param_docs.empty()) { + bool rendered = false; + if(hi.parameters && !hi.parameters->empty()) { + for(auto& param: *hi.parameters) { + if(!param.name) + continue; + auto info = doxygen.find_param_info(*param.name); + if(!info) + continue; + auto content = llvm::StringRef((*info)->content).trim(); + doc += "- `"; + doc += *param.name; + doc += "`"; + if(!content.empty()) { + doc += " — "; + doc += content; + } + doc += "\n"; + rendered = true; + } + } + if(!rendered) { + for(auto& [name, info]: param_docs) { + auto content = llvm::StringRef(info->content).trim(); + doc += "- `"; + doc += name; + doc += "`"; + if(!content.empty()) { + doc += " — "; + doc += content; + } + doc += "\n"; + } + } + doc += "\n"; + } + + if(auto ret = doxygen.get_return_info()) { + auto text = ret->trim(); + if(!text.empty()) { + doc += "**Returns:** "; + doc += text; + doc += "\n\n"; + } + } + + for(auto& [tag, contents]: doxygen.get_block_command_comments()) { + if(tag == "brief") + continue; + std::string label = tag.str(); + if(!label.empty()) + label[0] = std::toupper(label[0]); + for(auto& c: contents) { + auto text = llvm::StringRef(c.content).trim(); + if(!text.empty()) { + doc += "**"; + doc += label; + doc += ":** "; + doc += text; + doc += "\n\n"; + } + } + } + + auto final_doc = llvm::StringRef(doc).trim(); + if(!final_doc.empty()) + output.add_paragraph().append_text(final_doc.str()); + } + + if(!hi.definition.empty()) { + output.add_ruler(); + + std::string code; + if(!hi.local_scope.empty()) { + code += "// In " + llvm::StringRef(hi.local_scope).rtrim(':').str() + '\n'; + } else if(hi.namespace_scope && !hi.namespace_scope->empty()) { + code += + "// In namespace " + llvm::StringRef(*hi.namespace_scope).rtrim(':').str() + '\n'; + } + + if(!hi.access_specifier.empty()) + code += hi.access_specifier + ": "; + + code += hi.definition; + output.add_code_block(std::move(code), "cpp"); + } + + return output.as_markdown(); } auto hover_range(CompilationUnitRef unit, const clang::NamedDecl& decl, const PositionMapper& converter) -> std::optional { auto [fid, range] = unit.decompose_expansion_range(decl.getSourceRange()); - if(fid != unit.interested_file() || !range.valid()) { + if(fid != unit.interested_file() || !range.valid()) return std::nullopt; - } return protocol::Range{ .start = *converter.to_position(range.begin), @@ -55,21 +824,90 @@ auto hover_range(CompilationUnitRef unit, }; } -auto build_hover(CompilationUnitRef unit, const clang::NamedDecl& decl, PositionEncoding encoding) - -> protocol::Hover { - PositionMapper converter(unit.interested_content(), encoding); +auto get_deduced_type(clang::ASTContext& ctx, clang::SourceLocation loc) + -> std::optional { + if(!loc.isValid()) + return std::nullopt; + + struct DeducedTypeVisitor : clang::RecursiveASTVisitor { + clang::SourceLocation searched; + clang::QualType deduced; + + DeducedTypeVisitor(clang::SourceLocation loc) : searched(loc) {} + + bool VisitVarDecl(clang::VarDecl* D) { + if(auto* TSI = D->getTypeSourceInfo()) { + if(auto ATPTL = TSI->getTypeLoc().getAs()) { + if(ATPTL.getNameLoc() != searched) + return true; + } + } + if(auto* AT = D->getType()->getContainedAutoType()) { + deduced = AT->desugar(); + } + return true; + } + + bool VisitFunctionDecl(clang::FunctionDecl* D) { + if(!D->getTypeSourceInfo()) + return true; + auto cur = D->getReturnTypeSourceRange().getBegin(); + if(cur.isInvalid() && llvm::isa(D)) + cur = D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); + if(cur.isInvalid()) + cur = D->getSourceRange().getBegin(); + if(cur != searched) + return true; - protocol::MarkupContent content{ - .kind = protocol::MarkupKind::Markdown, - .value = hover_markdown(decl), + const clang::AutoType* AT = D->getReturnType()->getContainedAutoType(); + if(AT && !AT->getDeducedType().isNull()) { + deduced = AT->getDeducedType(); + } else if(auto* DT = + llvm::dyn_cast(D->getReturnType().getTypePtr())) { + if(!DT->getUnderlyingType().isNull()) + deduced = DT->getUnderlyingType(); + } else if(!D->getReturnType().isNull()) { + deduced = D->getReturnType(); + } + return true; + } + + bool VisitDecltypeTypeLoc(clang::DecltypeTypeLoc TL) { + if(TL.getBeginLoc() != searched) + return true; + const clang::DecltypeType* DT = llvm::dyn_cast(TL.getTypePtr()); + while(DT && !DT->getUnderlyingType().isNull()) { + deduced = DT->getUnderlyingType(); + DT = llvm::dyn_cast(deduced.getTypePtr()); + } + return true; + } }; + DeducedTypeVisitor V(loc); + V.TraverseAST(ctx); + if(V.deduced.isNull()) + return std::nullopt; + return V.deduced; +} + +auto build_hover(const HoverInfo& hi, + CompilationUnitRef unit, + const clang::NamedDecl* decl, + PositionEncoding encoding) -> protocol::Hover { + PositionMapper converter(unit.interested_content(), encoding); + protocol::Hover result{ - .contents = content, + .contents = + protocol::MarkupContent{ + .kind = protocol::MarkupKind::Markdown, + .value = present(hi), + }, }; - if(auto range = hover_range(unit, decl, converter)) { - result.range = *range; + if(decl) { + if(auto range = hover_range(unit, *decl, converter)) + result.range = *range; } return result; @@ -79,34 +917,123 @@ auto build_hover(CompilationUnitRef unit, const clang::NamedDecl& decl, Position auto hover(CompilationUnitRef unit, const clang::NamedDecl* decl, - const HoverOptions&, + const HoverOptions& options, PositionEncoding encoding) -> std::optional { - if(!decl) { + if(!decl) return std::nullopt; - } - return build_hover(unit, *decl, encoding); + auto pp = get_printing_policy(unit.context()); + auto hi = hover_decl(decl, unit, pp, options); + add_layout_info(*decl, hi); + + return build_hover(hi, unit, decl, encoding); } auto hover(CompilationUnitRef unit, std::uint32_t offset, const HoverOptions& options, PositionEncoding encoding) -> std::optional { - auto tree = SelectionTree::create_right(unit, LocalSourceRange(offset, offset)); - auto* node = tree.common_ancestor(); - if(!node) { + auto& ctx = unit.context(); + auto pp = get_printing_policy(ctx); + + auto file_loc = unit.create_location(unit.interested_file(), offset); + auto tokens = unit.spelled_tokens_touch(file_loc); + + if(tokens.empty()) return std::nullopt; - } - if(const auto* decl = node->get()) { - return hover(unit, decl, options, encoding); + std::optional hi; + + for(const auto& tok: tokens) { + if(tok.kind() == clang::tok::identifier) { + if(auto macro_hover = hover_macro(unit, tok.location())) { + hi = std::move(*macro_hover); + break; + } + } else if(tok.kind() == clang::tok::kw_auto || tok.kind() == clang::tok::kw_decltype) { + if(auto deduced = get_deduced_type(ctx, tok.location())) { + hi = hover_deduced_type(*deduced, tok, ctx, pp, options.show_aka); + break; + } + return std::nullopt; + } } - if(const auto* ref = node->get()) { - return hover(unit, ref->getDecl(), options, encoding); + if(!hi) { + auto tree = SelectionTree::create_right(unit, LocalSourceRange(offset, offset)); + auto* node = tree.common_ancestor(); + if(!node) + return std::nullopt; + + const clang::NamedDecl* target_decl = nullptr; + + if(const auto* decl = node->get()) { + target_decl = decl; + } else if(const auto* ref = node->get()) { + target_decl = llvm::dyn_cast(ref->getDecl()); + } else if(const auto* member = node->get()) { + target_decl = member->getMemberDecl(); + } else if(const auto* ctor = node->get()) { + target_decl = ctor->getConstructor(); + } else if(const auto* TL = node->get()) { + if(auto* tag_type = TL->getType()->getAs()) + target_decl = tag_type->getDecl(); + else if(auto* tdn = TL->getType()->getAs()) + target_decl = tdn->getDecl(); + else if(auto* tspt = TL->getType()->getAs()) { + if(auto* TD = tspt->getTemplateName().getAsTemplateDecl()) + target_decl = TD; + } + } else if(const auto* overload = node->get()) { + if(overload->getNumDecls() == 1) + target_decl = *overload->decls_begin(); + } + + if(const auto* CTE = node->get()) { + hi = hover_this_expr(CTE, ctx, pp, options.show_aka); + } else if(target_decl) { + auto info = hover_decl(target_decl, unit, pp, options); + if(target_decl == node->get()) + add_layout_info(*target_decl, info); + if(!info.value) { + for(auto* N = node; N; N = N->parent) { + if(const clang::Expr* E = N->get()) { + if(!E->getType().isNull() && E->getType()->isVoidType()) + break; + if(auto val = print_expr_value(E, ctx)) { + info.value = std::move(val); + break; + } + } else if(N->get() || N->get()) { + break; + } + } + } + hi = std::move(info); + } else if(const clang::Expr* E = node->get()) { + if(auto val = print_expr_value(E, ctx)) { + HoverInfo expr_hi; + expr_hi.type = print_type(E->getType(), ctx, pp, options.show_aka); + expr_hi.value = std::move(val); + expr_hi.name = "expression"; + hi = std::move(expr_hi); + } + } } - return std::nullopt; + if(!hi) + return std::nullopt; + + PositionMapper converter(unit.interested_content(), encoding); + protocol::Hover result{ + .contents = + protocol::MarkupContent{ + .kind = protocol::MarkupKind::Markdown, + .value = present(*hi), + }, + }; + + return result; } } // namespace clice::feature diff --git a/src/support/doxygen.cpp b/src/support/doxygen.cpp index 1e87c741e7..df2b105e9a 100644 --- a/src/support/doxygen.cpp +++ b/src/support/doxygen.cpp @@ -51,6 +51,15 @@ std::vector> + DoxygenInfo::get_param_command_comments() const { + std::vector> res; + for(const auto& [name, info]: param_command_comments) { + res.emplace_back(name, &info); + } + return res; +} + /// Process inline commands, we only interested in `\b` (bold), `\e` (italic) and `\c` (inline code) /// /// \param line The line diff --git a/src/support/doxygen.h b/src/support/doxygen.h index 992afa4110..86ec661bc7 100644 --- a/src/support/doxygen.h +++ b/src/support/doxygen.h @@ -49,6 +49,9 @@ class DoxygenInfo { return doc_for_return; } + std::vector> + get_param_command_comments() const; + private: llvm::SmallDenseMap> block_command_comments; diff --git a/src/support/structed_text.cpp b/src/support/markup.cpp similarity index 74% rename from src/support/structed_text.cpp rename to src/support/markup.cpp index 9a4790f3b5..c5535417a3 100644 --- a/src/support/structed_text.cpp +++ b/src/support/markup.cpp @@ -1,4 +1,4 @@ -#include "support/structed_text.h" +#include "support/markup.h" #include #include @@ -25,22 +25,23 @@ std::unique_ptr BulletList::clone() const { void BulletList::render_markdown(llvm::raw_ostream& os) const { for(auto& item: items) { - os << "- " << item.as_markdown() << '\n'; + auto content = item.as_markdown(); + os << "- "; + for(size_t i = 0; i < content.size(); ++i) { + os << content[i]; + if(content[i] == '\n' && i + 1 < content.size()) + os << " "; + } + os << '\n'; } } -StructedText& BulletList::add_item() { +Markup& BulletList::add_item() { return items.emplace_back(); } -// Clangd inserts escape char '\' before '*', '-' and other markdown markers -// That causes markdown comments are escaped and cannot be rendered properly -// on editors -// We do nothing on it. All the left comments are regarded as markdown rather -// than plain text void Paragraph::render_markdown(llvm::raw_ostream& os) const { bool need_space = false; - bool has_chunks = false; for(auto& chunk: chunks) { if(chunk.space_ahead || need_space) { os << ' '; @@ -58,17 +59,15 @@ void Paragraph::render_markdown(llvm::raw_ostream& os) const { os << '`' << chunk.content << '`'; break; } - case Kind::Strikethough: { + case Kind::Strikethrough: { os << "~~" << chunk.content << "~~"; break; } default: { - // Kind::PlainText os << chunk.content; break; } } - has_chunks = true; need_space = chunk.space_after; } } @@ -76,7 +75,6 @@ void Paragraph::render_markdown(llvm::raw_ostream& os) const { Paragraph& Paragraph::append_text(std::string text, Kind kind) { if(kind == Kind::PlainText) { llvm::StringRef s{text}; - // s = s.trim(" \t\v\f\r"); if(s.empty()) { return *this; } @@ -112,6 +110,10 @@ class Heading : public Paragraph { Paragraph::render_markdown(os); } + std::unique_ptr clone() const override { + return std::make_unique(*this); + } + private: unsigned level; }; @@ -119,7 +121,7 @@ class Heading : public Paragraph { class Ruler : public Block { public: void render_markdown(llvm::raw_ostream& os) const override { - os << "\n---\n"; + os << "---\n"; } bool is_ruler() const override { @@ -134,7 +136,10 @@ class Ruler : public Block { class CodeBlock : public Block { public: void render_markdown(llvm::raw_ostream& os) const override { - os << "```" << lang << '\n' << code << "```\n"; + os << "```" << lang << '\n' << code; + if(!code.empty() && code.back() != '\n') + os << '\n'; + os << "```\n"; } std::unique_ptr clone() const override { @@ -160,60 +165,55 @@ static std::string render_blocks(llvm::ArrayRef> blocks) blocks = blocks.drop_back(blocks.end() - last.base()); bool last_block_was_ruler = true; - // render for(const auto& b: blocks) { if(b->is_ruler() && last_block_was_ruler) { continue; } last_block_was_ruler = b->is_ruler(); b->render_markdown(os); + os << '\n'; } - // Get rid of redundant empty lines introduced in plaintext while imitating - // padding in markdown. - std::string adjusted_result; - llvm::StringRef trimmed_text(os.str()); - trimmed_text = trimmed_text.trim(" \t\v\f\r"); - - llvm::copy_if(trimmed_text, - std::back_inserter(adjusted_result), - [&trimmed_text](const char& C) { - return !llvm::StringRef(trimmed_text.data(), &C - trimmed_text.data() + 1) - // We allow at most two newlines. - .ends_with("\n\n\n"); - }); - - return adjusted_result; + // Collapse runs of 3+ newlines down to 2 (one blank line max). + std::string result; + llvm::StringRef text(os.str()); + text = text.trim(); + + llvm::copy_if(text, std::back_inserter(result), [&text](const char& C) { + return !llvm::StringRef(text.data(), &C - text.data() + 1).ends_with("\n\n\n"); + }); + + return result; } -void StructedText::append(StructedText& other) { +void Markup::append(Markup& other) { std::move(other.blocks.begin(), other.blocks.end(), std::back_inserter(blocks)); } -Paragraph& StructedText::add_paragraph() { +Paragraph& Markup::add_paragraph() { blocks.emplace_back(std::make_unique()); return *static_cast(blocks.back().get()); } -void StructedText::add_ruler() { +void Markup::add_ruler() { blocks.push_back(std::make_unique()); } -void StructedText::add_code_block(std::string code, std::string lang) { +void Markup::add_code_block(std::string code, std::string lang) { blocks.emplace_back(std::make_unique(std::move(code), std::move(lang))); } -Paragraph& StructedText::add_heading(unsigned level) { +Paragraph& Markup::add_heading(unsigned level) { blocks.emplace_back(std::make_unique(level)); return *static_cast(blocks.back().get()); } -BulletList& StructedText::add_bullet_list() { +BulletList& Markup::add_bullet_list() { blocks.push_back(std::make_unique()); return *static_cast(blocks.back().get()); } -std::string StructedText::as_markdown() const { +std::string Markup::as_markdown() const { return render_blocks(blocks); } diff --git a/src/support/structed_text.h b/src/support/markup.h similarity index 79% rename from src/support/structed_text.h rename to src/support/markup.h index ab02c8e535..4edb845ab4 100644 --- a/src/support/structed_text.h +++ b/src/support/markup.h @@ -5,11 +5,11 @@ #include #include -#include "llvm/Support/raw_os_ostream.h" +#include "llvm/Support/raw_ostream.h" namespace clice { -/// Base class of structed text +/// Base class of markup blocks class Block { public: virtual void render_markdown(llvm::raw_ostream& os) const = 0; @@ -31,7 +31,7 @@ class Paragraph : public Block { Italic, PlainText, InlineCode, - Strikethough, + Strikethrough, }; void render_markdown(llvm::raw_ostream& os) const override; @@ -54,7 +54,7 @@ class Paragraph : public Block { std::vector chunks; }; -class StructedText; +class Markup; /// Allow nested structure class BulletList : public Block { @@ -65,23 +65,23 @@ class BulletList : public Block { std::unique_ptr clone() const override; - StructedText& add_item(); + Markup& add_item(); private: - std::vector items; + std::vector items; }; -class StructedText { +class Markup { public: - StructedText() = default; + Markup() = default; - StructedText(const StructedText& other) { + Markup(const Markup& other) { *this = other; } - StructedText(StructedText&&) = default; + Markup(Markup&&) = default; - StructedText& operator=(const StructedText& other) { + Markup& operator=(const Markup& other) { blocks.clear(); for(auto& b: other.blocks) { blocks.push_back(b->clone()); @@ -89,9 +89,9 @@ class StructedText { return *this; } - StructedText& operator=(StructedText&&) = default; + Markup& operator=(Markup&&) = default; - void append(StructedText& doc); + void append(Markup& doc); Paragraph& add_paragraph(); diff --git a/tests/unit/feature/hover_tests.cpp b/tests/unit/feature/hover_tests.cpp index ed36ce9468..0b7c73f1c1 100644 --- a/tests/unit/feature/hover_tests.cpp +++ b/tests/unit/feature/hover_tests.cpp @@ -1,4 +1,5 @@ #include +#include #include "test/test.h" #include "test/tester.h" @@ -24,11 +25,36 @@ void run(llvm::StringRef code) { result = feature::hover(*unit, offset, {}, feature::PositionEncoding::UTF8); } -void compile_only(llvm::StringRef code) { +void run_with_options(llvm::StringRef code, feature::HoverOptions options) { add_main("main.cpp", code); ASSERT_TRUE(compile()); + + auto points = nameless_points(); + ASSERT_EQ(points.size(), 1U); + auto offset = points[0]; + result = feature::hover(*unit, offset, options, feature::PositionEncoding::UTF8); } +llvm::StringRef content() { + return std::get(result->contents).value; +} + +void expect_contains(llvm::StringRef expected) { + ASSERT_TRUE(result.has_value()); + auto* mc = std::get_if(&result->contents); + ASSERT_TRUE(mc != nullptr); + EXPECT_NE(mc->value.find(expected.str()), std::string::npos); +} + +void expect_not_contains(llvm::StringRef unexpected) { + ASSERT_TRUE(result.has_value()); + auto* mc = std::get_if(&result->contents); + ASSERT_TRUE(mc != nullptr); + EXPECT_EQ(mc->value.find(unexpected.str()), std::string::npos); +} + +// === Basic Declarations === + TEST_CASE(Namespace) { run(R"cpp( namespace $A { @@ -36,9 +62,8 @@ namespace $A { )cpp"); ASSERT_TRUE(result.has_value()); - auto* content = std::get_if(&result->contents); - ASSERT_TRUE(content != nullptr); - ASSERT_TRUE(content->value.find("namespace") != std::string::npos); + expect_contains("namespace"); + expect_contains("`A`"); } TEST_CASE(FunctionReference) { @@ -48,142 +73,877 @@ int x = $foo(); )cpp"); ASSERT_TRUE(result.has_value()); - auto* content = std::get_if(&result->contents); - ASSERT_TRUE(content != nullptr); - ASSERT_TRUE(content->value.find("foo") != std::string::npos); + expect_contains("foo"); + expect_contains("int"); } -TEST_CASE(RecordScope) { - compile_only(R"cpp( -typedef struct A { - struct B { - struct C {}; +TEST_CASE(GlobalFunction) { + run(R"cpp( +int compute(int a, double b) { return 0; } +int x = $compute(1, 2.0); +)cpp"); + + expect_contains("function"); + expect_contains("`compute`"); + expect_contains("`int`"); + expect_contains("Parameters:"); + expect_contains("`int a`"); + expect_contains("`double b`"); +} + +TEST_CASE(MemberFunction) { + run(R"cpp( +struct Foo { + int $bar(int x) { return x; } +}; +)cpp"); + + expect_contains("method"); + expect_contains("`bar`"); + expect_contains("Parameters:"); + expect_contains("`int x`"); + expect_contains("// In Foo"); +} + +TEST_CASE(ConstructorDecl) { + run(R"cpp( +struct Widget { + Widget(int x, double y); +}; +void use() { $Widget w(1, 2.0); } +)cpp"); + + expect_contains("`Widget`"); + expect_contains("struct"); +} + +TEST_CASE(DestructorRef) { + run(R"cpp( +struct Widget { + ~Widget(); +}; +void use(Widget* p) { p->~$Widget(); } +)cpp"); + + ASSERT_TRUE(result.has_value()); + expect_contains("Widget"); +} + +TEST_CASE(OperatorOverload) { + run(R"cpp( +struct Vec { + int val; + Vec $operator+(const Vec& rhs) const { return {val + rhs.val}; } +}; +)cpp"); + + expect_contains("operator+"); + expect_contains("// In Vec"); +} + +TEST_CASE(GlobalVariable) { + run(R"cpp( +int $global_var = 42; +)cpp"); + + expect_contains("variable"); + expect_contains("`global_var`"); + expect_contains("Type:"); + expect_contains("`int`"); +} + +TEST_CASE(StaticMember) { + run(R"cpp( +struct Foo { + static int $count; +}; +int Foo::count = 0; +)cpp"); + + expect_contains("`count`"); + expect_contains("Type:"); + expect_contains("`int`"); + expect_contains("// In Foo"); +} + +TEST_CASE(ConstexprVariable) { + run(R"cpp( +constexpr int $magic = 42; +)cpp"); + + expect_contains("variable"); + expect_contains("`magic`"); + expect_contains("Value ="); + expect_contains("`42"); +} + +TEST_CASE(EnumMember) { + run(R"cpp( +enum Color { Red = 1, $Green = 2, Blue = 3 }; +)cpp"); + + expect_contains("enum member"); + expect_contains("`Green`"); + expect_contains("Value ="); + expect_contains("`2`"); +} + +TEST_CASE(TypedefAlias) { + run(R"cpp( +typedef unsigned long $ULong; +)cpp"); + + expect_contains("type"); + expect_contains("`ULong`"); +} + +TEST_CASE(UsingAlias) { + run(R"cpp( +using $Integer = int; +)cpp"); + + expect_contains("type"); + expect_contains("`Integer`"); +} + +// === Scope Display === + +TEST_CASE(NamespaceScope) { + run(R"cpp( +namespace foo { +namespace bar { + int $val = 0; +} +} +)cpp"); + + expect_contains("// In namespace foo::bar"); +} + +TEST_CASE(NestedClassScope) { + run(R"cpp( +struct Outer { + struct Inner { + int $field; }; +}; +)cpp"); + + expect_contains("// In Outer::Inner"); +} + +TEST_CASE(AnonymousNamespace) { + run(R"cpp( +namespace { + int $hidden = 0; +} +)cpp"); + + expect_contains("variable"); + expect_contains("`hidden`"); +} + +TEST_CASE(FunctionLocalScope) { + run(R"cpp( +void func() { + int $local = 10; +} +)cpp"); - struct { - struct D {}; - } _; -} T; + expect_contains("variable"); + expect_contains("`local`"); + expect_contains("// In func"); +} -struct FORWARD_STRUCT; -struct FORWARD_CLASS; +TEST_CASE(LambdaScope) { + run(R"cpp( +void outer() { + auto lam = [](int $x) { return x; }; +} +)cpp"); + + expect_contains("parameter"); + expect_contains("`x`"); +} -void f() { - struct X {}; - class Y {}; +// === Type Information === - struct { - struct Z {}; - } _; +TEST_CASE(PointerType) { + run(R"cpp( +int val = 0; +int* $ptr = &val; +)cpp"); + + expect_contains("Type:"); + expect_contains("int *"); } -namespace n1 { - namespace n2 { - struct NA { - struct NB {}; - }; - } +TEST_CASE(ReferenceType) { + run(R"cpp( +int val = 0; +int& $ref = val; +)cpp"); - namespace { - struct NC {}; - } + expect_contains("Type:"); + expect_contains("int &"); } -namespace out { - namespace in { - struct M { - int x; - double y; - char z; - T a, b; - }; - } +TEST_CASE(AutoDeduction) { + run(R"cpp( +$auto x = 42; +)cpp"); + + expect_contains("int"); +} + +TEST_CASE(DecltypeDeduction) { + run(R"cpp( +int i = 0; +$decltype(i) j = 1; +)cpp"); + + expect_contains("int"); } + +TEST_CASE(ShowAka) { + run(R"cpp( +typedef unsigned long MyType; +$MyType x = 0; )cpp"); + + ASSERT_TRUE(result.has_value()); + expect_contains("MyType"); +} + +TEST_CASE(DisableShowAka) { + feature::HoverOptions opts; + opts.show_aka = false; + run_with_options(R"cpp( +typedef unsigned long MyType; +$MyType x = 0; +)cpp", + opts); + + ASSERT_TRUE(result.has_value()); + expect_not_contains("aka"); +} + +// === Function Signatures === + +TEST_CASE(FunctionReturnType) { + run(R"cpp( +double $compute() { return 3.14; } +)cpp"); + + expect_contains("`double`"); +} + +TEST_CASE(FunctionParameters) { + run(R"cpp( +void $process(int count, const char* name, double ratio) {} +)cpp"); + + expect_contains("Parameters:"); + expect_contains("`int count`"); + expect_contains("`const char * name`"); + expect_contains("`double ratio`"); +} + +TEST_CASE(DefaultArguments) { + run(R"cpp( +void $init(int x = 10, int y = 20) {} +)cpp"); + + expect_contains("Parameters:"); + expect_contains("10"); + expect_contains("20"); +} + +TEST_CASE(TemplateFunction) { + run(R"cpp( +template +T $identity(T val) { return val; } +)cpp"); + + expect_contains("function"); + expect_contains("`identity`"); + expect_contains("template"); +} + +TEST_CASE(VariadicTemplate) { + run(R"cpp( +template +void $variadic(Args... args) {} +)cpp"); + + expect_contains("function"); + expect_contains("`variadic`"); +} + +// === Template Parameters === + +TEST_CASE(ClassTemplate) { + run(R"cpp( +template +struct $Container { T value; }; +)cpp"); + + expect_contains("struct"); + expect_contains("`Container`"); + expect_contains("template"); +} + +TEST_CASE(TemplateWithDefaults) { + run(R"cpp( +template +struct $MyVec {}; +)cpp"); + + expect_contains("struct"); + expect_contains("`MyVec`"); +} + +TEST_CASE(NonTypeTemplateParam) { + run(R"cpp( +template +struct $FixedArray { int data[N]; }; +)cpp"); + + expect_contains("struct"); + expect_contains("`FixedArray`"); + expect_contains("template"); +} + +// === Documentation === + +TEST_CASE(BasicComment) { + run(R"cpp( +/// This is documentation. +int $documented = 0; +)cpp"); + + expect_contains("This is documentation."); +} + +TEST_CASE(MultiLineComment) { + run(R"cpp( +/// First line. +/// Second line. +void $multi() {} +)cpp"); + + expect_contains("First line."); + expect_contains("Second line."); +} + +TEST_CASE(NoComment) { + run(R"cpp( +int $no_doc = 0; +)cpp"); + + ASSERT_TRUE(result.has_value()); + expect_contains("`no_doc`"); +} + +TEST_CASE(DoxygenParam) { + run(R"cpp( +/// \param x The first value. +/// \param y The second value. +void $add(int x, int y) {} +)cpp"); + + expect_contains("`x`"); + expect_contains("The first value."); + expect_contains("`y`"); + expect_contains("The second value."); + expect_not_contains("\\param"); +} + +TEST_CASE(DoxygenReturn) { + run(R"cpp( +/// \return The sum of a and b. +int $sum(int a, int b) { return a + b; } +)cpp"); + + expect_contains("**Returns:**"); + expect_contains("The sum of a and b."); + expect_not_contains("\\return"); } -TEST_CASE(EnumStyle) { - compile_only(R"cpp( -enum Free { - A = 1, - B = 2, - C = 999, +TEST_CASE(DoxygenBrief) { + run(R"cpp( +/// \brief A brief description. +/// +/// A detailed description. +void $func() {} +)cpp"); + + expect_contains("A brief description."); + expect_contains("A detailed description."); + expect_not_contains("\\brief"); +} + +TEST_CASE(DoxygenInlineCode) { + run(R"cpp( +/// Use \c nullptr for null values. +void $func() {} +)cpp"); + + expect_contains("`nullptr`"); + expect_not_contains("\\c"); +} + +TEST_CASE(DoxygenNote) { + run(R"cpp( +/// \note Thread safety is not guaranteed. +void $func() {} +)cpp"); + + expect_contains("**Note:**"); + expect_contains("Thread safety is not guaranteed."); + expect_not_contains("\\note"); +} + +TEST_CASE(DoxygenFull) { + run(R"cpp( +/// \brief Compute the sum. +/// +/// Adds two integers and returns the result. +/// +/// \param a The left operand. +/// \param b The right operand. +/// \return The sum. +int $add(int a, int b) { return a + b; } +)cpp"); + + expect_contains("Compute the sum."); + expect_contains("Adds two integers"); + expect_contains("`a`"); + expect_contains("The left operand."); + expect_contains("`b`"); + expect_contains("The right operand."); + expect_contains("**Returns:**"); + expect_contains("The sum."); + expect_not_contains("\\brief"); + expect_not_contains("\\param"); + expect_not_contains("\\return"); +} + +// === Layout Info === + +TEST_CASE(StructSize) { + run(R"cpp( +struct $Point { + double x; + double y; }; +)cpp"); + + expect_contains("Size:"); + expect_contains("alignment"); +} -enum class Scope: long { - A = -8, - B = 2, - C = 100, +TEST_CASE(FieldOffset) { + run(R"cpp( +struct Data { + int a; + int $b; }; )cpp"); + + expect_contains("field"); + expect_contains("`b`"); + expect_contains("Offset:"); + expect_contains("Size:"); } -TEST_CASE(FunctionStyle) { - compile_only(R"cpp( -typedef long long ll; +TEST_CASE(FieldPadding) { + run(R"cpp( +struct Padded { + char $c; + int i; +}; +)cpp"); + + expect_contains("Offset:"); + expect_contains("Size:"); + expect_contains("padding"); +} -ll f(int x, int y, ll z = 1) { return 0; } +TEST_CASE(BitField) { + run(R"cpp( +struct Flags { + unsigned int $flag : 3; +}; +)cpp"); -template -T t(T a, T b, int c, ll d, S s) { return a; } + expect_contains("field"); + expect_contains("`flag`"); + expect_contains("Size:"); + expect_contains("bit"); +} -namespace { - constexpr static const char* g() { return "hello"; } +TEST_CASE(UnionField) { + run(R"cpp( +union Variant { + int $i; + float f; +}; +)cpp"); + + expect_contains("field"); + expect_contains("`i`"); + expect_contains("Size:"); + // Union fields should NOT have offset + expect_not_contains("Offset:"); } -namespace test { - namespace { - [[deprecated("test deprecate message")]] consteval int h() { return 1; } - } +// === Macro Hover === + +TEST_CASE(ObjectMacro) { + run(R"cpp( +#define MY_CONST 42 +int x = $MY_CONST; +)cpp"); + + expect_contains("macro"); + expect_contains("`MY_CONST`"); + expect_contains("#define MY_CONST 42"); } -struct A { - constexpr static A m(int left, double right) { return A(); } +TEST_CASE(FunctionMacro) { + run(R"cpp( +#define ADD(a, b) ((a) + (b)) +int x = $ADD(1, 2); +)cpp"); + + expect_contains("macro"); + expect_contains("`ADD`"); + expect_contains("#define ADD"); +} + +TEST_CASE(MacroDefinition) { + run(R"cpp( +#define $MARKER 100 +)cpp"); + + expect_contains("macro"); + expect_contains("`MARKER`"); + expect_contains("#define MARKER 100"); +} + +// === Expression Hover === + +TEST_CASE(ThisExpr) { + run(R"cpp( +struct Obj { + void method() { auto self = $this; } +}; +)cpp"); + + expect_contains("this"); + expect_contains("Obj"); +} + +TEST_CASE(ConstructorCall) { + run(R"cpp( +struct Box { + Box(int w, int h) {} }; +Box b = $Box(1, 2); )cpp"); + + ASSERT_TRUE(result.has_value()); + expect_contains("Box"); +} + +TEST_CASE(MemberAccess) { + run(R"cpp( +struct Item { int value; }; +void use() { + Item it; + int v = it.$value; } +)cpp"); -TEST_CASE(VariableStyle) { - compile_only(R"cpp( -void f() { - constexpr static auto x1 = 1; + expect_contains("field"); + expect_contains("`value`"); + expect_contains("Type:"); + expect_contains("`int`"); } + +TEST_CASE(TypeLocHover) { + run(R"cpp( +struct MyClass {}; +$MyClass obj; )cpp"); + + ASSERT_TRUE(result.has_value()); + expect_contains("MyClass"); } -TEST_CASE(AutoAndDecltype) { - compile_only(R"cpp( -$(a1)aut$(a2)o$(a3) i = -1; +TEST_CASE(ExpressionValue) { + run(R"cpp( +constexpr int a = 10; +constexpr int b = $a + 1; +)cpp"); + + ASSERT_TRUE(result.has_value()); + expect_contains("Value ="); +} -$(d1)dec$(d2)ltype$(d3)(i) j = 2; +// === Edge Cases === -struct A { int x; }; +TEST_CASE(ForwardDeclaration) { + run(R"cpp( +struct $Forward; +)cpp"); -aut$(a4)o va$(a5)r = A{}; + ASSERT_TRUE(result.has_value()); + expect_contains("`Forward`"); +} -a$(fa)uto f1() { return 1; } +TEST_CASE(AnonymousStruct) { + run(R"cpp( +struct Outer { + struct { int $x; } inner; +}; +)cpp"); -de$(fn_decltype)cltype(au$(fn_decltype_auto)to) f2() {} + expect_contains("field"); + expect_contains("`x`"); +} -int f3(au$(fn_para_auto)to x) {} +TEST_CASE(NoHover) { + add_main("main.cpp", R"cpp( +$ +int x; )cpp"); + ASSERT_TRUE(compile()); + + auto points = nameless_points(); + ASSERT_EQ(points.size(), 1U); + auto offset = points[0]; + result = feature::hover(*unit, offset, {}, feature::PositionEncoding::UTF8); + + EXPECT_FALSE(result.has_value()); } -TEST_CASE(Expr) { - compile_only(R"cpp( -int xxxx = 1; -int yyyy = xx$(e1)xx; +TEST_CASE(ScopedEnum) { + run(R"cpp( +enum class Direction { Up, Down, Left, Right }; +Direction d = Direction::$Up; +)cpp"); + + expect_contains("enum member"); + expect_contains("`Up`"); + expect_contains("Value ="); + expect_contains("`0`"); +} -struct A { - int function(int param) { - return thi$(e2)s$(e3)->$(e4)funct$(e5)ion(para$(e6)m); - } +// === Access Specifiers === - int fn(int param) { - return static$(e7)_cast(nul$(e8)lptr)->function(par$(e9)am); - } +TEST_CASE(PublicMember) { + run(R"cpp( +struct Foo { +public: + int $pub; +}; +)cpp"); + + expect_contains("field"); + expect_contains("`pub`"); + // struct members are public by default, check definition block + expect_contains("// In Foo"); +} + +TEST_CASE(PrivateMember) { + run(R"cpp( +class Bar { + int $priv; +}; +)cpp"); + + expect_contains("field"); + expect_contains("`priv`"); + expect_contains("private:"); +} + +// === Additional Tests === + +TEST_CASE(VoidFunction) { + run(R"cpp( +void $noop() {} +)cpp"); + + expect_contains("function"); + expect_contains("`noop`"); + expect_contains("`void`"); +} + +TEST_CASE(ConstMethod) { + run(R"cpp( +struct Obj { + int $get() const { return 0; } +}; +)cpp"); + + expect_contains("method"); + expect_contains("`get`"); + expect_contains("const"); +} + +TEST_CASE(StaticMethod) { + run(R"cpp( +struct Factory { + static Factory $create() { return {}; } +}; +)cpp"); + + expect_contains("method"); + expect_contains("`create`"); + expect_contains("static"); +} + +TEST_CASE(VirtualMethod) { + run(R"cpp( +struct Base { + virtual void $update() {} +}; +)cpp"); + + expect_contains("method"); + expect_contains("`update`"); + expect_contains("virtual"); +} + +TEST_CASE(PureVirtualMethod) { + run(R"cpp( +struct Interface { + virtual void $draw() = 0; +}; +)cpp"); + + expect_contains("method"); + expect_contains("`draw`"); + expect_contains("virtual"); + expect_contains("= 0"); +} + +TEST_CASE(EnumDefinition) { + run(R"cpp( +enum Status { OK, Error }; +void use($Status s) {} +)cpp"); + + expect_contains("`Status`"); +} + +TEST_CASE(ScopedEnumDefinition) { + run(R"cpp( +enum class Color : char { Red, Green, Blue }; +void use($Color c) {} +)cpp"); + + expect_contains("`Color`"); +} + +TEST_CASE(ClassDefinition) { + run(R"cpp( +class $Widget { + int x; + int y; +}; +)cpp"); + + expect_contains("class"); + expect_contains("`Widget`"); + expect_contains("Size:"); + expect_contains("alignment"); +} + +TEST_CASE(UnionDefinition) { + run(R"cpp( +union $Data { + int i; + float f; }; )cpp"); + + expect_contains("union"); + expect_contains("`Data`"); + expect_contains("Size:"); +} + +TEST_CASE(ParameterHover) { + run(R"cpp( +void func(int $param) {} +)cpp"); + + expect_contains("parameter"); + expect_contains("`param`"); + expect_contains("Type:"); + expect_contains("`int`"); +} + +TEST_CASE(ConstexprBigValue) { + run(R"cpp( +constexpr int $big = 255; +)cpp"); + + expect_contains("Value ="); + expect_contains("0xff"); +} + +TEST_CASE(NegativeEnumValue) { + run(R"cpp( +enum Signed { $Neg = -5 }; +)cpp"); + + expect_contains("enum member"); + expect_contains("`Neg`"); + expect_contains("-5"); +} + +TEST_CASE(TemplateTypeParameter) { + run(R"cpp( +template +struct Box { T val; }; +)cpp"); + + ASSERT_TRUE(result.has_value()); + expect_contains("`T`"); +} + +TEST_CASE(MultipleParameters) { + run(R"cpp( +void $multi(int a, int b, int c, int d) {} +)cpp"); + + expect_contains("Parameters:"); + expect_contains("`int a`"); + expect_contains("`int b`"); + expect_contains("`int c`"); + expect_contains("`int d`"); +} + +TEST_CASE(FunctionPointerVar) { + run(R"cpp( +int add(int a, int b) { return a + b; } +auto $fp = &add; +)cpp"); + + expect_contains("`fp`"); +} + +TEST_CASE(NestedNamespaceVar) { + run(R"cpp( +namespace a { namespace b { namespace c { + int $deep = 0; +}}} +)cpp"); + + expect_contains("// In namespace a::b::c"); } }; // TEST_SUITE(Hover) diff --git a/tests/unit/support/markup_tests.cpp b/tests/unit/support/markup_tests.cpp new file mode 100644 index 0000000000..986ae5d7c3 --- /dev/null +++ b/tests/unit/support/markup_tests.cpp @@ -0,0 +1,248 @@ +#include "test/test.h" +#include "support/markup.h" + +namespace clice::testing { + +namespace { + +TEST_SUITE(Markup) { + +TEST_CASE(EmptyDocument) { + Markup st; + EXPECT_EQ(st.as_markdown(), ""); +} + +TEST_CASE(SingleParagraph) { + Markup st; + st.add_paragraph().append_text("hello world"); + EXPECT_EQ(st.as_markdown(), "hello world"); +} + +TEST_CASE(PlainTextSpacing) { + Markup st; + auto& p = st.add_paragraph(); + p.append_text("hello"); + p.append_text("world"); + EXPECT_EQ(st.as_markdown(), "hello world"); +} + +TEST_CASE(InlineCode) { + Markup st; + auto& p = st.add_paragraph(); + p.append_text("Type:"); + p.append_text("int", Paragraph::Kind::InlineCode); + EXPECT_EQ(st.as_markdown(), "Type: `int`"); +} + +TEST_CASE(Bold) { + Markup st; + st.add_paragraph().append_text("important", Paragraph::Kind::Bold); + EXPECT_EQ(st.as_markdown(), "**important**"); +} + +TEST_CASE(Italic) { + Markup st; + st.add_paragraph().append_text("emphasis", Paragraph::Kind::Italic); + EXPECT_EQ(st.as_markdown(), "*emphasis*"); +} + +TEST_CASE(Strikethrough) { + Markup st; + st.add_paragraph().append_text("removed", Paragraph::Kind::Strikethrough); + EXPECT_EQ(st.as_markdown(), "~~removed~~"); +} + +TEST_CASE(MixedInline) { + Markup st; + auto& p = st.add_paragraph(); + p.append_text("Returns:", Paragraph::Kind::Bold); + p.append_text("the result"); + EXPECT_EQ(st.as_markdown(), "**Returns:** the result"); +} + +TEST_CASE(ConsecutiveInlineCode) { + Markup st; + auto& p = st.add_paragraph(); + p.append_text("int", Paragraph::Kind::InlineCode); + p.append_text("x", Paragraph::Kind::InlineCode); + EXPECT_EQ(st.as_markdown(), "`int` `x`"); +} + +TEST_CASE(Heading) { + Markup st; + st.add_heading(3).append_text("Title"); + EXPECT_EQ(st.as_markdown(), "### Title"); +} + +TEST_CASE(HeadingWithInlineCode) { + Markup st; + auto& h = st.add_heading(2); + h.append_text("function"); + h.append_text("foo", Paragraph::Kind::InlineCode); + EXPECT_EQ(st.as_markdown(), "## function `foo`"); +} + +TEST_CASE(Ruler) { + Markup st; + st.add_paragraph().append_text("above"); + st.add_ruler(); + st.add_paragraph().append_text("below"); + auto md = st.as_markdown(); + EXPECT_NE(md.find("above"), std::string::npos); + EXPECT_NE(md.find("---"), std::string::npos); + EXPECT_NE(md.find("below"), std::string::npos); +} + +TEST_CASE(ConsecutiveRulers) { + Markup st; + st.add_paragraph().append_text("text"); + st.add_ruler(); + st.add_ruler(); + st.add_paragraph().append_text("more"); + auto md = st.as_markdown(); + auto first = md.find("---"); + auto second = md.find("---", first + 3); + EXPECT_EQ(second, std::string::npos); +} + +TEST_CASE(LeadingTrailingRulers) { + Markup st; + st.add_ruler(); + st.add_paragraph().append_text("content"); + st.add_ruler(); + EXPECT_EQ(st.as_markdown(), "content"); +} + +TEST_CASE(CodeBlock) { + Markup st; + st.add_code_block("int x = 0;", "cpp"); + EXPECT_EQ(st.as_markdown(), "```cpp\nint x = 0;\n```"); +} + +TEST_CASE(CodeBlockTrailingNewline) { + Markup st; + st.add_code_block("int x = 0;\n", "cpp"); + EXPECT_EQ(st.as_markdown(), "```cpp\nint x = 0;\n```"); +} + +TEST_CASE(CodeBlockNoLang) { + Markup st; + st.add_code_block("hello"); + EXPECT_EQ(st.as_markdown(), "```\nhello\n```"); +} + +TEST_CASE(BulletListSimple) { + Markup st; + auto& list = st.add_bullet_list(); + list.add_item().add_paragraph().append_text("one"); + list.add_item().add_paragraph().append_text("two"); + list.add_item().add_paragraph().append_text("three"); + EXPECT_EQ(st.as_markdown(), "- one\n- two\n- three"); +} + +TEST_CASE(BulletListFormatted) { + Markup st; + auto& list = st.add_bullet_list(); + list.add_item().add_paragraph().append_text("bold", Paragraph::Kind::Bold); + list.add_item().add_paragraph().append_text("code", Paragraph::Kind::InlineCode); + EXPECT_EQ(st.as_markdown(), "- **bold**\n- `code`"); +} + +TEST_CASE(BulletListMultiline) { + Markup st; + auto& list = st.add_bullet_list(); + list.add_item().add_paragraph().append_text("line1\nline2"); + auto md = st.as_markdown(); + EXPECT_NE(md.find("- line1\n line2"), std::string::npos); +} + +TEST_CASE(BlockSeparation) { + Markup st; + st.add_paragraph().append_text("first"); + st.add_paragraph().append_text("second"); + auto md = st.as_markdown(); + EXPECT_NE(md.find("first\n"), std::string::npos); + EXPECT_NE(md.find("second"), std::string::npos); + EXPECT_EQ(md.find("firstsecond"), std::string::npos); +} + +TEST_CASE(ParagraphThenList) { + Markup st; + st.add_paragraph().append_text("Parameters:"); + auto& list = st.add_bullet_list(); + list.add_item().add_paragraph().append_text("int x", Paragraph::Kind::InlineCode); + auto md = st.as_markdown(); + EXPECT_EQ(md.find("Parameters:- "), std::string::npos); + EXPECT_EQ(md.find("Parameters:-"), std::string::npos); + EXPECT_NE(md.find("Parameters:"), std::string::npos); + EXPECT_NE(md.find("- `int x`"), std::string::npos); +} + +TEST_CASE(HeadingThenRuler) { + Markup st; + st.add_heading(3).append_text("title"); + st.add_ruler(); + st.add_paragraph().append_text("body"); + auto md = st.as_markdown(); + EXPECT_NE(md.find("### title\n"), std::string::npos); + EXPECT_NE(md.find("---"), std::string::npos); + EXPECT_NE(md.find("body"), std::string::npos); +} + +TEST_CASE(TripleNewlineCollapse) { + Markup st; + st.add_paragraph().append_text("a\n\n\n\nb"); + auto md = st.as_markdown(); + EXPECT_EQ(md.find("\n\n\n"), std::string::npos); +} + +TEST_CASE(ClonePreservesHeading) { + Markup st; + st.add_heading(2).append_text("Title"); + Markup copy = st; + auto md = copy.as_markdown(); + EXPECT_NE(md.find("## Title"), std::string::npos); +} + +TEST_CASE(NewlineChar) { + Markup st; + auto& p = st.add_paragraph(); + p.append_text("line1"); + p.append_newline_char(); + p.append_text("line2"); + auto md = st.as_markdown(); + EXPECT_NE(md.find("line1"), std::string::npos); + EXPECT_NE(md.find("line2"), std::string::npos); +} + +TEST_CASE(FullHoverLike) { + Markup st; + st.add_heading(3).append_text("function").append_text("add", Paragraph::Kind::InlineCode); + st.add_ruler(); + st.add_paragraph().append_text("\xe2\x86\x92").append_text("int", Paragraph::Kind::InlineCode); + st.add_paragraph().append_text("Parameters:"); + auto& params = st.add_bullet_list(); + params.add_item().add_paragraph().append_text("int a", Paragraph::Kind::InlineCode); + params.add_item().add_paragraph().append_text("int b", Paragraph::Kind::InlineCode); + st.add_ruler(); + st.add_code_block("int add(int a, int b);\n", "cpp"); + + auto md = st.as_markdown(); + + EXPECT_NE(md.find("### function `add`"), std::string::npos); + EXPECT_NE(md.find("---"), std::string::npos); + EXPECT_NE(md.find("\xe2\x86\x92 `int`"), std::string::npos); + EXPECT_NE(md.find("Parameters:"), std::string::npos); + EXPECT_NE(md.find("- `int a`"), std::string::npos); + EXPECT_NE(md.find("- `int b`"), std::string::npos); + EXPECT_NE(md.find("```cpp"), std::string::npos); + + EXPECT_EQ(md.find("`int`Parameters"), std::string::npos); + EXPECT_EQ(md.find("Parameters:- "), std::string::npos); +} + +}; // TEST_SUITE(Markup) + +} // namespace + +} // namespace clice::testing diff --git a/tests/unit/support/structed_text_tests.cpp b/tests/unit/support/structed_text_tests.cpp deleted file mode 100644 index 2a97c989a8..0000000000 --- a/tests/unit/support/structed_text_tests.cpp +++ /dev/null @@ -1,121 +0,0 @@ -#include "test/test.h" -#include "support/format.h" -#include "support/structed_text.h" - -namespace clice::testing { - -namespace { - -TEST_SUITE(StructedText) { - -TEST_CASE(Paragraph) { - constexpr const char* cb = - R"c(// Without processing, recommended -char *longestPalindrome_solv2(const char *s) { - int len = strlen(s); - int max_start = 0; - int max_len = 0; - for (int i = 0; i < len; ++i) { - // j = 0, max_len is odd - // j = 1, max_len is even - for (int j = 0; j <= 1; ++j) { - int l = i; - int r = i + j; - - // expand the range from center - while (l >= 0 && r < len && s[l] == s[r]) { - --l; - ++r; - } - - ++l; - --r; - - if (max_len < r - l + 1) { - max_len = r - l + 1; - max_start = i; - } - } - } - char *res = (char *)malloc((max_len + 1) * sizeof(char)); - memcpy(res, s + max_start, max_len); - res[max_len] = '\0'; - return res; -} -)c"; - StructedText st; - st.add_paragraph().append_text("CodeBlock Example:").append_newline_char(); - st.add_code_block(cb, "c"); - auto& para = st.add_paragraph(); - para.append_text("para1").append_newline_char(); - /// std::println("{}", st.as_markdown()); -} - -TEST_CASE(BulletList) { - StructedText st; - st.add_bullet_list().add_item().add_paragraph().append_text("Item1"); - st.add_bullet_list().add_item().add_paragraph().append_text("Item2", - Paragraph::Kind::InlineCode); - st.add_bullet_list().add_item().add_paragraph().append_text("Item3", Paragraph::Kind::Bold); - st.add_bullet_list().add_item().add_paragraph().append_text("Item4", Paragraph::Kind::Italic); - st.add_bullet_list().add_item().add_paragraph().append_text("Item5", - Paragraph::Kind::Strikethough); - /// std::println("{}", st.as_markdown()); -} - -TEST_CASE(FullText) { - StructedText st; - st.add_heading(3) - .append_text("function") - .append_text("test_bar", Paragraph::Kind::InlineCode) - .append_newline_char() - .append_text("Provided by:") - .append_text("`foo/bar/baz.h`"); - st.add_ruler(); - st.add_paragraph() - .append_text("→") - .append_text("int", Paragraph::Kind::InlineCode) - .append_newline_char(); - st.add_paragraph().append_text("Paramaters:", Paragraph::Kind::Bold).append_newline_char(); - auto& params = st.add_bullet_list(); - params.add_item() - .add_paragraph() - .append_text("int foo", Paragraph::Kind::InlineCode) - .append_text("doc for foo\ndoc for foo line2"); - params.add_item() - .add_paragraph() - .append_text("char** bar", Paragraph::Kind::InlineCode) - .append_text("doc for bar"); - params.add_item() - .add_paragraph() - .append_text("char** baz", Paragraph::Kind::InlineCode) - .append_text("doc for baz"); - st.add_paragraph().append_text(R"md( -brief block -brief line2 - a b c d e f - ~~~~^ -This is *Italic* **Bold** ~~Striketough~~, `InlineCode` -)md"); - st.add_ruler(); - st.add_paragraph().append_text("Details:", Paragraph::Kind::Bold).append_newline_char(); - auto& details = st.add_bullet_list(); - details.add_item().add_paragraph().append_text("Detail1: blah blah..."); - details.add_item().add_paragraph().append_text("Detail2: blah blah...\n Line2: ......"); - details.add_item().add_paragraph().append_text("Detail3: blah blah..."); - st.add_ruler(); - st.add_paragraph().append_text("Details:", Paragraph::Kind::Bold).append_newline_char(); - auto& warnings = st.add_bullet_list(); - warnings.add_item().add_paragraph().append_text("warnings1: blah blah..."); - warnings.add_item().add_paragraph().append_text("warnings2: blah blah...\n Line2: ......"); - warnings.add_item().add_paragraph().append_text("warnings3: blah blah..."); - st.add_ruler(); - st.add_code_block("int test_bar(int foo, char **bar, char **baz);\n", "cpp"); - /// std::println("{}", st.as_markdown()); -} - -}; // TEST_SUITE(StructedText) - -} // namespace - -} // namespace clice::testing From 2df42abd801df9b7d74df87d9dabee2f17086231 Mon Sep 17 00:00:00 2001 From: ykiko Date: Mon, 4 May 2026 16:34:21 +0800 Subject: [PATCH 2/3] fix(hover): use double newline between markdown blocks for proper VSCode rendering MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Single newline caused setext heading interpretation (text\n--- → H2) and paragraph merging in CommonMark/markdown-it. Co-Authored-By: Claude Opus 4.6 --- src/support/markup.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/support/markup.cpp b/src/support/markup.cpp index c5535417a3..c69eeabfde 100644 --- a/src/support/markup.cpp +++ b/src/support/markup.cpp @@ -171,7 +171,7 @@ static std::string render_blocks(llvm::ArrayRef> blocks) } last_block_was_ruler = b->is_ruler(); b->render_markdown(os); - os << '\n'; + os << "\n\n"; } // Collapse runs of 3+ newlines down to 2 (one blank line max). From f397e95b34a66e5a57fb783a9f27efae8e62d9e6 Mon Sep 17 00:00:00 2001 From: ykiko Date: Mon, 4 May 2026 20:28:04 +0800 Subject: [PATCH 3/3] feat(hover): format definition code blocks with clang-format Use the project's .clang-format style to format the code snippets shown in hover popups, so they match the user's formatting preferences instead of Clang's raw pretty-printer output. Co-Authored-By: Claude Opus 4.6 --- src/feature/feature.h | 2 ++ src/feature/formatting.cpp | 16 ++++++++++++++++ src/feature/hover.cpp | 8 +++++--- tests/unit/feature/formatting_tests.cpp | 12 ++++++++++++ 4 files changed, 35 insertions(+), 3 deletions(-) diff --git a/src/feature/feature.h b/src/feature/feature.h index b4904280a1..edb005064d 100644 --- a/src/feature/feature.h +++ b/src/feature/feature.h @@ -104,4 +104,6 @@ auto document_format(llvm::StringRef file, PositionEncoding encoding = PositionEncoding::UTF16) -> std::vector; +auto format_code(llvm::StringRef file, llvm::StringRef code) -> std::string; + } // namespace clice::feature diff --git a/src/feature/formatting.cpp b/src/feature/formatting.cpp index 0be637028d..eee92fb973 100644 --- a/src/feature/formatting.cpp +++ b/src/feature/formatting.cpp @@ -66,4 +66,20 @@ auto document_format(llvm::StringRef file, return edits; } +auto format_code(llvm::StringRef file, llvm::StringRef code) -> std::string { + auto style = clang::format::getStyle(clang::format::DefaultFormatStyle, + file, + clang::format::DefaultFallbackStyle, + code); + if(!style) + return code.str(); + + auto replacements = clang::format::reformat(*style, code, {tooling::Range(0, code.size())}); + auto result = tooling::applyAllReplacements(code, replacements); + if(!result) + return code.str(); + + return llvm::StringRef(*result).trim().str(); +} + } // namespace clice::feature diff --git a/src/feature/hover.cpp b/src/feature/hover.cpp index 5f4e0f537a..8d1167cb06 100644 --- a/src/feature/hover.cpp +++ b/src/feature/hover.cpp @@ -643,7 +643,7 @@ auto format_param(const Param& p) -> std::string { return result; } -auto present(const HoverInfo& hi) -> std::string { +auto present(const HoverInfo& hi, llvm::StringRef file = "") -> std::string { Markup output; Paragraph& header = output.add_heading(3); @@ -805,6 +805,8 @@ auto present(const HoverInfo& hi) -> std::string { code += hi.access_specifier + ": "; code += hi.definition; + if(!file.empty()) + code = feature::format_code(file, code); output.add_code_block(std::move(code), "cpp"); } @@ -901,7 +903,7 @@ auto build_hover(const HoverInfo& hi, .contents = protocol::MarkupContent{ .kind = protocol::MarkupKind::Markdown, - .value = present(hi), + .value = present(hi, unit.file_path(unit.interested_file())), }, }; @@ -1029,7 +1031,7 @@ auto hover(CompilationUnitRef unit, .contents = protocol::MarkupContent{ .kind = protocol::MarkupKind::Markdown, - .value = present(*hi), + .value = present(*hi, unit.file_path(unit.interested_file())), }, }; diff --git a/tests/unit/feature/formatting_tests.cpp b/tests/unit/feature/formatting_tests.cpp index 0a5d9a6fdf..4a731582bd 100644 --- a/tests/unit/feature/formatting_tests.cpp +++ b/tests/unit/feature/formatting_tests.cpp @@ -35,6 +35,18 @@ TEST_CASE(IncludeSort) { ASSERT_NE(edits.size(), 0U); } +TEST_CASE(FormatCode) { + auto result = feature::format_code("main.cpp", "int add( int a,int b ){return a+b;}"); + EXPECT_NE(result.find("int add("), std::string::npos); + EXPECT_EQ(result.find(" int a,int"), std::string::npos); +} + +TEST_CASE(FormatCodeIdempotent) { + auto first = feature::format_code("main.cpp", "int add( int a,int b ){return a+b;}"); + auto second = feature::format_code("main.cpp", first); + EXPECT_EQ(first, second); +} + }; // TEST_SUITE(Formatting) } // namespace