diff --git a/plugins/csharp/model/CsharpEntity.cs b/plugins/csharp/model/CsharpEntity.cs index c7c85b7c7..8425c4076 100644 --- a/plugins/csharp/model/CsharpEntity.cs +++ b/plugins/csharp/model/CsharpEntity.cs @@ -23,7 +23,8 @@ enum EtcEntityTypeEnum { Event, Invocation, - ForeachExpr + ForeachExpr, + Inheritance } class CsharpEtcEntity : CsharpTypedEntity { diff --git a/plugins/csharp/parser/src_csharp/AstVisitor.cs b/plugins/csharp/parser/src_csharp/AstVisitor.cs index 5b24a511b..dbbada0b8 100644 --- a/plugins/csharp/parser/src_csharp/AstVisitor.cs +++ b/plugins/csharp/parser/src_csharp/AstVisitor.cs @@ -56,14 +56,35 @@ private ulong fnvHash(string data_) } return hash; - } + } + + // Deterministic replacement for GetHashCode(), which is reference based + // for syntax nodes and randomized per process for strings. Both would + // give different ids for the same entity on every parse. + private long stableHash(string data_) + { + return unchecked((long)fnvHash(data_)); + } + + private long getEntityHash(SyntaxNode node) + { + string[] properties = + { + node.SyntaxTree.FilePath,":", + node.Kind().ToString(),":", + node.Span.Start.ToString(),":", + node.Span.End.ToString() + }; + + return stableHash(string.Concat(properties)); + } private ulong getAstNodeId(SyntaxNode node){ CsharpAstNode astNode = new CsharpAstNode { AstValue = node.ToString(), RawKind = node.Kind(), - EntityHash = node.GetHashCode(), + EntityHash = getEntityHash(node), AstType = AstTypeEnum.Declaration }; astNode.SetLocation(node.SyntaxTree.GetLineSpan(node.Span)); @@ -86,7 +107,7 @@ private CsharpAstNode AstNode(SyntaxNode node, AstSymbolTypeEnum type, AstTypeEn { AstValue = node.ToString(), RawKind = node.Kind(), - EntityHash = node.GetHashCode(), + EntityHash = getEntityHash(node), AstSymbolType = type, AstType = astType, Accessibility = acc @@ -175,7 +196,9 @@ public override void VisitInterfaceDeclaration(InterfaceDeclarationSyntax node) QualifiedName = qName, DocumentationCommentXML = Model.GetDeclaredSymbol(node).GetDocumentationCommentXml(), EntityHash = astNode.EntityHash - }; + }; + + VisitBaseList(node.BaseList, astNode); foreach (PropertyDeclarationSyntax propertyDeclaration in node.Members.OfType()) { @@ -226,9 +249,11 @@ public override void VisitStructDeclaration(StructDeclarationSyntax node) EntityHash = astNode.EntityHash }; - foreach (VariableDeclarationSyntax variableDeclaration in node.Members.OfType()) + VisitBaseList(node.BaseList, astNode); + + foreach (var variableDeclaration in node.Members.OfType()) { - VisitVariableDecl(variableDeclaration, astNode); + VisitVariableDecl(variableDeclaration.Declaration, astNode); } foreach (PropertyDeclarationSyntax propertyDeclaration in node.Members.OfType()) @@ -321,6 +346,8 @@ public override void VisitClassDeclaration(ClassDeclarationSyntax node) EntityHash = astNode.EntityHash }; + VisitBaseList(node.BaseList, astNode); + foreach (var variableDeclaration in node.Members.OfType()) { VisitVariableDecl(variableDeclaration.Declaration, astNode); @@ -416,6 +443,8 @@ public override void VisitRecordDeclaration(RecordDeclarationSyntax node) { EntityHash = astNode.EntityHash }; + VisitBaseList(node.BaseList, astNode); + foreach (var variableDeclaration in node.Members.OfType()) { VisitVariableDecl(variableDeclaration.Declaration, astNode); @@ -480,6 +509,41 @@ public override void VisitRecordDeclaration(RecordDeclarationSyntax node) { DbContext.CsharpClasses.Add(csharpRecord); } + private void VisitBaseList(BaseListSyntax baseList, CsharpAstNode parent) + { + if (baseList == null) + return; + + foreach (BaseTypeSyntax baseType in baseList.Types) + { + var symbol = Model.GetTypeInfo(baseType.Type).Type as INamedTypeSymbol; + if (symbol == null) + continue; + + symbol = symbol.OriginalDefinition; + + var declaration = symbol.DeclaringSyntaxReferences + .Select(r => r.GetSyntax()) + .FirstOrDefault(s => s is BaseTypeDeclarationSyntax); + if (declaration == null) + continue; + + var astNode = AstNode(baseType, AstSymbolTypeEnum.EtcEntity, AstTypeEnum.Usage); + CsharpEtcEntity inheritance = new CsharpEtcEntity + { + AstNode = astNode, + EntityHash = astNode.EntityHash, + ParentNode = parent, + EtcEntityType = EtcEntityTypeEnum.Inheritance, + DeclaratorNodeId = getAstNodeId(declaration), + Name = symbol.Name, + QualifiedName = symbol.ToString(), + QualifiedType = symbol.TypeKind.ToString() + }; + DbContext.CsharpEtcEntitys.Add(inheritance); + } + } + private void VisitDelegateDecl(DelegateDeclarationSyntax node, CsharpAstNode parent) { CsharpAstNode astNode = AstNode(node,AstSymbolTypeEnum.Method); @@ -616,7 +680,7 @@ private void VisitMethodDecl(MethodDeclarationSyntax node, CsharpAstNode parent) QualifiedName = qName, QualifiedType = qType, DocumentationCommentXML = Model.GetDeclaredSymbol(node).GetDocumentationCommentXml(), - TypeHash = qType.GetHashCode(), + TypeHash = stableHash(qType), EntityHash = astNode.EntityHash, ParentNode = parent, MethodType = MethodTypeEnum.Method @@ -666,7 +730,7 @@ private void VisitOperatorDecl(OperatorDeclarationSyntax node, CsharpAstNode par QualifiedName = qName, QualifiedType = qType, DocumentationCommentXML = Model.GetDeclaredSymbol(node).GetDocumentationCommentXml(), - TypeHash = qType.GetHashCode(), + TypeHash = stableHash(qType), EntityHash = astNode.EntityHash, ParentNode = parent, MethodType = MethodTypeEnum.Operator @@ -704,7 +768,7 @@ private void VisitMethodParameters(SeparatedSyntaxList paramete AstNode = astNode, Name = param.Identifier.Text, QualifiedType = paramQType, - TypeHash = paramQType.GetHashCode(), + TypeHash = stableHash(paramQType), EntityHash = astNode.EntityHash, ParentNode = parent, VariableType = VariableTypeEnum.Parameter @@ -752,7 +816,7 @@ private void VisitVariableDecl(VariableDeclarationSyntax node, CsharpAstNode par AstNode = astNode, Name = variable.Identifier.Text, QualifiedType = varQType, - TypeHash = varQType.GetHashCode(), + TypeHash = stableHash(varQType), DocumentationCommentXML = Model.GetDeclaredSymbol(variable).GetDocumentationCommentXml(), EntityHash = astNode.EntityHash, VariableType = isLINQvar ? VariableTypeEnum.LINQ : VariableTypeEnum.Variable, @@ -779,7 +843,7 @@ private void VisitPropertyDecl(PropertyDeclarationSyntax node, CsharpAstNode par AstNode = astNode, Name = node.Identifier.Text, QualifiedType = varQType, - TypeHash = varQType.GetHashCode(), + TypeHash = stableHash(varQType), VariableType = VariableTypeEnum.Property, DocumentationCommentXML = Model.GetDeclaredSymbol(node).GetDocumentationCommentXml(), EntityHash = astNode.EntityHash, @@ -951,11 +1015,69 @@ public override void VisitInvocationExpression(InvocationExpressionSyntax node) DbContext.CsharpEtcEntitys.Add(invoc); } } - } - } + } + } + + VisitMethodInvocation(node); base.VisitInvocationExpression(node); - } + } + + // Records an invocation whose DeclaratorNodeId points to the declaration + // of the called method. This is what the Callee / Caller references and + // the function call diagram rely on. + private void VisitMethodInvocation(InvocationExpressionSyntax node) + { + SimpleNameSyntax name = node.Expression switch + { + MemberAccessExpressionSyntax memberAccess => memberAccess.Name, + MemberBindingExpressionSyntax memberBinding => memberBinding.Name, + SimpleNameSyntax simpleName => simpleName, + _ => null + }; + + // Unqualified Foo() calls are already recorded by VisitIdentifierName. + if (name == null || (name == node.Expression && name is IdentifierNameSyntax)) + return; + + var method = Model.GetSymbolInfo(node).Symbol as IMethodSymbol; + if (method == null) + return; + + method = (method.ReducedFrom ?? method).OriginalDefinition; + method = method.PartialImplementationPart ?? method; + + var declaration = method.DeclaringSyntaxReferences + .Select(r => r.GetSyntax()) + .FirstOrDefault(s => s is BaseMethodDeclarationSyntax); + if (declaration == null) + return; + + var type = ""; + try + { + var info = Model.GetTypeInfo(node).ConvertedType; + if (info != null) type = info.Name; + } + catch (Exception) + { + FullyParsed = false; + } + + var declaratorNodeId = getAstNodeId(declaration); + var astNode = AstNode(name, AstSymbolTypeEnum.EtcEntity, AstTypeEnum.Usage); + CsharpEtcEntity invoc = new CsharpEtcEntity + { + AstNode = astNode, + EntityHash = astNode.EntityHash, + EtcEntityType = EtcEntityTypeEnum.Invocation, + DeclaratorNodeId = declaratorNodeId, + Name = name.Identifier.Text, + QualifiedName = method.ToString(), + QualifiedType = type + }; + DbContext.CsharpEtcEntitys.Add(invoc); + } public override void VisitIdentifierName(IdentifierNameSyntax node) { diff --git a/plugins/csharp/parser/src_csharp/Program.cs b/plugins/csharp/parser/src_csharp/Program.cs index 8cdc20b94..b714e7c76 100644 --- a/plugins/csharp/parser/src_csharp/Program.cs +++ b/plugins/csharp/parser/src_csharp/Program.cs @@ -72,6 +72,23 @@ static async Task Main(string[] args) } } + private static void RecreateCsharpTables(CsharpDbContext context) + { + var tables = context.Model.GetEntityTypes() + .Select(e => e.GetTableName()) + .Where(t => t != null) + .Distinct() + .Append("__EFMigrationsHistory"); + + foreach (var table in tables) + { + string sql = "DROP TABLE IF EXISTS \"" + table + "\" CASCADE"; + context.Database.ExecuteSqlRaw(sql); + } + + context.Database.Migrate(); + } + private static async Task RunParserAsync(string primaryInput, int threadNum) { // Converting the connectionstring into entity framework style connectionstring @@ -82,7 +99,7 @@ private static async Task RunParserAsync(string primaryInput, int threadNum .Options; await using var _context = new CsharpDbContext(options); - _context.Database.Migrate(); + RecreateCsharpTables(_context); if (IsSolutionInput(primaryInput)) { diff --git a/plugins/csharp/service/CMakeLists.txt b/plugins/csharp/service/CMakeLists.txt index cfc163255..3ab817894 100644 --- a/plugins/csharp/service/CMakeLists.txt +++ b/plugins/csharp/service/CMakeLists.txt @@ -39,6 +39,7 @@ add_subdirectory(src_csharp) add_library(csharpservice SHARED src/csharpservice.cpp + src/csharpdiagram.cpp src/plugin.cpp) target_compile_options(csharpservice PUBLIC -Wno-unknown-pragmas) diff --git a/plugins/csharp/service/csharpservice.thrift b/plugins/csharp/service/csharpservice.thrift index 4d223da5e..4aea6242d 100644 --- a/plugins/csharp/service/csharpservice.thrift +++ b/plugins/csharp/service/csharpservice.thrift @@ -49,9 +49,6 @@ service CsharpService map getDiagramTypes(1:common.AstNodeId astNodeId) throws (1:common.InvalidId ex) - string getDiagram(1:common.AstNodeId astNodeId, 2:i32 diagramId) - throws (1:common.InvalidId exId, 2:common.Timeout exLong) - list getSyntaxHighlight( 1:common.FileRange range, 2:list content) diff --git a/plugins/csharp/service/include/service/csharpservice.h b/plugins/csharp/service/include/service/csharpservice.h index 3660098c9..0b6ee1c37 100644 --- a/plugins/csharp/service/include/service/csharpservice.h +++ b/plugins/csharp/service/include/service/csharpservice.h @@ -184,14 +184,6 @@ class CSharpQueryHandler : public CsharpServiceIf _service -> getDiagramTypes(return_, astNodeId_); } - void getDiagram( - std::string& return_, - const core::AstNodeId& astNodeId_, - const std::int32_t diagramId_) override - { - _service -> getDiagram(return_, astNodeId_, diagramId_); - } - void getSyntaxHighlight( std::vector& return_, const core::FileRange& range_, @@ -219,7 +211,7 @@ using TransportException = apache::thrift::transport::TTransportException; class CsharpServiceHandler : virtual public LanguageServiceIf { - friend class Diagram; + friend class CsharpDiagram; public: CsharpServiceHandler( @@ -323,6 +315,28 @@ class CsharpServiceHandler : virtual public LanguageServiceIf const core::FileRange& range_) override; private: + // Must be kept in sync with CSharpServiceEnums.cs. + enum DiagramType + { + FUNCTION_CALL, + DETAILED_CLASS + }; + + enum ReferenceType + { + DEFINITION = 0, + CALLEE = 5, + CALLER = 6, + LOCAL_VAR = 10, + INHERIT_FROM = 19, + INHERIT_BY = 20, + DATA_MEMBER = 21, + METHOD = 22 + }; + + + core::AstNodeId getDefinitionId(const core::AstNodeId& astNodeId_); + std::shared_ptr _db; util::OdbTransaction _transaction; diff --git a/plugins/csharp/service/src/csharpdiagram.cpp b/plugins/csharp/service/src/csharpdiagram.cpp new file mode 100644 index 000000000..551413b09 --- /dev/null +++ b/plugins/csharp/service/src/csharpdiagram.cpp @@ -0,0 +1,577 @@ +#include +#include +#include + +#include + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +#include "csharpdiagram.h" + +namespace +{ + +/** + * Returns the position after the attribute section (e.g. [Route("[x]")]) + * starting at pos_, or std::string::npos if the brackets are unbalanced. + */ +std::size_t skipAttribute(const std::string& str_, std::size_t pos_) +{ + int depth = 0; + bool inString = false; + + for (; pos_ < str_.size(); ++pos_) + { + char c = str_[pos_]; + + if (inString) + { + if (c == '\\') + ++pos_; + else if (c == '"') + inString = false; + } + else if (c == '"') + inString = true; + else if (c == '[') + ++depth; + else if (c == ']' && --depth == 0) + return pos_ + 1; + } + + return std::string::npos; +} + +const std::vector accessibilityModifiers = { + "public", "private", "protected", "internal"}; + +/** + * All member modifiers. In the class diagram the visibility and the static and + * virtual members are shown by formatting, so the keywords are not needed. + */ +const std::vector memberModifiers = { + "public", "private", "protected", "internal", "static", "virtual", + "abstract", "override", "sealed", "new", "extern", "unsafe", "partial", + "async", "readonly", "required", "volatile", "const"}; + +/** + * Removes the leading attributes and the given leading modifiers from the + * declaration of a node, and cuts the signature before the body. + */ +std::string toSignature( + std::string str_, + const std::vector& modifiers_ = accessibilityModifiers) +{ + boost::trim_left(str_); + + // Attributes may share a line with the declaration, so they are removed + // by bracket matching instead of dropping whole lines. + while (!str_.empty() && str_[0] == '[') + { + std::size_t end = skipAttribute(str_, 0); + if (end == std::string::npos) + break; + + str_.erase(0, end); + boost::trim_left(str_); + } + + // Modifiers are only removed as whole leading words, so names like + // "publicKey" are kept. + bool removed = true; + while (removed) + { + removed = false; + + for (const auto& tag : modifiers_) + if (boost::starts_with(str_, tag) && + (str_.size() == tag.size() || + std::isspace(static_cast(str_[tag.size()])))) + { + str_.erase(0, tag.size()); + boost::trim_left(str_); + removed = true; + } + } + + // Cut before a block body or an expression body. + str_ = str_.substr(0, std::min(str_.find('{'), str_.find("=>"))); + boost::trim(str_); + + return str_; +} + +/** + * Returns the signature of a member for the class diagram: without + * attributes, modifiers, body and constructor initializer (": base(...)"). + */ +std::string toMemberSignature(const std::string& str_, const std::string& kind_) +{ + // Multi-line parameter lists are joined into one line. + static const std::regex whitespace("\\s+"); + static const std::regex afterOpenParen("\\( "); + static const std::regex beforeCloseParen(" \\)"); + std::string signature = std::regex_replace( + toSignature(str_, memberModifiers), whitespace, " "); + signature = std::regex_replace(signature, afterOpenParen, "("); + signature = std::regex_replace(signature, beforeCloseParen, ")"); + + // Interface, abstract and delegate members end with a semicolon. + if (!signature.empty() && signature.back() == ';') + { + signature.pop_back(); + boost::trim_right(signature); + } + + if (kind_ == "ConstructorDeclaration") + { + std::size_t open = signature.find('('); + int depth = 0; + + for (std::size_t i = open; open != std::string::npos && i < signature.size(); ++i) + if (signature[i] == '(') + ++depth; + else if (signature[i] == ')' && --depth == 0) + { + signature.erase(i + 1); + break; + } + } + + return signature; +} + +/** + * Removes the namespace qualifiers from a type name, e.g. + * "System.Collections.Generic.List" -> "List". + */ +std::string toShortTypeName(const std::string& type_) +{ + static const std::regex qualifier("[A-Za-z_][A-Za-z0-9_]*\\."); + return std::regex_replace(type_, qualifier, ""); +} + +/** + * This function wraps the content to a HTML tag and adds attributes to it. + */ +std::string graphHtmlTag( + const std::string& tag_, + const std::string& content_, + const std::string& attr_ = "") +{ + return "<" + tag_ + " " + attr_ + ">" + content_ + ""; +} + +bool contains(const std::vector& tags_, const std::string& tag_) +{ + return std::find(tags_.begin(), tags_.end(), tag_) != tags_.end(); +} + +} + +namespace cc +{ +namespace service +{ +namespace language +{ + +CsharpDiagram::CsharpDiagram( + std::shared_ptr db_, + std::shared_ptr datadir_, + const cc::webserver::ServerContext& context_) + : _db(db_), + _transaction(db_), + _projectHandler(db_, datadir_, context_) +{ +} + +void CsharpDiagram::getFunctionCallDiagram( + util::Graph& graph_, + const AstNodeInfo& centerNodeInfo_, + const std::vector& calleeNodeInfos_, + const std::vector& callerNodeInfos_) +{ + // A node is decorated only when it is first added, so e.g. a recursive + // center node keeps its own decoration (same as in the C++ plugin). + std::map visitedNodes; + + graph_.setAttribute("rankdir", "LR"); + + AstNodeInfo centerInfo = centerNodeInfo_; + centerInfo.astNodeValue = toSignature(centerInfo.astNodeValue); + util::Graph::Node centerNode = addNode(graph_, centerInfo); + decorateNode(graph_, centerNode, centerNodeDecoration); + visitedNodes[centerInfo.id] = centerNode; + + for (const auto& calleeNodeInfo : calleeNodeInfos_) + { + util::Graph::Node calleeNode; + + auto it = visitedNodes.find(calleeNodeInfo.id); + if (it == visitedNodes.end()) + { + AstNodeInfo calleeInfo = calleeNodeInfo; + calleeInfo.astNodeValue = toSignature(calleeInfo.astNodeValue); + calleeNode = addNode(graph_, calleeInfo); + decorateNode(graph_, calleeNode, calleeNodeDecoration); + visitedNodes.insert(it, std::make_pair(calleeInfo.id, calleeNode)); + } + else + calleeNode = it->second; + + if (!graph_.hasEdge(centerNode, calleeNode)) + { + util::Graph::Edge edge = graph_.createEdge(centerNode, calleeNode); + decorateEdge(graph_, edge, calleeEdgeDecoration); + } + } + + for (const auto& callerNodeInfo : callerNodeInfos_) + { + util::Graph::Node callerNode; + + auto it = visitedNodes.find(callerNodeInfo.id); + if (it == visitedNodes.end()) + { + AstNodeInfo callerInfo = callerNodeInfo; + callerInfo.astNodeValue = toSignature(callerInfo.astNodeValue); + callerNode = addNode(graph_, callerInfo); + decorateNode(graph_, callerNode, callerNodeDecoration); + visitedNodes.insert(it, std::make_pair(callerInfo.id, callerNode)); + } + else + callerNode = it->second; + + if (!graph_.hasEdge(callerNode, centerNode)) + { + util::Graph::Edge edge = graph_.createEdge(callerNode, centerNode); + decorateEdge(graph_, edge, callerEdgeDecoration); + } + } + + _subgraphs.clear(); +} + +std::string CsharpDiagram::getFunctionCallLegend() +{ + util::LegendBuilder builder("Function call diagram"); + + builder.addNode("center function", centerNodeDecoration); + builder.addNode("called function", calleeNodeDecoration); + builder.addNode("caller function", callerNodeDecoration); + builder.addEdge("called", calleeEdgeDecoration); + builder.addEdge("caller", callerEdgeDecoration); + + return builder.getOutput(); +} + +void CsharpDiagram::getDetailedClassDiagram( + util::Graph& graph_, + CsharpServiceHandler& csharpHandler_, + const core::AstNodeId& astNodeId_) +{ + std::vector nodes; + + graph_.setAttribute("rankdir", "BT"); + + //--- Center node ---// + + AstNodeInfo nodeInfo; + csharpHandler_.getAstNodeInfo(nodeInfo, astNodeId_); + + util::Graph::Node currentNode = addClassNode(graph_, csharpHandler_, nodeInfo); + + //--- Types from which the queried type inherits ---// + + csharpHandler_.getReferences(nodes, nodeInfo.id, + CsharpServiceHandler::INHERIT_FROM, {}); + + for (const AstNodeInfo& node : nodes) + { + util::Graph::Node inheritNode = addClassNode(graph_, csharpHandler_, node); + + if (!graph_.hasEdge(currentNode, inheritNode)) + { + util::Graph::Edge edge = graph_.createEdge(currentNode, inheritNode); + decorateEdge(graph_, edge, inheritClassEdgeDecoration); + } + } + + nodes.clear(); + + //--- Types by which the queried type is inherited ---// + + csharpHandler_.getReferences(nodes, nodeInfo.id, + CsharpServiceHandler::INHERIT_BY, {}); + + for (const AstNodeInfo& node : nodes) + { + util::Graph::Node inheritNode = addClassNode(graph_, csharpHandler_, node); + + if (!graph_.hasEdge(inheritNode, currentNode)) + { + util::Graph::Edge edge = graph_.createEdge(inheritNode, currentNode); + decorateEdge(graph_, edge, inheritClassEdgeDecoration); + } + } + + _subgraphs.clear(); +} + +std::string CsharpDiagram::getDetailedClassLegend() +{ + util::LegendBuilder builder("Detailed Class Diagram"); + + builder.addNode("class", classNodeDecoration); + builder.addNode("public member", {{"shape", "none"}, + {"label", graphHtmlTag("font", "+", "color='green'")}}, true); + builder.addNode("private member", {{"shape", "none"}, + {"label", graphHtmlTag("font", "-", "color='red'")}}, true); + builder.addNode("protected member", {{"shape", "none"}, + {"label", graphHtmlTag("font", "#", "color='blue'")}}, true); + builder.addNode("internal member", {{"shape", "none"}, + {"label", graphHtmlTag("font", "~", "color='darkorange'")}}, true); + builder.addNode("static method or data member", {{"shape", "none"}, + {"label", "static"}}, true); + builder.addNode("virtual, abstract or override method", {{"shape", "none"}, + {"label", "virtual"}}, true); + builder.addEdge("inheritance", inheritClassEdgeDecoration); + + return builder.getOutput(); +} + +util::Graph::Node CsharpDiagram::addClassNode( + util::Graph& graph_, + CsharpServiceHandler& csharpHandler_, + const AstNodeInfo& nodeInfo_) +{ + util::Graph::Node node = addNode(graph_, nodeInfo_); + + graph_.setNodeAttribute(node, "label", + getDetailedClassNodeLabel(csharpHandler_, nodeInfo_), true); + graph_.setNodeAttribute(node, "shape", "none"); + + return node; +} + +std::string CsharpDiagram::getDetailedClassNodeLabel( + CsharpServiceHandler& csharpHandler_, + const AstNodeInfo& nodeInfo_) +{ + std::string colAttr = "border='0' align='left'"; + std::string label = ""; + + // The AST node value of a type is its whole source text, so the name is + // taken from its properties. + std::map properties; + csharpHandler_.getProperties(properties, nodeInfo_.id); + std::string name = boost::trim_copy(properties["Name"]); + + label.append(graphHtmlTag("tr", graphHtmlTag("td", + graphHtmlTag("font", util::escapeHtml(name), "color='white'"), + "colspan='2' SIDES='B' bgcolor='#316ECF' align='center'"))); + + //--- Data members of the type: fields, then properties ---// + + std::vector nodes; + csharpHandler_.getReferences(nodes, nodeInfo_.id, + CsharpServiceHandler::LOCAL_VAR, {}); + + std::vector propertyNodes; + csharpHandler_.getReferences(propertyNodes, nodeInfo_.id, + CsharpServiceHandler::DATA_MEMBER, {}); + nodes.insert(nodes.end(), propertyNodes.begin(), propertyNodes.end()); + + for (auto it = nodes.begin(); it != nodes.end(); ++it) + { + std::map memberProperties; + csharpHandler_.getProperties(memberProperties, it->id); + + std::string content = boost::trim_copy(memberProperties["Name"]); + std::string type = toShortTypeName( + boost::trim_copy(memberProperties["Qualified Type"])); + if (!type.empty()) + content += " : " + type; + + std::string attr = colAttr; + if (it == nodes.end() - 1) + attr = "border='1' align='left' SIDES='B'"; + + label += graphHtmlTag("tr", + graphHtmlTag("td", visibilityToHtml(*it), attr) + + graphHtmlTag("td", + memberContentToHtml(*it, util::escapeHtml(content)), attr)); + } + + nodes.clear(); + + //--- Methods of the type ---// + + csharpHandler_.getReferences(nodes, nodeInfo_.id, + CsharpServiceHandler::METHOD, {}); + + for (const AstNodeInfo& node : nodes) + { + // Property accessors are shown by their properties. + if (contains(node.tags, "accessor")) + continue; + + std::string signature = + toMemberSignature(node.astNodeValue, node.astNodeType); + + if (!signature.empty()) + label += graphHtmlTag("tr", + graphHtmlTag("td", visibilityToHtml(node), colAttr) + + graphHtmlTag("td", + memberContentToHtml(node, util::escapeHtml(signature)), colAttr)); + } + + label.append("
"); + + return label; +} + +std::string CsharpDiagram::visibilityToHtml(const AstNodeInfo& node_) +{ + if (contains(node_.tags, "public")) + return graphHtmlTag("font", "+", "color='green'"); + if (contains(node_.tags, "private")) + return graphHtmlTag("font", "-", "color='red'"); + if (contains(node_.tags, "protected")) + return graphHtmlTag("font", "#", "color='blue'"); + if (contains(node_.tags, "internal")) + return graphHtmlTag("font", "~", "color='darkorange'"); + + return ""; +} + +std::string CsharpDiagram::memberContentToHtml( + const AstNodeInfo& node_, + const std::string& content_) +{ + std::string startTags; + std::string endTags; + + if (contains(node_.tags, "static")) + { + startTags += ""; + endTags.insert(0, ""); + } + + if (contains(node_.tags, "virtual")) + { + startTags += ""; + endTags.insert(0, ""); + } + + return startTags + content_ + endTags; +} + +util::Graph::Node CsharpDiagram::addNode( + util::Graph& graph_, + const AstNodeInfo& nodeInfo_) +{ + util::Graph::Node node + = graph_.getOrCreateNode(nodeInfo_.id, + addSubgraph(graph_, nodeInfo_.range.file)); + + graph_.setNodeAttribute(node, "label", nodeInfo_.astNodeValue); + + return node; +} + +util::Graph::Subgraph CsharpDiagram::addSubgraph( + util::Graph& graph_, + const core::FileId& fileId_) +{ + auto it = _subgraphs.find(fileId_); + + if (it != _subgraphs.end()) + return it->second; + + core::FileInfo fileInfo; + _projectHandler.getFileInfo(fileInfo, fileId_); + + util::Graph::Subgraph subgraph + = graph_.getOrCreateSubgraph("cluster_" + fileInfo.path); + + graph_.setSubgraphAttribute(subgraph, "id", fileInfo.id); + graph_.setSubgraphAttribute(subgraph, "label", fileInfo.path); + + _subgraphs.insert(it, std::make_pair(fileId_, subgraph)); + + return subgraph; +} + +void CsharpDiagram::decorateNode( + util::Graph& graph_, + const util::Graph::Node& node_, + const Decoration& decoration_) const +{ + for (const auto& attr : decoration_) + graph_.setNodeAttribute(node_, attr.first, attr.second); +} + +void CsharpDiagram::decorateEdge( + util::Graph& graph_, + const util::Graph::Edge& edge_, + const Decoration& decoration_) const +{ + for (const auto& attr : decoration_) + graph_.setEdgeAttribute(edge_, attr.first, attr.second); +} + +void CsharpDiagram::decorateSubgraph( + util::Graph& graph_, + const util::Graph::Subgraph& subgraph_, + const Decoration& decoration_) const +{ + for (const auto& attr : decoration_) + graph_.setSubgraphAttribute(subgraph_, attr.first, attr.second); +} + +const CsharpDiagram::Decoration CsharpDiagram::centerNodeDecoration = { + {"style", "filled"}, + {"fillcolor", "gold"} +}; + +const CsharpDiagram::Decoration CsharpDiagram::calleeNodeDecoration = { + {"style", "filled"}, + {"fillcolor", "lightblue"} +}; + +const CsharpDiagram::Decoration CsharpDiagram::callerNodeDecoration = { + {"style", "filled"}, + {"fillcolor", "coral"} +}; + +const CsharpDiagram::Decoration CsharpDiagram::calleeEdgeDecoration = { + {"color", "blue"} +}; + +const CsharpDiagram::Decoration CsharpDiagram::callerEdgeDecoration = { + {"color", "red"} +}; + +const CsharpDiagram::Decoration CsharpDiagram::classNodeDecoration = { + {"shape", "box"} +}; + +const CsharpDiagram::Decoration CsharpDiagram::inheritClassEdgeDecoration = { + {"arrowhead", "empty"} +}; + +} +} +} diff --git a/plugins/csharp/service/src/csharpdiagram.h b/plugins/csharp/service/src/csharpdiagram.h new file mode 100644 index 000000000..fc7efe3c0 --- /dev/null +++ b/plugins/csharp/service/src/csharpdiagram.h @@ -0,0 +1,160 @@ +#ifndef CC_SERVICE_LANGUAGE_CSHARPDIAGRAM_H +#define CC_SERVICE_LANGUAGE_CSHARPDIAGRAM_H + +#include +#include +#include + +namespace cc +{ +namespace service +{ +namespace language +{ + +class CsharpDiagram +{ +public: + CsharpDiagram( + std::shared_ptr db_, + std::shared_ptr datadir_, + const cc::webserver::ServerContext& context_); + + /** + * In the function call diagram the nodes are methods and the edges are the + * calls between them. + */ + void getFunctionCallDiagram( + util::Graph& graph_, + const AstNodeInfo& centerNodeInfo_, + const std::vector& calleeNodeInfos_, + const std::vector& callerNodeInfos_); + + /** + * This function creates legend for the Function call diagram. + * @return The generated legend as a string in SVG format. + */ + std::string getFunctionCallLegend(); + + /** + * This is a classical UML class diagram for the selected type and its direct + * base types and derived types. The nodes contain the data members and the + * methods with their visibility. The members are queried through the + * service handler like in the C++ plugin. + */ + void getDetailedClassDiagram( + util::Graph& graph_, + CsharpServiceHandler& csharpHandler_, + const core::AstNodeId& astNodeId_); + + /** + * This function creates legend for the Detailed class diagram. + * @return The generated legend as a string in SVG format. + */ + std::string getDetailedClassLegend(); + +private: + typedef std::vector> Decoration; + + /** + * This function adds a type node with an UML class label to the graph. + */ + util::Graph::Node addClassNode( + util::Graph& graph_, + CsharpServiceHandler& csharpHandler_, + const AstNodeInfo& nodeInfo_); + + /** + * This function creates the HTML label of a type node: the name of the type, + * its data members (fields and properties) and its methods. + */ + std::string getDetailedClassNodeLabel( + CsharpServiceHandler& csharpHandler_, + const AstNodeInfo& nodeInfo_); + + /** + * This function returns the colored UML visibility sign of a member based on + * its tags. + */ + std::string visibilityToHtml(const AstNodeInfo& node_); + + /** + * This function makes the already escaped content of a member bold if it is + * static and italic if it is virtual, abstract or override. + */ + std::string memberContentToHtml( + const AstNodeInfo& node_, + const std::string& content_); + + /** + * This function adds a node which represents an AST node. The label of the + * node is the AST node value. A node associated with the AST node is added + * only once. If already added then the previous one is returned. + */ + util::Graph::Node addNode( + util::Graph& graph_, + const AstNodeInfo& nodeInfo_); + + /** + * This function adds a subgraph which represents a file. The label of the + * subgraph will be the file path and the subgraph will have a border. A + * subgraph associated with the file is added only once. If already added then + * the previous one is returned. + */ + util::Graph::Subgraph addSubgraph( + util::Graph& graph_, + const core::FileId& fileId_); + + /** + * This function decorates a graph node. + * @param graph_ A graph object. + * @param node_ A graph node + * @param decoration_ A map which describes the style attributes. + */ + void decorateNode( + util::Graph& graph_, + const util::Graph::Node& node_, + const Decoration& decoration_) const; + + /** + * This function decorates a graph edge. + * @param graph_ A graph object. + * @param edge_ A graph edge + * @param decoration_ A map which describes the style attributes. + */ + void decorateEdge( + util::Graph& graph_, + const util::Graph::Edge& edge_, + const Decoration& decoration_) const; + + /** + * This function decorates a graph subgraph. + * @param graph_ A graph object. + * @param subgraph_ A graph subgraph + * @param decoration_ A map which describes the style attributes. + */ + void decorateSubgraph( + util::Graph& graph_, + const util::Graph::Subgraph& subgraph_, + const Decoration& decoration_) const; + + static const Decoration centerNodeDecoration; + static const Decoration calleeNodeDecoration; + static const Decoration callerNodeDecoration; + static const Decoration calleeEdgeDecoration; + static const Decoration callerEdgeDecoration; + static const Decoration classNodeDecoration; + static const Decoration inheritClassEdgeDecoration; + + std::map _subgraphs; + + std::shared_ptr _db; + util::OdbTransaction _transaction; + core::ProjectServiceHandler _projectHandler; +}; + +} +} +} + +#endif diff --git a/plugins/csharp/service/src/csharpservice.cpp b/plugins/csharp/service/src/csharpservice.cpp index 7d44b417d..cbdd0fb41 100644 --- a/plugins/csharp/service/src/csharpservice.cpp +++ b/plugins/csharp/service/src/csharpservice.cpp @@ -4,6 +4,8 @@ #include #include +#include "csharpdiagram.h" + namespace cc { namespace service @@ -70,10 +72,16 @@ void CsharpServiceHandler::getAstNodeInfo( return _db->query_one( FileQuery::path == return_.range.file); }); + if (!file) + { + core::InvalidId ex; + ex.__set_msg("Invalid C# AST node ID or source file"); + ex.__set_nodeid(astNodeId_); + throw ex; + } std::stringstream ss; - ss << file; + ss << file->id; return_.range.file = ss.str(); - //LOG(info) << "csharpQuery.getAstNodeInfo: file = " << return_.range.file; } void CsharpServiceHandler::getAstNodeInfoByPosition( @@ -134,7 +142,7 @@ void CsharpServiceHandler::getDiagramTypes( const core::AstNodeId& astNodeId_) { LOG(info) << "getDiagramTypes"; - //csharpQueryHandler.getDiagramTypes(return_, astNodeId_); + _csharpQueryHandler.getDiagramTypes(return_, astNodeId_); } void CsharpServiceHandler::getDiagram( @@ -143,7 +151,35 @@ void CsharpServiceHandler::getDiagram( const std::int32_t diagramId_) { LOG(info) << "getDiagram"; - //csharpQueryHandler.getDiagram(return_, astNodeId_, diagramId_); + CsharpDiagram diagram(_db, _datadir, _context); + util::Graph graph; + + core::AstNodeId definitionId = getDefinitionId(astNodeId_); + + switch (diagramId_) + { + case FUNCTION_CALL: + { + AstNodeInfo centerInfo; + getAstNodeInfo(centerInfo, definitionId); + + std::vector calleeInfos; + getReferences(calleeInfos, definitionId, CALLEE, {}); + + std::vector callerInfos; + getReferences(callerInfos, definitionId, CALLER, {}); + + diagram.getFunctionCallDiagram(graph, centerInfo, calleeInfos, callerInfos); + break; + } + + case DETAILED_CLASS: + diagram.getDetailedClassDiagram(graph, *this, definitionId); + break; + } + + if (graph.nodeCount() != 0) + return_ = graph.output(util::Graph::SVG); } void CsharpServiceHandler::getDiagramLegend( @@ -151,6 +187,34 @@ void CsharpServiceHandler::getDiagramLegend( const std::int32_t diagramId_) { LOG(info) << "getDiagramLegend"; + + CsharpDiagram diagram(_db, _datadir, _context); + + switch (diagramId_) + { + case FUNCTION_CALL: + return_ = diagram.getFunctionCallLegend(); + break; + + case DETAILED_CLASS: + return_ = diagram.getDetailedClassLegend(); + break; + } +} + +core::AstNodeId CsharpServiceHandler::getDefinitionId( + const core::AstNodeId& astNodeId_) +{ + AstNodeInfo nodeInfo; + getAstNodeInfo(nodeInfo, astNodeId_); + + if (nodeInfo.symbolType != "EtcEntity") + return astNodeId_; + + std::vector definitions; + getReferences(definitions, astNodeId_, DEFINITION, {}); + + return definitions.empty() ? astNodeId_ : definitions.front().id; } void CsharpServiceHandler::getFileDiagramTypes( @@ -206,7 +270,15 @@ void CsharpServiceHandler::getReferences( return _db->query_one( FileQuery::path == nodeinfo.range.file); }); - + + // Skip the reference instead of failing the whole request. + if (!file) + { + LOG(warning) << "[csharpservice] No file record for reference: " + << nodeinfo.range.file; + continue; + } + std::stringstream ss; ss << file->id; nodeinfo.range.file = ss.str(); diff --git a/plugins/csharp/service/src_csharp/CSharpQueryHandler.cs b/plugins/csharp/service/src_csharp/CSharpQueryHandler.cs index a221b65b9..311d1c404 100644 --- a/plugins/csharp/service/src_csharp/CSharpQueryHandler.cs +++ b/plugins/csharp/service/src_csharp/CSharpQueryHandler.cs @@ -6,6 +6,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; @@ -119,13 +120,132 @@ private CsharpAstNode queryCsharpAstNode(string astNodeId) private List queryInvocations(CsharpAstNode astNode) { + // Base list entries are listed by the Inherited by reference instead. var ret = dbContext.CsharpEtcEntitys - .Where(e => e.DeclaratorNodeId == astNode.Id) + .Where(e => e.DeclaratorNodeId == astNode.Id + && e.EtcEntityType != EtcEntityTypeEnum.Inheritance) .Select(e => e.AstNode) .ToList(); return ret; } + private List queryInheritFrom(CsharpAstNode astNode) + { + var ret = + from inh in dbContext.CsharpEtcEntitys + join node in dbContext.CsharpAstNodes + on inh.DeclaratorNodeId equals node.Id + where inh.ParentNode.Id == astNode.Id + && inh.EtcEntityType == EtcEntityTypeEnum.Inheritance + select node; + return ret.Distinct().ToList(); + } + + private List queryInheritBy(CsharpAstNode astNode) + { + var ret = dbContext.CsharpEtcEntitys + .Where(e => e.DeclaratorNodeId == astNode.Id + && e.EtcEntityType == EtcEntityTypeEnum.Inheritance) + .Select(e => e.ParentNode) + .Distinct() + .ToList(); + return ret; + } + + private static string toVisibilityTag(Microsoft.CodeAnalysis.Accessibility accessibility) + { + switch (accessibility) + { + case Microsoft.CodeAnalysis.Accessibility.Public: + return "public"; + case Microsoft.CodeAnalysis.Accessibility.Private: + return "private"; + case Microsoft.CodeAnalysis.Accessibility.Protected: + case Microsoft.CodeAnalysis.Accessibility.ProtectedOrInternal: + case Microsoft.CodeAnalysis.Accessibility.ProtectedAndInternal: + return "protected"; + case Microsoft.CodeAnalysis.Accessibility.Internal: + return "internal"; + default: + return null; + } + } + + // Creates the infos of the members of a type ordered by their position, + // tagged with their lowercase visibility, "static", "virtual" (also for + // abstract, override and interface members) and "accessor". The modifiers + // are not stored in the database, so they are read from the source text. + private List createMemberInfoList( + List members, CsharpAstNode type) + { + var typeSyntax = SyntaxFactory.ParseMemberDeclaration(type.AstValue ?? "") + as BaseTypeDeclarationSyntax; + bool isInterface = typeSyntax is InterfaceDeclarationSyntax; + + // Field declarators do not contain the modifiers of their declaration. + var fieldModifiers = new Dictionary(); + if (typeSyntax is TypeDeclarationSyntax typeDeclaration) + foreach (var field in typeDeclaration.Members.OfType()) + foreach (var variable in field.Declaration.Variables) + fieldModifiers[variable.Identifier.Text] = field.Modifiers; + + var ret = new List(); + foreach (var member in members + .OrderBy(m => m.Location_range_start_line) + .ThenBy(m => m.Location_range_start_column)) + { + var info = createAstNodeInfo(member); + var modifiers = new Microsoft.CodeAnalysis.SyntaxTokenList(); + bool hasBody = true; + + if (member.RawKind == SyntaxKind.VariableDeclarator) + { + string name = new string((member.AstValue ?? "") + .TakeWhile(c => char.IsLetterOrDigit(c) || c == '_' || c == '@') + .ToArray()); + fieldModifiers.TryGetValue(name, out modifiers); + } + else if (member.RawKind.ToString().EndsWith("AccessorDeclaration")) + { + info.Tags.Add("accessor"); + } + else + { + var memberSyntax = SyntaxFactory.ParseMemberDeclaration(member.AstValue ?? ""); + if (memberSyntax != null) + modifiers = memberSyntax.Modifiers; + if (memberSyntax is BaseMethodDeclarationSyntax method) + hasBody = method.Body != null || method.ExpressionBody != null; + } + + string visibility = toVisibilityTag(member.Accessibility); + if (visibility != null) + info.Tags.Add(visibility); + + bool has(SyntaxKind kind) => modifiers.Any(t => t.RawKind == (int)kind); + + bool isStatic = has(SyntaxKind.StaticKeyword) || has(SyntaxKind.ConstKeyword); + if (isStatic) + info.Tags.Add("static"); + + if (has(SyntaxKind.VirtualKeyword) + || has(SyntaxKind.AbstractKeyword) + || has(SyntaxKind.OverrideKeyword) + || (isInterface && !isStatic && !hasBody)) + info.Tags.Add("virtual"); + + ret.Add(info); + } + + return ret; + } + + private bool isType(CsharpAstNode astNode) + { + return astNode.AstSymbolType == AstSymbolTypeEnum.Class + || astNode.AstSymbolType == AstSymbolTypeEnum.Struct; + } + private List queryDeclarators(CsharpAstNode astNode) { var ids = dbContext.CsharpEtcEntitys @@ -289,7 +409,7 @@ private List queryEvents(CsharpAstNode astNode) CancellationToken cancellationToken = default(CancellationToken)) { System.Console.WriteLine("[CSharpService] getAstNodeInfoAsync"); - return await Task.FromResult(new language.AstNodeInfo()); + return await Task.FromResult(createAstNodeInfo(queryCsharpAstNode(astNodeId))); } public async Task getAstNodeInfoByPosition(string path_, @@ -529,6 +649,12 @@ public async Task getReferenceCount(string astNodeId, int referenceId, case ReferenceType.DATA_MEMBER: ret = queryProperties(node).Count(); break; + case ReferenceType.INHERIT_FROM: + ret = queryInheritFrom(node).Count(); + break; + case ReferenceType.INHERIT_BY: + ret = queryInheritBy(node).Count(); + break; case ReferenceType.THIS_CALLS: ret = queryCalls(node).Count(); break; @@ -592,10 +718,18 @@ public async Task getReferenceCount(string astNodeId, int referenceId, ret = createAstNodeInfoList(queryParams(node)); break; case ReferenceType.LOCAL_VAR: - ret = createAstNodeInfoList(queryLocals(node)); + ret = isType(node) + ? createMemberInfoList(queryLocals(node), node) + : createAstNodeInfoList(queryLocals(node)); break; case ReferenceType.DATA_MEMBER: - ret = createAstNodeInfoList(queryProperties(node)); + ret = createMemberInfoList(queryProperties(node), node); + break; + case ReferenceType.INHERIT_FROM: + ret = createAstNodeInfoList(queryInheritFrom(node)); + break; + case ReferenceType.INHERIT_BY: + ret = createAstNodeInfoList(queryInheritBy(node)); break; case ReferenceType.THIS_CALLS: ret = createAstNodeInfoList(queryCalls(node)); @@ -610,7 +744,7 @@ public async Task getReferenceCount(string astNodeId, int referenceId, ret = createAstNodeInfoList(queryEnumConsts(node)); break; case ReferenceType.METHOD: - ret = createAstNodeInfoList(queryMethods(node)); + ret = createMemberInfoList(queryMethods(node), node); break; case ReferenceType.CONSTRUCTOR: ret = createAstNodeInfoList(queryMethodType(node, MethodTypeEnum.Constructor)); @@ -664,13 +798,19 @@ public async Task getFileReferenceCount(string path, int referenceId, public async Task> getDiagramTypes(string astNodeId, CancellationToken cancellationToken = default(CancellationToken)) { - return await Task.FromResult(new Dictionary()); - } + var node = queryCsharpAstNode(astNodeId); + var ret = new Dictionary(); - public async Task getDiagram(string astNodeId, int diagramId, - CancellationToken cancellationToken = default(CancellationToken)) - { - return await Task.FromResult("Diagram"); + // Usages offer the diagrams of their definition, like in the C++ plugin. + if (node.AstSymbolType == AstSymbolTypeEnum.EtcEntity) + node = queryDeclarators(node).FirstOrDefault() ?? node; + + if (node.AstSymbolType == AstSymbolTypeEnum.Method) + ret.Add("Function call diagram", (int)DiagramType.FUNCTION_CALL); + else if (isType(node)) + ret.Add("Detailed class diagram", (int)DiagramType.DETAILED_CLASS); + + return await Task.FromResult(ret); } public async Task> getSyntaxHighlight(FileRange range,