A code analysis method, an analysis device, an electronic device, and a storage medium

CN122924837APending Publication Date: 2026-10-16MIDEA GRP (SHANGHAI) CO LTD +1
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611047718.5
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-07-14
Publication Date
2026-10-16

AI Technical Summary

Technical Problem

[0003]在分析代码过程中,传统代码分析工具无法有效处理同时包含多种编程语言的复杂代码库的代码分析工作,导致跨语言的代码之间理解困难

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122924837A_ABST
    Figure CN122924837A_ABST
Patent Text Reader

Abstract

The application provides a code analysis method, an analysis device, an electronic equipment and a storage medium. The method is applied to the technical field of code analysis. The method comprises the following steps: determining a unified abstract syntax tree according to a target code file to be analyzed. The target code file comprises multiple source codes written in different programming languages; constructing a target code knowledge graph according to the unified abstract syntax tree and the target code file; performing weight calculation on M graph nodes in the target code knowledge graph to obtain target weights of the M graph nodes; and determining a code analysis result of the target code file according to the target weights of the M graph nodes. The method can unify the syntax structures of different programming languages, eliminate the differences between languages, realize unified representation of cross-language codes, and realize cross-language analysis and understanding of complex code libraries.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the field of code analysis technology, and more specifically, to a code analysis method, analysis apparatus, electronic device, and storage medium in the field of code analysis technology. Background Technology

[0002] Currently, in the software development and maintenance process, understanding the structure of the code in the codebase is key to improving code analysis efficiency and maintaining the code.

[0003] In the process of code analysis, traditional code analysis tools cannot effectively handle the analysis of complex code libraries that contain multiple programming languages, leading to difficulties in understanding code across languages. Summary of the Invention

[0004] This application provides a code analysis method, analysis device, electronic device, and storage medium. The method can unify the syntax structure of different programming languages, eliminate differences between languages, realize a unified representation of cross-language code, and achieve cross-language analysis and understanding of complex code libraries.

[0005] Firstly, a code analysis method is provided, comprising: determining a unified abstract syntax tree (UPN) corresponding to a target code file to be analyzed, wherein the target code file includes multiple source codes written in different programming languages; constructing a target code knowledge graph based on the UPN and the target code file, wherein the graph nodes of the target code knowledge graph are the code entities in the target code file, and the graph edges of the target code knowledge graph are the relationships between multiple code entities; calculating the weights of M graph nodes in the target code knowledge graph to obtain the target weights of the M graph nodes, wherein M is a positive integer greater than 1; and determining the code analysis result of the target code file based on the target weights of the M graph nodes.

[0006] In the above technical solution, this application provides a code analysis method. During implementation, this method determines a unified abstract syntax tree (API) corresponding to the source code of multiple different programming languages ​​in the target code file. This process unifies the syntactic structures of different programming languages, eliminates differences between languages, and achieves a unified representation of cross-language code. Simultaneously, this method is not limited by the number of programming languages ​​and can achieve cross-language analysis and understanding of complex code libraries. Furthermore, based on the unified API and the target code file, a target code knowledge graph is constructed, enabling structured modeling of the relationships between code entities. This transforms complex code structures from text into a visual network of relationships, facilitating subsequent analysis. Finally, by calculating the node weights of each node in the target code knowledge graph, this application quantifies the importance of each code entity within the entire code library, providing reliable data support for code maintenance and optimization, thereby obtaining more reliable code analysis results and improving the accuracy of code analysis.

[0007] In conjunction with the first aspect, in some possible implementations, determining the unified abstract syntax tree corresponding to the target code file to be analyzed includes: for any source code among the multiple source codes, parsing the source code using the syntax parser corresponding to that source code to generate an initial abstract syntax tree for that source code; after all the initial abstract syntax trees of the multiple source codes have been generated, converting the multiple original nodes included in the initial abstract syntax trees of the multiple source codes into multiple standard nodes; and generating the unified abstract syntax tree based on the multiple standard nodes.

[0008] In the above technical solution, when parsing source code of multiple programming languages, this application first obtains an initial abstract syntax tree by parsing the source code using the parser corresponding to each programming language. This ensures that the parsing result completely matches the logic of the source code, guaranteeing the accuracy of syntax parsing. Based on this, the nodes of each initial abstract syntax tree are mapped to obtain standard nodes, allowing all source code to share the same node system. This facilitates unified code analysis and effectively solves the cross-language parsing barrier in the code analysis process.

[0009] In combination with the first aspect and the above implementation methods, in some possible implementation methods, before constructing the target code knowledge graph based on the unified abstract syntax tree and the target code file, the code analysis method further includes: for any standard node among the multiple standard nodes, obtaining the attribute information and identifier of the standard node; using the identifier of the standard node as the key and the attribute information of the standard node as the value, constructing the mapping relationship of the standard node; and, after all the mapping relationships of the multiple standard nodes have been constructed, obtaining the global node mapping table based on the mapping relationships of the multiple standard nodes.

[0010] In the above technical solution, before constructing the code knowledge graph, a global node mapping table is first established using the attribute information and identifiers of standard nodes. This allows for the creation of a unique index identifier for each transformed standard node. Consequently, during subsequent queries, all attribute information of the standard node can be directly located using the identifier, avoiding decentralized node queries and improving node retrieval efficiency.

[0011] Combining the first aspect and the above implementation methods, in some possible implementation methods, the construction of the target code knowledge graph based on the unified abstract syntax tree and the target code file includes: constructing an initial code knowledge graph based on the unified abstract syntax tree, the global node mapping table, and the target code file; and performing a rationality verification on the initial code knowledge graph to obtain the target code knowledge graph.

[0012] Combining the first aspect and the above implementation methods, in some possible implementation methods, the initial code knowledge graph is constructed based on the unified abstract syntax tree, the global node mapping table, and the target code file. This includes: obtaining configuration files for the various source codes; parsing the configuration files for the various source codes to obtain a global path mapping table for the various source codes, where the configuration files define the path mapping rules for the source codes and the global path mapping table represents the correspondence between path aliases and base paths; extracting the semantic relationships between the multiple standard nodes based on the unified abstract syntax tree, the global path mapping table, and the global node mapping table; and constructing the initial code knowledge graph based on the multiple standard nodes and the semantic relationships between them.

[0013] Combining the first aspect and the above implementation methods, in some possible implementation methods, the semantic relationships between the multiple standard nodes are extracted based on the unified abstract syntax tree, the global path mapping table, and the global node mapping table. This includes: for any import node in the unified abstract syntax tree, obtaining the import path and identifier of the import node; if the import path of the import node is a path alias, determining the actual file path of the import node based on the import path of the import node and the global path mapping table; if the import path of the import node is not a path alias, determining the actual file path of the import node through the path mapping strategy corresponding to the import path of the import node; and based on the import node... Using the identifier of the point and the actual file path of the imported node, search the global node mapping table to determine the first defined node; construct the first semantic association relationship of the imported node based on the imported node and the first defined node; for any reference node in the unified abstract syntax tree other than the multiple imported nodes, obtain the identifier of the reference node, and search the global node mapping table based on the identifier of the reference node to determine the second defined node; construct the second semantic association relationship of the reference node based on the reference node and the second defined node; determine the first semantic association relationship of the multiple imported nodes and the second semantic association relationship of the multiple reference nodes as the semantic association relationship between the multiple standard nodes.

[0014] Combining the first aspect and the above implementation methods, in some possible implementation methods, the weight calculation of the M graph nodes in the target code knowledge graph to obtain the target weights of the M graph nodes includes: for any graph node among the M graph nodes, obtaining the multidimensional importance feature of the graph node in the target code knowledge graph, the multidimensional importance feature being used to represent the core degree of the graph node in the target code knowledge graph; performing weighted fusion of the multidimensional importance feature of the graph node to obtain the initial weight of the graph node; and, given the initial weights of the M graph nodes, determining the target weights of the M graph nodes based on the initial weights of the M graph nodes and the target code knowledge graph.

[0015] In the above technical solution, the initial weights of graph nodes are calculated using multi-dimensional weighting, taking into account the importance of each node in the graph structure from various aspects, making the weight calculation more objective and accurate. Furthermore, correcting the initial weights using the target code knowledge graph can further reflect the actual propagation impact of nodes in the overall dependency network, improving the accuracy of graph node weight calculation.

[0016] Combining the first aspect and the above implementation methods, in some possible implementation methods, the multidimensional importance feature includes at least one of the graph structure weight, code feature weight, semantic feature weight, and usage pattern weight of the graph node. Obtaining the multidimensional importance feature of the graph node in the target code knowledge graph includes: calculating the graph structure weight of the graph node based on its topological features, where the topological features represent the connection state of the graph node in the target code knowledge graph; determining the code feature weight of the graph node based on the source code features corresponding to the graph node in the target code file; determining the semantic feature weight of the graph node based on its semantic keywords; and determining the usage pattern weight of the graph node based on its usage results in the target code knowledge graph.

[0017] Combining the first aspect and the above implementation methods, in some possible implementation methods, the target weights of the M graph nodes are determined based on their initial weights and the target code knowledge graph. This includes: assigning edge weights to each graph edge of the target code knowledge graph; performing multiple iterations on the global importance score of the M graph nodes based on their initial weights and the edge weights of each graph edge of the target code knowledge graph to obtain the target global importance score of the M graph nodes, which represents the overall influence of the graph nodes in the target code knowledge graph; and determining the target weights of the M graph nodes based on their target global importance scores.

[0018] Combining the first aspect and the above implementation methods, in some possible implementation methods, the global importance score of the M graph nodes is iterated multiple times based on the initial weights of the M graph nodes and the edge weights of each graph edge of the target code knowledge graph to obtain the target global importance score of the M graph nodes. This includes: in the i-th iteration, for any graph node among the M graph nodes, determining any upstream node among the M graph nodes that points to the graph node, where i is a positive integer greater than or equal to 1; based on the (i-1)-th iteration global importance score of the upstream node, the edge weight of the upstream node pointing to the graph node, the cumulative edge weight of the upstream node, and the initial weight of the graph node, the i-th iteration global importance score of the graph node is obtained. For the global importance score, when i=1, the (i-1)th round global importance score of the upstream node is the weight after normalization of the initial weight of the upstream node, and the cumulative edge weight is the sum of the edge weights of all outgoing edges of the upstream node. Given the i-th round global importance scores of the M graph nodes, if the i-th round global importance scores of the M graph nodes satisfy a preset convergence condition, the i-th round global importance scores of the M graph nodes are determined as the target global importance scores of the M graph nodes. If the i-th round global importance scores of the M graph nodes do not satisfy the preset convergence condition, the (i+1)th round of iteration is executed, setting i+1=i, and the determination steps for the i-th round global importance scores of the M graph nodes are repeated.

[0019] In conjunction with the first aspect and the above implementation methods, in some possible implementation methods, the code analysis further includes: obtaining the (i-1)th round global importance score of the M graph nodes after obtaining the i-th round global importance score; determining the i-th round iteration error based on the i-th round global importance score and the (i-1)th round global importance score of the M graph nodes; determining that the i-th round global importance score of the M graph nodes satisfies the preset convergence condition if the i-th round iteration error is less than or equal to a preset error; and determining that the i-th round global importance score of the M graph nodes does not satisfy the preset convergence condition if the i-th round iteration error is greater than the preset error.

[0020] Combining the first aspect and the above implementation methods, in some possible implementation methods, determining the target weights of the M graph nodes based on their target global importance scores includes: for any graph node among the M graph nodes, obtaining the degree centrality and betweenness centrality of the graph node; determining the fusion centrality of the graph node based on its degree centrality and betweenness centrality; and determining the target weight of the graph node based on its fusion centrality and its target global importance score.

[0021] In the above technical solution, when calculating the target weight of the graph node, two types of centrality indicators, degree centrality and betweenness centrality, are introduced, which can more comprehensively reflect the influence of the node at the local and global levels and improve the accuracy and reliability of the weight calculation.

[0022] In conjunction with the first aspect and the above implementation methods, in some possible implementation methods, before determining the code analysis result of the target code file based on the target weights of the M graph nodes, the code analysis method further includes: performing code activity analysis on the target code file to obtain a code activity report; and determining the code analysis result of the target code file based on the target weights of the M graph nodes includes: determining the node classification labels of the M graph nodes and the importance ranking result of the M graph nodes based on the target weights of the M graph nodes; and generating the code analysis result based on the importance ranking result of the M graph nodes, the node classification labels of the M graph nodes, and the code activity report.

[0023] In the above technical solution, the final code analysis result is generated based on the importance ranking of M graph nodes, node classification labels, and code activity analysis report. This can comprehensively evaluate code quality, maintainability, and potential risk levels, providing a quantitative basis for subsequent code refactoring and optimization. It can also help developers effectively identify key issues and high-risk areas in the code.

[0024] Secondly, a code analysis device is provided, comprising: a determining module, configured to determine a unified abstract syntax tree (UPN) corresponding to a target code file to be analyzed, the target code file including multiple source codes written in different programming languages; a constructing module, configured to construct a target code knowledge graph based on the UPN and the target code file, wherein the graph nodes of the target code knowledge graph are the code entities in the target code file, and the graph edges of the target code knowledge graph are the relationships between multiple code entities; the determining module is further configured to calculate the weights of M graph nodes in the target code knowledge graph to obtain the target weights of the M graph nodes, where M is a positive integer greater than 1; and the determining module is further configured to determine the code analysis result of the target code file based on the target weights of the M graph nodes.

[0025] In conjunction with the second aspect, in some possible implementations, the determining module is further configured to: for any one of the multiple source codes, parse the source code using the corresponding syntax parser to generate an initial abstract syntax tree for the source code; when all the initial abstract syntax trees of the multiple source codes have been generated, convert the multiple original nodes included in the initial abstract syntax trees of the multiple source codes into multiple standard nodes; and generate the unified abstract syntax tree based on the multiple standard nodes.

[0026] In conjunction with the second aspect and the above implementation methods, in some possible implementation methods, before constructing the target code knowledge graph based on the unified abstract syntax tree and the target code file, the construction module is further used to: for any standard node among the multiple standard nodes, obtain the attribute information and identifier of the standard node; construct the mapping relationship of the standard node using the identifier of the standard node as the key and the attribute information of the standard node as the value; and, after all the mapping relationships of the multiple standard nodes have been constructed, obtain the global node mapping table based on the mapping relationships of the multiple standard nodes.

[0027] In conjunction with the second aspect and the above implementation methods, in some possible implementation methods, the building module is also used to: construct an initial code knowledge graph based on the unified abstract syntax tree, the global node mapping table, and the target code file; and perform a rationality check on the initial code knowledge graph to obtain the target code knowledge graph.

[0028] In conjunction with the second aspect and the above implementation methods, in some possible implementation methods, the building module is also used to: obtain the configuration files of the multiple source codes; parse the configuration files of the multiple source codes to obtain a global path mapping table of the multiple source codes, wherein the configuration files are used to define the path mapping rules of the source codes, and the global path mapping table is used to represent the correspondence between path aliases and base paths; extract the semantic association relationships between the multiple standard nodes based on the unified abstract syntax tree, the global path mapping table, and the global node mapping table; and construct the initial code knowledge graph based on the multiple standard nodes and the semantic association relationships between the multiple standard nodes.

[0029] In conjunction with the second aspect and the above implementation methods, in some possible implementation methods, the building module is further configured to: for any import node in the unified abstract syntax tree, obtain the import path and identifier of the import node; if the import path of the import node is a path alias, determine the actual file path of the import node based on the import path of the import node and the global path mapping table; if the import path of the import node is not a path alias, determine the actual file path of the import node through the path mapping strategy corresponding to the import path of the import node; search the global node mapping table based on the identifier of the import node and the actual file path of the import node to determine a first definition node; construct a first semantic association relationship for the import node based on the import node and the first definition node; for any reference node in the unified abstract syntax tree other than multiple import nodes, obtain the identifier of the reference node, and search the global node mapping table based on the identifier of the reference node to determine a second definition node; construct a second semantic association relationship for the reference node based on the reference node and the second definition node; and determine the first semantic association relationship of the multiple import nodes and the second semantic association relationship of the multiple reference nodes as the semantic association relationship between the multiple standard nodes.

[0030] In conjunction with the second aspect and the above implementation methods, in some possible implementation methods, the determining module is further configured to: for any graph node among the M graph nodes, obtain the multidimensional importance feature of the graph node in the target code knowledge graph, the multidimensional importance feature being used to represent the core degree of the graph node in the target code knowledge graph; perform weighted fusion on the multidimensional importance feature of the graph node to obtain the initial weight of the graph node; and, given the initial weights of the M graph nodes, determine the target weights of the M graph nodes based on the initial weights of the M graph nodes and the target code knowledge graph.

[0031] In conjunction with the second aspect and the above implementation methods, in some possible implementation methods, the multidimensional importance feature includes at least one of the graph structure weight, code feature weight, semantic feature weight, and usage pattern weight of the graph node. The determining module is further configured to: calculate the graph structure weight of the graph node based on the topological features of the graph node, where the topological features represent the connection state of the graph node in the target code knowledge graph; determine the code feature weight of the graph node based on the source code features corresponding to the graph node in the target code file; determine the semantic feature weight of the graph node based on the semantic keywords of the graph node; and determine the usage pattern weight of the graph node based on the usage results of the graph node in the target code knowledge graph.

[0032] In conjunction with the second aspect and the above implementation methods, in some possible implementation methods, the determining module is further configured to: assign edge weights to each graph edge of the target code knowledge graph; perform multiple iterations on the global importance scores of the M graph nodes based on the initial weights of the M graph nodes and the edge weights of each graph edge of the target code knowledge graph to obtain the target global importance scores of the M graph nodes, which are used to represent the comprehensive influence of the graph nodes in the target code knowledge graph; and determine the target weights of the M graph nodes based on the target global importance scores of the M graph nodes.

[0033] In conjunction with the second aspect and the above implementation methods, in some possible implementation methods, the determining module is further used to: during the i-th iteration, for any graph node among the M graph nodes, determine any upstream node among the M graph nodes pointing to that graph node, where i is a positive integer greater than or equal to 1; based on the (i-1)-th round global importance score of the upstream node, the edge weight of the upstream node pointing to the graph node, the cumulative edge weight of the upstream node, and the initial weight of the graph node, obtain the i-th round global importance score of the graph node; when i=1, the (i-1)-th round global importance score of the upstream node is the value of the upstream node. The initial weight of a node is normalized, and the cumulative edge weight is the sum of the edge weights of all outgoing edges of the upstream node. Given the i-th round global importance scores of the M graph nodes, if the i-th round global importance scores of the M graph nodes satisfy a preset convergence condition, the i-th round global importance scores of the M graph nodes are determined as the target global importance scores of the M graph nodes. If the i-th round global importance scores of the M graph nodes do not satisfy the preset convergence condition, the (i+1)-th round of iteration is executed, setting i+1=i, and the steps for determining the i-th round global importance scores of the M graph nodes are repeated.

[0034] In conjunction with the second aspect and the above implementation methods, in some possible implementation methods, the determining module is further configured to: obtain the (i-1)th round global importance score of the M graph nodes after obtaining the i-th round global importance score of the M graph nodes; determine the i-th round iteration error based on the i-th round global importance score and the (i-1)th round global importance score of the M graph nodes; determine that the i-th round global importance score of the M graph nodes satisfies the preset convergence condition if the i-th round iteration error is less than or equal to a preset error; and determine that the i-th round global importance score of the M graph nodes does not satisfy the preset convergence condition if the i-th round iteration error is greater than the preset error.

[0035] In conjunction with the second aspect and the above implementation methods, in some possible implementation methods, the determining module is further configured to: for any graph node among the M graph nodes, obtain the degree centrality and betweenness centrality of the graph node; determine the fusion centrality of the graph node based on the degree centrality and betweenness centrality of the graph node; and determine the target weight of the graph node based on the fusion centrality of the graph node and the target global importance score of the graph node.

[0036] In conjunction with the second aspect and the above implementation methods, in some possible implementation methods, before determining the code analysis result of the target code file based on the target weights of the M graph nodes, the determining module is further configured to: perform code activity analysis on the target code file to obtain a code activity report; and the determining module is further configured to: determine the node classification labels of the M graph nodes and the importance ranking result of the M graph nodes based on the target weights of the M graph nodes; and generate the code analysis result based on the importance ranking result of the M graph nodes, the node classification labels of the M graph nodes, and the code activity report.

[0037] Thirdly, an electronic device is provided, including a memory and a processor. The memory is used to store executable program code, and the processor is used to call and run the executable program code from the memory, causing the electronic device to execute the code analysis method in the first aspect or any possible implementation thereof.

[0038] Fourthly, a computer program product is provided, comprising: computer program code, which, when run on a computer, causes the computer to execute the code analysis method described in the first aspect or any possible implementation thereof.

[0039] Fifthly, a computer-readable storage medium is provided that stores computer program code, which, when run on a computer, causes the computer to execute the code analysis method described in the first aspect or any possible implementation thereof. Attached Figure Description

[0040] Figure 1 This is a schematic flowchart illustrating a code analysis method provided in an embodiment of this application; Figure 2 This is a schematic diagram of the structure of an electronic device provided in an embodiment of this application; Figure 3 This is a schematic flowchart illustrating another code analysis method provided in an embodiment of this application; Figure 4 This is a schematic diagram of the structure of a code analysis device provided in an embodiment of this application; Figure 5 This is a schematic diagram of the structure of another electronic device provided in an embodiment of this application. Detailed Implementation

[0041] The technical solutions in this application will be clearly and thoroughly described below with reference to the accompanying drawings. In the description of the embodiments of this application, unless otherwise stated, " / " means "or," for example, A / B can mean A or B. "And / or" in the text is merely a description of the relationship between related objects, indicating that three relationships can exist. For example, A and / or B can represent: A existing alone, A and B existing simultaneously, and B existing alone. Furthermore, in the description of the embodiments of this application, "multiple" refers to two or more than two.

[0042] Hereinafter, the terms "first" and "second" are used for descriptive purposes only and should not be construed as implying or suggesting relative importance or implicitly indicating the number of technical features indicated. Thus, a feature defined as "first" or "second" may explicitly or implicitly include one or more of that feature.

[0043] Before introducing the methods of the embodiments of this application, the technical terms that may be involved in the embodiments of this application will be explained first.

[0044] Abstract Syntax Tree (AST): A tree-like representation of the abstract syntactic structure of source code, where each node in the tree represents a syntactic structure in the code.

[0045] tree-sitter is an incrementally embeddable parser generation tool and library for building high-performance, accurate parsers for programming languages.

[0046] Degree centrality refers to the number of direct neighbors a node has, and is used to measure a node's direct connectivity in a graph.

[0047] Betweenness centrality: refers to the number of times a node appears on the shortest path between any two other nodes.

[0048] PageRank originally refers to a measure of a webpage's importance within the overall web's link network. It treats hyperlinks between webpages as votes; the more webpages linking to a page, the higher its score. Furthermore, links from high-authority pages carry greater weight. In this application's embodiment, it specifically refers to an algorithm for measuring node importance in a code knowledge graph. It integrates a node's cold-start prior weight with topological dependency link weights to quantify the importance of code within the entire codebase.

[0049] After explaining the technical terms used in the embodiments of this application, the application scenarios of the embodiments of this application are described below.

[0050] Currently, in the process of software development and maintenance, understanding and becoming familiar with the internal organization structure of the entire code repository and the dependency and calling logic between modules through the entire lifecycle management of software code, including daily development, version iteration, and online operation and maintenance, is the core prerequisite and foundation for improving code analysis speed and reducing software maintenance costs and risks from the root.

[0051] In a codebase, a complete set of business logic typically includes code in multiple programming languages. For example, in a complete business logic framework, web pages, mini-programs, and client-side interfaces are mostly written in front-end languages ​​such as JavaScript, Hyper Text Markup Language (HTML), and Cascading Style Sheets (CSS) to implement page interactions, while back-end business logic is developed using back-end languages ​​such as Python, Java, and Go. Therefore, analyzing complex codebases containing multiple programming languages ​​becomes crucial.

[0052] In addressing the aforementioned issues, related technologies primarily employ single-language parsing tools to parse code from various programming languages ​​separately, or only support a limited number of programming languages. This approach cannot effectively handle complex codebases with a wide range of programming languages, leading to difficulties in understanding cross-language code.

[0053] In view of this, embodiments of this application provide a code analysis method. During implementation, this method determines a unified abstract syntax tree (API) corresponding to the source code of multiple different programming languages ​​in the target code file. This process unifies the syntactic structures of different programming languages, eliminates differences between languages, and achieves a unified representation of cross-language code. Simultaneously, this method is not limited by the number of programming languages ​​and can achieve cross-language analysis and understanding of complex code libraries. Furthermore, based on the unified API and the target code file, a target code knowledge graph is constructed, enabling structured modeling of the relationships between code entities. This transforms complex code structures from text into a visual network of relationships, facilitating subsequent analysis. Finally, by calculating the node weights of each node in the target code knowledge graph, this application can quantify the importance of each code entity within the entire code library, providing reliable data support for code maintenance and optimization, thereby obtaining more reliable code analysis results and improving the accuracy of code analysis.

[0054] It should be understood that the method of this application embodiment is applied to an electronic device, which may be a server, personal computer, laptop, tablet computer or smartphone, etc. This application embodiment does not limit the type of electronic device that performs the method.

[0055] The following will be through Figure 1 The specific implementation process of a code analysis method provided in the embodiments of this application is described in detail.

[0056] Figure 1 This is a schematic flowchart of a code analysis method provided in an embodiment of this application.

[0057] For example, such as Figure 1 As shown, the code analysis method 100 includes steps 101 to 104.

[0058] 101. Based on the target code file to be analyzed, determine the unified abstract syntax tree corresponding to the target code file. The target code file includes multiple source codes written in different programming languages.

[0059] In the implementation of the method in this application embodiment, the electronic device first obtains the target code file to be analyzed. Specifically, the electronic device can obtain the target code file to be analyzed in the following ways: for example, the target code file can be uploaded to the electronic device by a technician, or the electronic device can automatically pull it from a preset code repository or a specified directory. This application embodiment does not limit the method by which the electronic device obtains the target code file.

[0060] As can be seen from the aforementioned deficiencies in the related technologies, the target code files to be analyzed in the embodiments of this application include various source codes written in different programming languages. Here, source code refers to a plain text file written in a programming language according to certain syntax rules.

[0061] Optionally, various programming languages ​​include, but are not limited to, JavaScript, Python, Java, Go, C++, HTML, etc. This application embodiment does not specifically limit the programming language of the target code file.

[0062] It should be understood that each programming language has its own set of independent syntax rules; therefore, the syntax rules of various source codes written in different programming languages ​​will also differ significantly. To eliminate these syntactic differences at the source and facilitate subsequent code analysis, electronic devices first need to parse the various source codes to obtain a Unified Abstract Syntax Tree (UAST). Specifically, a UAST refers to a standard tree-like data structure that maps multiple parsed source codes to the same fixed syntax structure.

[0063] The following section describes the specific generation process of the aforementioned Unified Abstract Syntax Tree.

[0064] One possible implementation involves determining the unified abstract syntax tree (UPN) corresponding to the target code file based on the target code file to be analyzed, including: For any source code among multiple source codes, the source code is parsed using the corresponding syntax parser to generate an initial abstract syntax tree for the source code; Once the initial abstract syntax trees of multiple source codes have been generated, the multiple original nodes included in the initial abstract syntax trees of multiple source codes are converted into multiple standard nodes. A unified abstract syntax tree is generated based on multiple standard nodes.

[0065] It should be understood that the specific process of obtaining the unified abstract syntax tree (API) consists of two steps. The first step involves the electronic device independently parsing the source code of each programming language to obtain an initial API for that language. The second step involves the electronic device performing node standardization on the initial APIs of each programming language to obtain the unified API. Specifically, the initial API is the API structure obtained based on the independent syntax rules provided by each programming language; that is, the API of each programming language before conversion.

[0066] Specifically, during the first step, for the various source codes in the target code file, the electronic device first identifies each programming language based on the file extension (e.g., .py, .java, .go, .ts) and content characteristics (e.g., #! / usr / bin / env python). Furthermore, the electronic device internally maintains a pre-maintained parser registry to record the corresponding syntax parser (Tree-sitter) for each programming language.

[0067] After identifying the specific programming languages, for the source code of any one of these programming languages, the electronic device can dynamically load the Tree-sitter parser corresponding to that programming language based on the parser registry and the current programming language, and parse the source code text of that programming language and convert it into the initial abstract syntax tree (AST) corresponding to that programming language.

[0068] By performing the above parsing steps on the source code of each programming language, we can obtain the initial abstract syntax tree of multiple programming languages, that is, the initial abstract syntax tree of multiple source codes.

[0069] After obtaining the initial abstract syntax tree (AST) of various source codes, the electronic device performs the second step described above. Specifically, the electronic device pre-stores predefined node transformation rules (or mapping rules) to map AST nodes (i.e., original nodes) of various programming languages ​​to unified standard nodes.

[0070] Optionally, the standard node types in this application embodiment include, but are not limited to, function definition nodes, variable declaration nodes, call expression nodes, import statement nodes, class definition nodes, conditional statement nodes, and loop statement nodes. Specifically, function definition nodes represent the function structure defined in the code; variable declaration nodes represent variable information defined in the code; call expression nodes represent function or method call relationships; conditional statement nodes represent branching logic in the code; import statement nodes represent module reference relationships in the code; class definition nodes represent class structure information in the code; and loop statement nodes represent repeated execution logic in the code.

[0071] Based on the above mapping rules, the electronic device traverses each original node of each initial abstract syntax tree, finds the corresponding standard node type, and converts the original node into a matching standard node, thereby eliminating the differences in syntax structure between different programming languages.

[0072] After obtaining the standard nodes corresponding to each original node, for some complex syntactic structures, electronic devices also need to perform dimension detection and dimensionality reduction operations to split the multi-dimensional complex nodes into multiple independent standard nodes, and then reorganize them according to the original hierarchical relationship.

[0073] For example, for compound declaration syntax structures such as JavaScript's `const{a,b}=obj` or Python's `x,y=point`, electronic devices will perform dimension detection and dimensionality reduction, breaking them down into multiple independent, more basic atomic nodes, such as splitting them into two independent variable declaration nodes, while preserving the original assignment relationships, ensuring that the unified abstract syntax tree is consistent with the structure in the source code.

[0074] After obtaining multiple standard nodes through the above steps, the electronic device can automatically create a global virtual root node as the top-level parent node of the final unified abstract syntax tree. It then traverses all standard nodes, taking the standard node corresponding to the root node of each programming language or each initial abstract syntax tree as a child node of the top-level parent node. Based on the relationships between the standard nodes during the parsing process, it recursively attaches lower-level standard nodes such as classes, methods, and variables from top to bottom, thus obtaining the final global unified abstract syntax tree.

[0075] It should be noted that, in the above process, the embodiments of this application also provide an exception handling mechanism. In the event of an exception such as encoding error, file corruption or insufficient operation permissions in the target code file, the electronic device automatically records the exception information and skips the processing of the file, so as to avoid affecting the parsing process of other normal files and ensure the smoothness of code analysis.

[0076] In the above technical solution, when parsing source code of multiple programming languages, this application first obtains an initial abstract syntax tree by parsing the source code using the parser corresponding to each programming language. This ensures that the parsing result completely matches the logic of the source code, guaranteeing the accuracy of syntax parsing. Based on this, the nodes of each initial abstract syntax tree are mapped to obtain standard nodes, allowing all source code to share the same node system. This facilitates unified code analysis and effectively solves the cross-language parsing barrier in the code analysis process.

[0077] 102. Based on the unified abstract syntax tree and the target code file, construct the target code knowledge graph. The graph nodes of the target code knowledge graph are the various code entities in the target code file, and the graph edges of the target code knowledge graph are the association relationships between multiple code entities.

[0078] After obtaining the unified abstract syntax tree, electronic devices can construct a target code knowledge graph based on the unified abstract syntax tree and the target code file, thereby realizing the structured extraction of code entities and their relationships.

[0079] It should be understood that before constructing the target code knowledge graph, in order to centrally manage the information of the unified abstract syntax tree scattered in different files, electronic devices can also build a global index library to classify and store the information of each node, so as to facilitate subsequent fast retrieval and related queries and improve the efficiency of knowledge graph construction.

[0080] In one possible implementation, before constructing the target code knowledge graph based on the unified abstract syntax tree and the target code file, the code analysis method also includes: For any one of the multiple standard nodes, obtain the attribute information and identifier of the standard node; Construct a mapping relationship for standard nodes using the identifier of the standard node as the key and the attribute information of the standard node as the value; Once the mapping relationships of multiple standard nodes have been established, a global node mapping table is obtained based on these relationships.

[0081] The aforementioned global index library is a node information index library used to store the global node mapping table.

[0082] It should be understood that the Unified Abstract Syntax Tree (UPS) obtained in step 101 above only represents the syntactic structure of the target code file. In other words, the UPS cannot contain the semantic information of the target code file, such as the actual meaning of functions or variables and their relationship with the context. Therefore, after obtaining the UPS, the electronic device also needs to store the attribute information of each standard node to facilitate subsequent semantic analysis and relationship identification.

[0083] The attribute information includes parent node reference, scope hierarchy, node type, node name, and location information. Scope hierarchy refers to the node's depth within the nested code structure, used to identify the visibility of variables or functions. Location information refers to the node's line and column number and file path in the source code file. The file path refers to the absolute storage path of the source code containing the node on the device. The node name can be understood as the node's business name in the source code file, such as key fields corresponding to the node in the source code file, like function names or method names, etc.

[0084] Specifically, for each standard node, during the process of generating a unified abstract syntax tree from the initial abstract syntax tree, the electronic device can assign a globally unique node number as the unique identifier for each standard node transformed from the original node, and simultaneously extract the node's name, node type, position information, scope level, and parent node reference. The scope level can be obtained by calculating the nesting depth of the node during the traversal of the initial abstract syntax tree; the parent node reference can be obtained by recording the parent node pointer of the current node while traversing the nodes of the initial abstract syntax tree.

[0085] Based on the unique identifier and attribute information of each standard node, electronic devices can establish a mapping relationship between the standard node, using the unique identifier as the key and the attribute information as the value. This mapping relationship is between the identifier and the attribute information. The attribute information includes the parent node reference field, scope hierarchy, node type, and location information mentioned earlier.

[0086] By establishing the mapping relationship for each standard node, and after the mapping relationship for all standard nodes has been established, the electronic device can summarize the mapping relationships of all standard nodes to obtain the final global node mapping table.

[0087] In the above technical solution, before constructing the code knowledge graph, a global node mapping table is first established using the attribute information and identifiers of standard nodes. This allows for the creation of a unique index identifier for each transformed standard node, enabling subsequent queries to directly locate all attribute information of the standard node through the identifier. This avoids decentralized node queries and improves node retrieval efficiency.

[0088] Based on the obtained global node mapping table, electronic devices can determine the target code knowledge graph according to the unified abstract syntax tree, the global node mapping table, and the target code file.

[0089] One possible implementation involves constructing a target code knowledge graph based on a unified abstract syntax tree and the target code file, including: Based on the unified abstract syntax tree, global node mapping table, and target code files, construct an initial code knowledge graph; The initial code knowledge graph is validated for reasonableness to obtain the target code knowledge graph.

[0090] Specifically, the construction of the target code knowledge graph is divided into two steps. The first step is that the electronic device constructs an initial code knowledge graph based on the unified abstract syntax tree, the global node mapping table, and the target code file. Then, the target code knowledge graph is obtained by verifying the initial code knowledge graph.

[0091] The following section provides a detailed description of the specific process of constructing the initial code knowledge graph.

[0092] One possible implementation involves constructing an initial code knowledge graph based on a unified abstract syntax tree, a global node mapping table, and the target code file, including: Retrieve configuration files for various source codes; The configuration files of various source codes are parsed to obtain global path mapping tables for various source codes. The configuration files are used to define the path mapping rules of the source codes, and the global path mapping tables are used to represent the correspondence between path aliases and base paths. Based on the unified abstract syntax tree, global path mapping table, and global node mapping table, extract the semantic relationships between multiple standard nodes; An initial code knowledge graph is constructed based on multiple standard nodes and the semantic relationships between them.

[0093] Path aliases are short reference names created for files or directories in a project to replace complex relative paths, improving code readability and maintainability.

[0094] For example, in some projects, after setting the "src" directory as a path alias of "@", you can use "import Component from "@ / components / Component" instead of "import Component from ".. / .. / components / Component", thereby reducing the nesting of ".. / " and simplifying the import path.

[0095] A relative path describes the location of a target file relative to the current working directory or a reference directory. It does not begin with the root directory but locates the file relative to the current directory. For example, the path corresponding to .. / .. / in the example above.

[0096] The base path refers to the root path used to specify an application or resource.

[0097] It should be understood that, based on the meaning of path aliases mentioned above, when configuring import paths in source code, path aliases are often used instead of complex relative paths to improve code readability. However, path aliases are abbreviated paths used by developers to simplify complexity and do not contain folder location information. Electronic devices cannot directly locate the real directory address using only path aliases. Therefore, during code parsing, path aliases in the source code need to be pre-mapped to the actual base path to accurately identify file locations.

[0098] Specifically, when performing path mapping, electronic devices can read the configuration files for each programming language. The configuration files are mainly used to define the path mapping rules for each programming language. By parsing the configuration files, the electronic device can obtain the mapping relationship between each path alias defined in the configuration file and its corresponding base path, thus obtaining a global path mapping table.

[0099] It should be understood that the global path mapping table here refers to the correspondence between all path aliases and base paths in each programming language, and is not limited to the correspondence between path aliases and base paths involved in the target code file.

[0100] Optionally, the configuration file type corresponding to the same programming language can be one or more, and this application embodiment does not limit this.

[0101] For example, taking JavaScript as an example, the corresponding configuration files include webpack.config.js, vite.config.js, rollup.config.js, tsconfig.json, and jsconfig.json. Among them, webpack.config.js is the configuration file for the webpack module bundler. vite.config.js is the configuration file for the Vite front-end build tool. rollup.config.js is the configuration file for the Rollup module bundler. jsconfig.json is a configuration file specific to JavaScript projects.

[0102] Taking the programming language TypeScript as an example, the corresponding configuration files include webpack.config.js, vite.config.js, rollup.config.js, and tsconfig.json. Among them, tsconfig.json is the configuration file for the TypeScript programming language. webpack.config.js, vite.config.js, and rollup.config.js are general configuration files that adapt to both JavaScript and TypeScript.

[0103] For each programming language, the electronic device can read its corresponding configuration file, prioritizing regular expression matching and syntax parsing to parse the path alias field and extract the mapping between path aliases and base paths. Based on this, the mapping between each path alias and base path extracted from the configuration files of all programming languages ​​forms the aforementioned global path mapping table. The key fields used to define path aliases differ across different configuration files.

[0104] For example, with the configuration file webpack.config.js, the path alias field can be the alias field; with the configuration file vite.config.js, the path alias field can be a nested resolve.alias field; with the configuration file tsconfig.json, the path alias field is the paths field; and with the configuration file package.json, the path alias field is the exports field.

[0105] It should be understood that the above-described regular expression matching and syntax parsing methods are applicable to situations where the format is standardized and the configuration file contains clear and explicit path alias fields. In practical scenarios, for dynamic alias paths in JS / TS source code that contain environment variables and conditional branches, regular expression matching and syntax parsing cannot obtain accurate mapping relationships. In this embodiment, a Large Language Model (LLM) is also introduced to convert dynamically changeable alias paths into fixed static path mapping relationships.

[0106] For example, if a path alias configured in a source code is `alias:{'@':process.env.NODE_ENV==='production'?path.resolve(_dirname,'dist'):path.resolve(_dirname, 'src')}`, where the path alias `@` corresponds to different base paths in the development and production environments, when the LLM model parses the above dynamic path alias, the ternary conditional expression corresponding to the dynamic path alias (`process.env.NODE_ENV==='production'?path.resolve(_dirname,'dist'):path.resolve(_dirname,'src')}`) is used as the input text for the LLM. The LLM, through its code semantic understanding capabilities learned during training, identifies the syntactic structure of this ternary conditional expression and determines whether it is a condition for judgment. The process involves two branches: a truth branch and a false branch, where the condition is `process.env.NODE_ENV === 'production'`. These branches split into two mapping branches for the path alias: the first branch is for the production environment (`path.resolve(__dirname, 'dist')`), and the second branch is for the development environment (`path.resolve(__dirname, 'src')`). After LLM parsing, the multi-branch mapping result for the alias path is output. The absolute directory address (e.g., ` / project / dist` or ` / project / src`) obtained from the branch's calculations is then used as the final base path, thus completing the static mapping of the dynamic path alias.

[0107] It should also be understood that in the Go programming language, each module's root directory contains a `go.mod` file. The first line of this file is usually the `module` directive, which defines the project's unique identifier, i.e., the address of the code repository, and directly determines the base import path for all packages in the project. For example, if `go.mod` declares `module github.com / user / project`, the system first recognizes this module declaration statement, extracts the module path as the project root identifier, and uses this as the base path prefix for all internal imports within this module.

[0108] The `require` statements in this configuration file are used to declare, line by line, the names of external third-party modules that the project depends on for execution and compilation, along with their corresponding locked version numbers. The electronic device parses each `require` configuration item, extracts the logical import path and version constraint information of the external dependent modules, records them in the module dependency list, and marks the import as belonging to the scope of external third-party dependencies. When parsing the corresponding import statements in the `.go` source code later, this list can be used to determine that the reference is not a module from the project's own source code; it is only recorded in the knowledge graph as a dependency on this external component, and will not be searched for in the project's global symbol table to match the corresponding source code node.

[0109] The `replace` statement in this configuration file is used to force the address of a remote dependency module to be mapped to a specified local directory path on the local machine. The device records this mapping relationship and prioritizes replacing it with the specified local path when addressing dependencies. The `exclude` statement is used to specify the dependency versions that are prohibited from being used. The excluded versions are skipped directly during the resolution process to avoid dependency version conflicts.

[0110] If a project has multiple independent go.mod submodule configuration files at different directory levels, the device builds an overall module dependency graph and creates an independent path resolution context for each submodule. The root module prefix and dependency replacement rules of each submodule are isolated from each other and do not overlap.

[0111] For relative path imports in the source code without module prefixes, the actual addressing path of the target file is calculated by using the folder containing the go.mod file of the submodule to which the current .go file belongs as the base directory; if there is a vendor dependency cache directory in the project root directory, the native Go addressing priority is followed, and third-party dependencies are read first from the source code path in the vendor directory.

[0112] Subsequently, the electronic device reads each `require` dependency declaration, `replace` path replacement rule, and `exclude` version exclusion constraint from the current `go.mod` file, records the external module information required by the project, the path rewriting mapping relationship from remote dependencies to local folders, and directly removes dependency versions prohibited by the `exclude` field during dependency address parsing. After completing the full path rule collection, the electronic device parses the complete import path of each cross-module import statement in the source code and distinguishes between three types of imports based on their origin: for imports of Go programming language built-in standard libraries such as `fmt`, the code graph association and construction process is skipped; for imports from github.com / gin- Imports of third-party open-source libraries like gonic / gin, which are introduced via the require statement, only mark the project's reference association to the external component in the dependency relationship, without searching the project's internal symbol table. For local module imports like example.com / internal / pkg, which are prefixed with the root path of this module and point to the project's own source code, the standard physical path of the referenced file is calculated by combining the previously generated path mapping context. The corresponding syntax nodes are matched based on the global UAST symbol table, and a formal semantic dependency association edge is established between the referrer node and the referenced definition node. Finally, all module rules and import associations are integrated to generate a complete path mapping relationship for the Go programming language.

[0113] Thus, through the above process, the electronic device can obtain the complete path mapping relationship of all programming language environments in the target code, that is, the global path mapping table.

[0114] After obtaining the global path mapping table, the electronic device can extract the semantic relationships of multiple standard nodes in the unified abstract syntax tree based on the unified abstract syntax tree, the global path mapping table, and the global node mapping table. Then, based on the multiple standard nodes and the semantic relationships between them, an initial code knowledge graph can be constructed.

[0115] The extraction process of the above semantic relationships will be described in detail below.

[0116] One possible implementation involves extracting semantic relationships between multiple standard nodes based on a unified abstract syntax tree, a global path mapping table, and a global node mapping table, including: For any import node in the unified abstract syntax tree, obtain the import path and identifier of the import node; When the import path of an import node is a path alias, the actual file path of the import node is determined based on the import path of the import node and the global path mapping table; when the import path of an import node is not a path alias, the actual file path of the import node is determined through the path mapping strategy corresponding to the import path of the import node. Based on the identifier and actual file path of the imported node, the global node mapping table is searched to determine the first defined node; based on the imported node and the first defined node, the first semantic association relationship of the imported node is constructed. For any reference node in the unified abstract syntax tree other than multiple import nodes, obtain the identifier of the reference node, and search the global node mapping table according to the identifier of the reference node to determine the second definition node; construct the second semantic association relationship of the reference node based on the reference node and the second definition node. The first semantic association relationship of multiple imported nodes and the second semantic association relationship of multiple referenced nodes are determined as the semantic association relationship between multiple standard nodes.

[0117] Specifically, when extracting semantic relationships, the electronic device, in conjunction with the aforementioned pre-established global path mapping table, first traverses multiple standard nodes in the Unified Abstract Syntax Tree (UAST) to identify import nodes. Import nodes are nodes in the UAST that describe the syntactic structures used to import other modules or packages in the code. The purpose of prioritizing import nodes here is that they serve as the initiating nodes of cross-file reference relationships and are the fundamental entry points for building cross-file dependencies. Other standard nodes, while capable of forming syntactic call relationships within a single source code file, lack the ability to carry external file addressing path information. Therefore, when extracting global semantic relationships, it is necessary to prioritize traversing all import nodes as the starting point of the association chain.

[0118] For example, during the traversal process, the electronic device can determine whether the current standard node is an import node (i.e., the aforementioned import statement node) by using keywords or the node type in the attribute information of the standard node.

[0119] When the currently traversed standard node is an import node, different path resolution strategies are used to process the import node depending on whether its import path is an alias path. First, the electronic device can obtain the import path of the import node and obtain its identifier based on its attribute information.

[0120] In the first case, when the import path of the import node is a path alias, based on the aforementioned global path mapping table, the electronic device can retrieve the base path corresponding to the import path in the global path mapping table according to the import path of the import node, and convert it into the actual file path through path completion processing.

[0121] For example, if the import path is @ / components / Button, and the global mapping table is configured with a mapping rule for the @ / prefix corresponding to the project source code directory src / , the electronic device will replace the alias prefix @ / in the import path with the actual base path src / , and then combine it with the project root directory prefix to generate an intermediate path with the root directory, such as / project_root / src / components / Button. Furthermore, the electronic device will perform suffix completion on this intermediate path to obtain the actual file path / project_root / src / components / Button.vue.

[0122] For example, when the import path is ~ / utils / helpers, if the global mapping table is configured with a mapping rule for the ~ / prefix corresponding to the project source code directory src / utils / , the electronic device will replace the alias prefix ~ / in the import path with the actual base path src / utils / , and then combine it with the project root directory prefix to generate an intermediate path with the root directory, such as / project_root / src / utils / helpers. Furthermore, the electronic device will perform suffix completion on this intermediate path to obtain the actual file path / project_root / src / utils / helpers.ts.

[0123] It should be noted that for some special import scenarios, regarding the conditional export logic configured in the `exports` field of the `package.json` file of a Node.js project, the electronic device first extracts the module import identifier corresponding to the import node, traverses and parses the hierarchical structure of the `exports` object within the target dependency package's `package.json`, and splits out the import alias, multiple sets of judgment conditions, and the resource paths bound to each condition. Then, it identifies the module import specification (ESModule import / CommonJS import) and runtime environment parameters of the current project, matches the only effective condition branch according to the priority rules built into the `exports` field, and uses the file path corresponding to this branch to complete the mapping and replacement of the import alias, obtaining the replaced intermediate path. Subsequently, it fully adopts the completion logic for the above path alias import scenario to complete the extension of the intermediate path, and finally converts it to obtain the actual file path.

[0124] For TypeScript ternary quote directive / / / <reference path="..." / >During the source code scanning phase, the electronic device captures such comment instructions through format matching and extracts the path text within the path parameter. This path is treated as a special type of non-standard import path and processed according to its type: if it is an alias path, the global path mapping table is queried to complete the alias replacement; if it is a relative path, the directory level is calculated based on the current source code file location to generate the corresponding intermediate path. Subsequently, the completion logic in the above path alias import scenario is used to complete the intermediate path and finally generate the actual file path.

[0125] In the second case, when the import path of the imported node is not a path alias, this can be further subdivided into the following situations.

[0126] (1) If the import path of the import node is a relative path, such as . / component, .. / utils, etc. The specific path mapping strategy is as follows: The electronic device first obtains the absolute disk path of the source code file where the statement of the current import node is located, combines the directory hierarchy of the file, traces back to the root directory of the project, then concatenates the relative path to obtain the intermediate path, and then performs suffix completion to obtain the actual file path.

[0127] (2) If the file extension of the import path of the import node is missing, the specific path mapping strategy is: the electronic device automatically completes common file extensions, such as .js, .ts, .jsx, .tsx, .go, .java, etc., to obtain the actual file path.

[0128] (3) If the import path of the imported node is a directory import (e.g., import '. / utils'), the specific path mapping strategy is as follows: The electronic device first automatically locates the folder directory corresponding to . / utils and searches for the index files (e.g., index.js, index.ts) in the directory in order. If an index file is found, the electronic device directly uses the path of the index file as the actual file path. If no index file is found, the electronic device reads the package.json configuration in the folder directory corresponding to . / utils, reads the entry file name configured in the main field, and concatenates them to generate the actual file path.

[0129] Thus, through the above steps, the electronic device can obtain the actual file path of the imported node.

[0130] Furthermore, after obtaining the actual file path of the imported node, before actually parsing each source code file, the electronic device needs to pre-establish a list of available identifiers for each programming language to handle default references in the source code files. For example: console, window, and document for JavaScript / TypeScript; print and len for Python; and all classes under the java.lang package for Java. Each built-in identifier is modeled as a "virtual definition node" in the system, containing metadata such as name, language, and type description.

[0131] During symbol resolution, for any import node in the Unified Abstract Syntax Tree (UAST), the electronic device can look up the corresponding first definition node in the global node mapping table based on the import node's identifier and actual file path. The definition node specifically refers to the node at the original declaration location of the identifier in the source code. Furthermore, based on the import node and the first definition node, the electronic device creates a first semantic association to record the reference chain of the identifier from its declaration location to its reference location.

[0132] Specifically, the electronic device first uses the identifier of the imported node as the key to search for a list of candidate definition nodes in the global node mapping table. It then performs precise matching and filtering based on the actual file path, prioritizing definition nodes in the same file or directory as the first definition node. If the search process hits a re-export node, it recursively traces the export link back to the original declaration location of the identifier to determine the first definition node. Finally, based on the imported node and the first definition node, a corresponding association record is generated as the first semantic association.

[0133] Furthermore, for reference nodes of other types besides import nodes in the Unified Abstract Syntax Tree (UAST) (such as CallExpression, Identifier, New Expression, etc.), electronic devices construct a nested scope chain from the inside out through the UAST hierarchy, searching for candidate identifiers by following the rules of identifier definition level by level from the innermost scope. For JavaScript, the hoisting logic for var declarations is handled separately, correcting the definition position of var-modified variables within a function scope to the top of the scope, avoiding misalignment of definition searches due to the order of source code writing. During the traversal and search process, if multiple scopes encounter duplicate symbols, variable shadowing scenarios are identified, prioritizing the variable in the current inner scope as the valid definition, and shielding the interference of outer variables with the same name. Variable hoisting refers to the syntax mechanism in JavaScript where var-declared variables have their lifetime raised to the top of the scope during the scope pre-resolution phase. Variable shadowing refers to the syntax rule that inner identifiers with the same name in nested scopes will override outer synchronization symbols and be preferentially referenced by the current line of code.

[0134] After completing the scope hierarchy constraints, the electronic device then uses the node identifier as the key to retrieve the list of candidate definition nodes in the global node mapping table, and performs matching and filtering based on the context scope of the current file. It prioritizes matching definition nodes within the same module or parent scope as the second definition node. If a secondary transit export identifier is matched, the original second definition node is also located, and finally, the corresponding second semantic association relationship between the reference node and the second definition node is generated.

[0135] The electronic device summarizes and integrates the first semantic relationships of all imported nodes and the second semantic relationships of all referenced nodes to obtain a complete set of semantic relationships between all standard nodes in the unified abstract syntax tree.

[0136] After obtaining the complete semantic relationships between standard nodes, the electronic device combines the aforementioned standard nodes to construct an initial code knowledge graph.

[0137] Specifically, the electronic device uses multiple standard nodes as entity nodes in the initial code knowledge graph. The types of entity nodes include function / method nodes, class nodes, variable nodes, type definition nodes, and module nodes, corresponding to the aforementioned node types. Function / method nodes store function names, parameter lists, return types, and access modifiers. Class nodes store class names, inheritance relationships, and interface implementations. Variable nodes store variable names, data types, scope, initial values, and whether they are exported. Type definition nodes store type names, generic parameters, and inheritance constraints. In addition, each node also carries location information such as its associated file path, start line number, and end line number.

[0138] At the same time, the electronic device generates corresponding entity edges (i.e., graph edges) based on the semantic relationships analyzed above, which are used to connect two standard nodes with semantics such as calling, dependency, and inheritance.

[0139] Optionally, the semantic relationships between two standard nodes include import relationships, call relationships, inheritance relationships, dependency relationships, and containment relationships. Import relationships represent reference dependencies between modules, established through import statements. Call relationships represent the execution call chain between functions or methods. Inheritance relationships represent the parent-child hierarchy between classes or interfaces. Dependency relationships represent the use of other entities by variables or modules. Containment relationships represent the affiliation of a module to its submodules or members.

[0140] The initial code knowledge graph constructed above is stored in the form of an adjacency list, including a node dictionary and an edge dictionary. The node dictionary stores all entity node information with the unique identifier of the node as the key, and the edge dictionary stores all entity edge information with the source node identifier as the key.

[0141] Furthermore, to improve the retrieval efficiency of electronic devices, this application embodiment also establishes several efficient indexing methods, including a trie index, a suffix tree index, a hash index, and a spatial index. Among them, the trie index supports fast path prefix matching for module path searching; the suffix tree index supports fast suffix matching for file extension and type name searching; the hash index enables fast lookup based on node identifier, name, and path; and the spatial index provides range queries based on code location.

[0142] After obtaining the initial code knowledge graph, the electronic device further verifies its rationality to obtain the final target code knowledge graph used for analysis.

[0143] Specifically, the steps for validating the rationality of the initial code knowledge graph include the following aspects: (1) Invalid reference and circular dependency removal check.

[0144] The electronic device traverses all graph edges within the initial code knowledge graph, extracts the target file path carried by each graph edge, accesses the local file system, and verifies whether the source file corresponding to the path actually exists. If the file does not exist, the import relationship is marked as an invalid reference, and the graph edge is removed or an exception is marked in the initial knowledge code graph.

[0145] A depth-first traversal is used to recursively traverse dependency links downwards along the graph edges of import relationships. During the traversal, a path stack is maintained. If a file node already existing in the stack is encountered again during the traversal, it indicates that a circular dependency cycle has been detected. For example, A imports B, B imports C, and C imports A in turn, forming a closed loop. The electronic device automatically marks all nodes and graph edges involved in the entire loop and provides optimization suggestions to break the circular dependency based on module dependency priority and import level.

[0146] (2) Configure consistency verification.

[0147] Retrieve all path aliases such as @ / and ~ / from the global path mapping table, and verify whether the underlying real directory / file path pointed to by the alias is accessible within the project; if the target path of the alias is missing or the directory does not exist, determine that the alias configuration is invalid and mark the configuration inconsistency problem.

[0148] Read the version numbers of third-party modules declared in package management configurations such as package.json, go.mod, and pom.xml; compare them with the actual project runtime dependency versions parsed from the initial code knowledge graph, check whether the two are compatible, whether there are version conflicts, and whether there are high and low version mismatch issues, and record the risk items of version inconsistency.

[0149] Within the same scope, it searches for instances where identifiers with the exact same name are defined multiple times, and it checks for entities with the same name across modules globally, distinguishing between legitimate overloading and illegal naming conflicts; it adds conflict markers to conflicting nodes, indicating the conflict location and duplicate definitions.

[0150] For multi-language mixed-language engineering scenarios, verify the mapping contract of cross-language calls. For example, check whether the field and type constraints of the front-end TypeScript interface structure match the field names, data types, and input / output parameter structures of the back-end Java entity class. If fields are missing, types do not match, or parameter lists are inconsistent, determine that the cross-language interface mapping is incompatible and write a verification exception report.

[0151] (3) Syntax error and parsing failure.

[0152] When the source code contains syntax errors that prevent the parser from traversing it, the electronic device performs partial parsable content extraction and inserts dedicated placeholder nodes to replace the missing entities in the completely unparseable code regions.

[0153] When the code uses experimental syntax or custom extended syntax that is fully incorporated into the standard, the electronic device calls a preset heuristic rule base to perform inferential parsing based on grammatical features and context, extracting as many dependencies and entity information as possible, and adding confidence scores to the graph nodes and edges generated by this illegal syntax.

[0154] (4) Code consistency check.

[0155] Electronic devices check code style consistency, verify the grouping and ordering of import statements, check the consistency of global naming conventions (camel case, snake case, Pascal case), and identify unused imported but not deleted code.

[0156] After the above-mentioned rationality verification, the electronic device can obtain the target code knowledge graph.

[0157] 103. Calculate the weights of M graph nodes in the target code knowledge graph to obtain the target weights of the M graph nodes, where M is a positive integer greater than 1.

[0158] After obtaining the final target code knowledge graph through step 102, the electronic device can calculate the weights of the M graph nodes contained in the target code knowledge graph to obtain the target weight of each graph node.

[0159] In one possible implementation, weights are calculated for M graph nodes in the target code knowledge graph to obtain the target weights of the M graph nodes, including: For any graph node among the M graph nodes, obtain the multidimensional importance feature of the graph node in the target code knowledge graph. The multidimensional importance feature is used to represent the coreness of the graph node in the target code knowledge graph. The initial weights of the graph nodes are obtained by weighted fusion of the multidimensional importance features of the graph nodes. Given the initial weights of the M graph nodes, the target weights of the M graph nodes are determined based on the initial weights of the M graph nodes and the target code knowledge graph.

[0160] Specifically, for any graph node, the determination of the target weight of the graph node is divided into two stages. The first stage is to calculate the initial weight of the graph node, and the second stage is to correct the initial weight based on the target code knowledge graph to obtain the target weight.

[0161] In this embodiment, the initial weight is also referred to as the "cold start weight," which is the basic weight value calculated based on the static structural features of the code. The cold start weight is obtained by weighted fusion of multi-dimensional importance features. Optionally, the multi-dimensional importance features include graph structure weight, code structure weight, semantic feature weight, and usage pattern weight.

[0162] Among them, graph structure weights reflect the topological importance of nodes in the network, code structure weights reflect the degree of organization and standardization of the code itself, semantic feature weights measure the semantic relevance of node naming to its context, and pattern weights characterize the frequency and scope of node invocation. The process of determining each weight will be described in detail below.

[0163] For any graph node, after obtaining its multidimensional importance features, the electronic device can perform weighted fusion of the multidimensional importance features according to preset feature weight ratios to obtain the initial weight of the graph node. For M graph nodes, the preset feature weight ratios corresponding to the multidimensional importance features are fixed when calculating the initial weight of each graph node.

[0164] The calculation process of the initial weight of any graph node can be represented by the following formula (1).

[0165] Formula (1) In formula (1): W 0( v ): Graph node v The initial weights; W g ( v ): Graph node v Graph structure weights; W c ( v ): Graph node v Code feature weights; W s ( v ): Graph node v semantic feature weights; W u ( v ): Graph node v Usage pattern weight; α The proportion of the graph structure weight can be 0.5 in this embodiment. βThe proportion of code feature weights can be 0.25 in this embodiment. γ The proportion of semantic feature weights can be 0.15 in this embodiment. δ The proportion of pattern weights used can be 0.1 in this embodiment.

[0166] Therefore, by performing the initial weight calculation steps described above for each graph node, the electronic device can obtain the initial weights of the M graph nodes. Furthermore, the electronic device can combine the initial weights of the M graph nodes with the topological structure of the target code knowledge graph to perform weight correction, thereby obtaining the target weights for each graph node.

[0167] It should be noted that in practical applications, the number and type of multidimensional importance features can be flexibly adjusted according to the actual scenario. The above is merely an exemplary configuration provided in this application embodiment. Correspondingly, the preset feature weight ratio can also be dynamically adjusted according to requirements.

[0168] In the above technical solution, the initial weights of graph nodes are calculated using multi-dimensional weighting, taking into account the importance of each node in the graph structure from various aspects, making the weight calculation more objective and accurate. Furthermore, correcting the initial weights using the target code knowledge graph can further reflect the actual propagation impact of nodes in the overall dependency network, improving the accuracy of graph node weight calculation.

[0169] The specific methods for determining the aforementioned multi-dimensional weights are as follows.

[0170] In one possible implementation, the multidimensional importance features include at least one of the graph structure weights, code feature weights, semantic feature weights, and usage pattern weights of the graph node. The multidimensional importance features of the graph node in the target code knowledge graph are obtained, including: Based on the topological features of the graph nodes, the graph structure weights of the graph nodes are calculated. The topological features are used to represent the connection state of the graph nodes in the target code knowledge graph. The code feature weights of the graph nodes are determined based on the source code features corresponding to the graph nodes in the target code file. Determine the semantic feature weights of the graph nodes based on their semantic keywords; The usage pattern weights of graph nodes are determined based on their usage in the target code knowledge graph.

[0171] Specifically, the graph structure weights are calculated based on the topological features of the graph nodes. These topological features represent the connections between the graph node and other graph nodes in the target code knowledge graph, reflecting the breadth and scope of connections within the graph node.

[0172] Optionally, the topological features of a graph node include at least one of weighted in-degree, weighted out-degree, number of relation types, and edge confidence. Weighted in-degree refers to the sum of the weights of all incoming edges pointing to the node, weighted out-degree refers to the sum of the weights of all outgoing edges pointing from the node to other nodes, number of relation types refers to the number of different relation types associated with the node, and edge confidence refers to the degree of confidence of the corresponding graph edge.

[0173] For a given graph node, the electronic device can count all graph edges pointing to that node, calculate the edge weight of each edge, and sum them to obtain the weighted in-degree. The edge weights of each graph edge in the target code knowledge graph can be pre-defined according to the semantic relationship type. For example, invocation relationships are specifically divided into four types: active invocation, passive dependency, direct invocation, and indirect invocation. In this embodiment, the edge weight of an active invocation graph edge can be set to 0.8, the edge weight of a passive dependency graph edge to 0.2, the edge weight of a direct invocation graph edge to 0.9, and the edge weight of an indirect invocation graph edge to 0.1.

[0174] Similarly, weighted out-degree can be calculated by counting all graph edges emitted by the graph node and summing the edge weights of each graph edge.

[0175] The electronic device can count the number of different relationship types associated with the node to obtain the number of relationship types.

[0176] Edge confidence refers to the confidence level of all graph edges associated with a given graph node. Based on the foregoing, when a graph edge is generated using illegal syntax, the edge confidence is generated using heuristic rules; when a graph edge is generated using standard syntax, the edge confidence defaults to 1.

[0177] After obtaining the weighted in-degree, weighted out-degree, number of relation types, and edge confidence, the electronic device can further average the confidence of all graph edges associated with the graph node to obtain the average edge confidence. Then, it can further perform a weighted summation of the weighted in-degree, weighted out-degree, number of relation types, and average edge confidence to obtain the graph structure features. The weights of the weighted in-degree, weighted out-degree, number of relation types, and average edge confidence can be set as needed. In other implementations, the feature types included in the topological features and the weights of each type can also be appropriately adjusted; this embodiment does not limit this.

[0178] The code feature weights can be calculated from the source code features corresponding to the graph nodes in the target code file. Specifically, the source code features are dynamically adapted based on the node type of the graph node.

[0179] For example, when the node type is a file node, the source code characteristics include code functions and the number of functions; when the node type is a class node, the source code characteristics include the number of lines of code, the number of methods, the inheritance depth, and the number of interfaces; when the node type is a function node, the source code characteristics include the number of lines of code, the number of parameters, the number of branches, and the nesting depth.

[0180] Based on this, when calculating the code feature weights corresponding to the current graph node, the electronic device first determines and acquires the appropriate source code features according to the node type of the graph node. For example, taking a function node as an example, the electronic device can determine the number of lines of code based on attribute information, the number of parameters based on the parameter list of the function node, the number of branches based on the unified abstract syntax tree, and the nesting depth by statistically analyzing the nesting level of code blocks.

[0181] After obtaining the various source code features, the electronic device further normalizes these features to obtain normalized source code features. Then, it performs a weighted sum of these normalized features to obtain the code feature weights. The weights of each source code feature can be set as needed.

[0182] The semantic feature weighting is essentially a process of semantic parsing and role mapping of node names. First, the electronic device obtains the name strings of the graph nodes (such as class names, function names, or variable names) and performs word segmentation to extract multiple keywords. Further, the electronic device matches each keyword with a predefined multi-level semantic lexicon.

[0183] The semantic lexicon is divided into multiple categories based on architectural roles, with each category assigned a different base score. For example, the entry point category (matching main, entry, start, bootstrap, etc., base score 0.8), the control layer (Controller, Router, API) has a base score of 0.7, the business service layer (Service, Business) has a base score of 0.6, the configuration / factory layer (Config, Factory) has a base score of 0.5, and the data model layer (Entity, DTO, VO) has a base score of 0.4. If no category is matched, the base score is set to 0.3. If a keyword matches multiple categories, the highest base score is used.

[0184] The entry point class refers to the code layer that is executed and loaded first. The controller layer class receives HTTP requests from the frontend, validates input parameters, intercepts requests, calls the business layer, and returns the response. The business service layer is the core business logic layer, used to receive instructions from the controller, process data, and return results. The configuration / factory class manages application configurations and creates object instances. The data model class carries the definition of data transmission objects.

[0185] After obtaining the base score corresponding to each keyword of the graph node, the average of the base scores of multiple keywords is taken as the semantic feature weight.

[0186] For usage pattern weights, the electronic device can count the number of times a graph node is imported, called, and inherited in the target code knowledge graph. The number of imports refers to the number of graph edges of the import type pointing to the graph node; the number of calls refers to the number of graph edges of the call type pointing to the graph node; and the number of inheritances refers to the number of graph edges of the inheritance type pointing to the graph node. Furthermore, the electronic device normalizes these quantities and then performs a weighted fusion of the normalized quantities to obtain the usage pattern weights. The weights for each quantity can be set as needed, and this embodiment does not limit this.

[0187] The following section details the process of determining the target weights of M graph nodes based on their initial weights and the target code knowledge graph.

[0188] In one possible implementation, the target weights of the M graph nodes are determined based on their initial weights and the target code knowledge graph, including: Assign edge weights to each edge of the target code knowledge graph; Based on the initial weights of the M graph nodes and the edge weights of each graph edge in the target code knowledge graph, the global importance scores of the M graph nodes are iterated in multiple rounds to obtain the target global importance scores of the M graph nodes. The global importance scores are used to represent the comprehensive influence of the graph nodes in the target code knowledge graph. The target weights of the M graph nodes are determined based on their global importance scores.

[0189] The specific allocation method for the edge weights of the above-mentioned graph edges is described above and will not be repeated here.

[0190] It should be understood that, in determining the target weights of each graph node, this application specifically introduces the Graph-Scorer centrality evaluation algorithm. The initial weights of the M graph nodes obtained above are used as personalized prior initial scores for the PageRank iteration process, replacing the traditional method of uniformly distributing the initial scores of PageRank nodes. During the iteration process, the electronic device performs multiple rounds of weighted information propagation and iterative updates on the global importance scores of the nodes calculated by PageRank iteration until all node scores converge and stabilize. The final converged global importance scores (i.e., ratings) of the M graph nodes are then the target global importance scores for the M graph nodes.

[0191] Among them, the global importance score is used to represent the overall importance of the graph nodes in the entire target code knowledge graph on a global scale.

[0192] After obtaining the global importance scores of the M graph nodes, the electronic device can also combine the multidimensional centrality indices of the graph nodes to obtain the target weights of the M graph nodes. The reason for combining the multidimensional centrality indices of the graph nodes is that different centrality indices can reflect the importance of nodes from different dimensions, such as degree centrality and betweenness centrality, to make up for the limitations of a single scoring dimension and make the weight results more comprehensively reflect the actual importance of the nodes.

[0193] The following section details the implementation process of obtaining the global importance score of M graph nodes through multiple iterations.

[0194] In one possible implementation, based on the initial weights of the M graph nodes and the edge weights of each graph edge in the target code knowledge graph, the global importance score of the M graph nodes is iterated through multiple rounds to obtain the target global importance score of the M graph nodes, including: During the i-th iteration, for any graph node among the M graph nodes, determine any upstream node among the M graph nodes that points to the graph node, where i is a positive integer greater than or equal to 1; Based on the (i-1)th round global importance score of the upstream node, the edge weights of the upstream node pointing to the graph node, the cumulative edge weights of the upstream node, and the initial weights of the graph node, the i-th round global importance score of the graph node is obtained. When i=1, the (i-1)th round global importance score of the upstream node is the weight after normalization of the initial weights of the upstream node, and the cumulative edge weights are the sum of the edge weights of all outgoing edges of the upstream node. Given the i-th round global importance scores of M graph nodes, if the i-th round global importance scores of the M graph nodes satisfy the preset convergence condition, the i-th round global importance scores of the M graph nodes are determined as the target global importance scores of the M graph nodes; if the i-th round global importance scores of the M graph nodes do not satisfy the preset convergence condition, the (i+1)-th round of iteration is executed, i+1=i, and the steps for determining the i-th round global importance scores of the M graph nodes are repeated.

[0195] It should be understood that, before conducting multiple iterations, in order to ensure the iteration convergence rate, this application proposes an error tolerance threshold that dynamically determines the iteration convergence based on the number of nodes, used to determine when the iteration process terminates. For example, when the number of nodes is no greater than 50, the error tolerance threshold is equal to 0.01 minus 0.000125 multiplied by the difference between the number of nodes and 10; when the number of nodes is between 50 and 1000, the error tolerance threshold is equal to 0.005 minus 0.00008 multiplied by the difference between the number of nodes and 50; when the number of nodes is greater than 1000, the error tolerance threshold is equal to 0.001 minus 0.00225 multiplied by the difference between the number of nodes and 100.

[0196] Taking the i-th iteration as an example, in the i-th iteration, for any graph node, the global importance score of that graph node in the i-th iteration is called the "i-th iteration global importance score".

[0197] The calculation process of the global importance score of any graph node in the i-th round can be represented by the following formula (2).

[0198] Formula (2) In formula (2): P ( v ): Graph nodes v The weights after normalization of the initial weights of each graph node are used as the initial global importance score in the iteration process, that is, the global importance score when i=0. W 0( v ): Graph nodes v The initial weights; ε : Extremely small positive numbers, avoid denominators of 0; The sum of the initial weights of the M graph nodes; d Damping factor, usually taken as 0.85, represents the probability of a random jump; PR (t+ 1)( v ): The final graph node obtained in the current iteration process v Global importance score; PR ( t ()( u ): In the previous iteration, the graph nodes v any upstream node u The global importance score, i.e., the upstream node u For dependent graph nodes v upstream node u As the dependent node, the graph node v For dependent nodes; w ( u , v ): From any upstream node u Pointing to the current graph node v The edge weights (connection strengths) of the graph edges. w ( u , z ): Any upstream node u Points to any downstream node it is connected to. z The edge weight, i.e., the weight of the downstream node. z upstream node u The nodes it depends on, downstream nodes z For the dependent node, the upstream node u As a dependent node, the summation result of this item is the upstream node. u The cumulative edge weights.

[0199] The upstream nodes mentioned above refer to the nodes that initiate dependencies and reference other nodes, and are the nodes connected to the starting points of directed edges in the target knowledge code graph; the downstream nodes refer to the nodes that are depended on by other nodes and receive the weights passed on by them, and are the nodes connected to the ending points of directed edges.

[0200] Combining the calculation method of formula (2), in the i-th iteration process, for any graph node v Electronic devices can acquire map nodes v Any upstream node in the target code knowledge graph u The (i-1)th round of global importance scoring PR ( t ()( u (Where, when i=1, the upstream node...) u The (i-1)th round of global importance scoring PR ( t ()( u ) is the upstream nodeu Initial weights after normalization P ( u Meanwhile, based on the edge weights of each graph edge, the electronic device can obtain information from the upstream node. u Pointing to graph nodes v edge weights of the graph edges w ( u , v Then calculate the upstream node. u Multiple graph edges (i.e., upstream nodes) between the upstream node and all its downstream nodes. u The sum of the edge weights of all outgoing edges is used to obtain the upstream node. u The cumulative edge weight is the result calculated within the second summation symbol in the second half of the second row of formula (2).

[0201] Furthermore, electronic devices are based on upstream nodes. u The (i-1)th round of global importance score, upstream node u Pointing to graph nodes v edge weights of the graph edges w ( u , v ) and upstream nodes u The cumulative edge weights can be used to determine the upstream node. u The importance score component for the graph node is all the calculation results within the first summation symbol in the second half of the second row of formula (2).

[0202] Specifically, the above calculation of upstream nodes u In the process of scoring the importance of the graph nodes, according to the calculation process shown in formula (2), the electronic device first assigns the upstream node to the graph node. u The (i-1)th round of global importance score and upstream node u Pointing to graph nodes v edge weights of the graph edges w ( u , v Multiplying the two together gives the upstream node. u For graph nodes v The importance contribution, and then the upstream nodes u The ratio of the importance contribution to the cumulative edge weight is used to obtain the upstream node. u For graph nodes v Importance rating components.

[0203] By using the graph nodes v The importance scores of all upstream nodes are summed, and the summation result is multiplied by the damping factor to obtain the graph nodes. vThe importance score is passed on during the iteration process, which is the result of the calculation of the second term after the plus sign in formula (2).

[0204] Based on this, and further based on the graph nodes v Normalize the initial weights of the graph nodes. v The initial weights, normalized weights, and (1- d Multiply by , and obtain the graph nodes during the iteration process. v The basic weight part is the calculation result of the first term before the plus sign in formula (2). Finally, the transitive part of the importance score is added to the basic weight part to obtain the graph node. v The i-th round of global importance scoring.

[0205] It should be noted that when a node has no outward imports or calls, it will not point to any other node; this is called a "dangling node." Combining this with formula (2) above, when the upstream node... u No downstream nodes z When the cumulative edge weight is 0, i.e. the denominator is 0, the dangling node will not be able to pass on the importance contribution to other nodes. In this embodiment of the application, in order to solve this problem, the weight of the dangling node is evenly distributed to all other nodes, i.e. the cumulative edge weight in formula (2) is the normalized weight of the initial weight of the dangling node, thereby ensuring the normal progress of the iteration process.

[0206] After obtaining the i-th round global importance scores of M graph nodes through the above process, the error tolerance of this iteration (i.e., the i-th round iteration error) can be determined based on the M i-th round global importance scores, and compared with the aforementioned error tolerance threshold to determine whether the i-th round global importance scores of the M graph nodes meet the preset convergence conditions.

[0207] When the global importance scores of the M graph nodes in the i-th round satisfy the preset convergence condition, then the global importance scores of the M graph nodes in the i-th round are the target global importance scores of the M graph nodes. Specifically, the global importance score of any graph node in the i-th round is the target global importance score of that graph node.

[0208] The process for determining whether the global importance scores of the M graph nodes in the i-th round meet the preset convergence conditions is as follows.

[0209] In one possible implementation, code analysis also includes: Given the i-th round global importance scores of M graph nodes, obtain the (i-1)-th round global importance scores of the M graph nodes; The iteration error of the i-th round is determined based on the global importance scores of the M graph nodes in the i-th round and the global importance scores of the M graph nodes in the (i-1)-th round. If the iteration error in the i-th round is less than or equal to the preset error, the global importance scores of the M graph nodes in the i-th round are determined to satisfy the preset convergence condition. If the iteration error in the i-th round is greater than the preset error, the global importance score of the M graph nodes in the i-th round does not meet the preset convergence condition.

[0210] Specifically, the electronic device can determine a first scoring vector based on the i-th round global importance scores of the M graph nodes, and a second scoring vector based on the (i-1)-th round global importance scores of the M graph nodes, and calculate the distance between the first and second scoring vectors as the i-th round iteration error. Optionally, the distance between the two vectors can be Euclidean distance, Manhattan distance, or cosine similarity, etc., and this embodiment does not limit this.

[0211] When the iteration error of the i-th round is less than or equal to the preset error (i.e., the error tolerance threshold pre-calibrated by the number of nodes), the electronic device determines that the global importance score of the M graph nodes in the i-th round meets the preset convergence condition, and determines the global importance score of the M graph nodes in the i-th round as the target global importance score of the M graph nodes.

[0212] Conversely, when the iteration error of the i-th round is greater than the preset error, the electronic device determines that the global importance score of the M graph nodes in the i-th round does not meet the preset convergence condition. Then, it continues to iterate the (i+1)-th round of iteration and sets i+1=i, repeating the above steps for determining the global importance score of the M graph nodes in the i-th round.

[0213] After obtaining the global importance scores of the M graph nodes, the process of determining the target weights of the M graph nodes by combining the multidimensional centrality index is as follows.

[0214] In one possible implementation, the target weights of the M graph nodes are determined based on their global importance scores, including: For any graph node among M graph nodes, obtain the degree centrality and betweenness centrality of the graph node; The fusion centrality of the graph nodes is determined based on their degree centrality and betweenness centrality. The target weight of a graph node is determined based on its fusion centrality and global target importance score.

[0215] Degree centrality refers to the number of edges directly connecting a node. In a directed graph, it is divided into in-degree (the number of edges pointing to that node) and out-degree (the number of edges pointing from that node to other nodes). Betweenness centrality refers to the frequency with which a node is located on all paths in a network; it is the proportion of shortest paths between all pairs of nodes that pass through that node.

[0216] Specifically, the in-degree and out-degree of degree centrality can be calculated using the following formula (3).

[0217] Formula (3) In formula (3): in ( v ): Graph nodes v The number of incoming edges; out ( v ): Graph nodes v The number of outgoing edges; M -1: Theoretically, a single node can be pointed to by all other nodes at most; C in ( v ): Graph nodes v in-degree; C out (v): Graph Nodes v The degree of departure.

[0218] By weighted summing of the in-degree and out-degree values, we can obtain the graph nodes. v Degree centrality, denoted as " C degree ( v The weights of in-degree and out-degree can be set according to requirements.

[0219] The calculation process of betweenness centrality can be obtained by the following formula (4).

[0220] Formula (4) In formula (4): σ ( s,t ):node s To the node t The total number of shortest paths, s ≠ t ; σ ( s , t |v ):node s To the node t And passing through nodes v The number of shortest paths; BC raw ( v ): Primal betweenness centrality; C between ( v ): Normalized betweenness centrality, betweenness centrality in the embodiments of this application; ( M -1)( M -2): The maximum number of combinations of node pairs in a directed graph.

[0221] Based on the above formula, when calculating the target weight of any graph node, the electronic device can first obtain the degree centrality and betweenness centrality of the graph node.

[0222] In calculating target weights, to eliminate cross-project metric discrepancies, electronic devices can normalize the degree centrality, betweenness centrality, and global importance scores of graph nodes before fusion. For any one of the degree centrality, betweenness centrality, and global importance scores, the normalization process is specifically divided into three stages.

[0223] Phase 1: Logarithmic transformation.

[0224] Apply a base-10 logarithmic transformation to the original numerical value of this term, the specific formula is as follows: Clog ( v )= log 10 ( C ( v )+1). Among them, C ( v ) represents the original value of this item. Clog ( v ) represents the value of this term after logarithmic transformation.

[0225] Second stage: Extreme value normalization.

[0226] This step is to force the logarithmically transformed values ​​to be mapped to the [0,1] interval. The specific formula is as follows: C minmax ( v )=( Clog ( v )- min ( C _ log )) / ( max ( C_log )- min ( C_log )+ ε ).in, ε It is a very small positive number. C minmax ( v () represents the value after extreme value normalization. min ( C _ log () refers to the minimum value of this term after logarithmic transformation of M graph nodes. max ( C _ log ) refers to the maximum value of this item after logarithmic transformation of M graph nodes.

[0227] Third stage: Quantile normalization.

[0228] Specifically, the electronic device performs parallel computation based on rank-quantile normalized values, preserving the relative order of the weight distribution and preventing outliers. The rank of each of the M graph nodes is obtained by arranging this item in ascending order. r ( v )∈{1, ..., M}. Quantile normalized value when M=1 Cquantile ( v Set M to 0.5; use the average rank when there are identical scores; when M > 1: Cquantile ( v )=( r ( v )-1) / ( M -1).

[0229] Finally, the electronic device takes a weighted average of the extreme value normalized value and the quantile normalized value of this term to obtain the final normalized result of this term. C final ( v )= ω · C minmax ( v )+( 1 -ω)· Cquantile ( v ),in ω 0.6 is acceptable. C final ( v The result is the final normalized result.

[0230] When calculating the target weight of any graph node, the final normalized degree centrality, betweenness centrality, and target global importance score of the graph node can be obtained by normalizing the degree centrality, betweenness centrality, and target global importance score of the graph node according to the above three stages.

[0231] Finally, the electronic device fuses the final normalized degree centrality, the final normalized betweenness centrality, and the final normalized global importance score of the target to obtain the target weight of the graph node. The specific expression is shown in the following formula (5).

[0232] Formula (5) In formula (5): w final ( v ): Graph nodes v The target weight; C aux ( v ): Degree centrality after final normalization C finaldegree ( v and the betweenness centrality after final normalization C finalbetween ( v The weighted result of ) η 0.5 is acceptable; ρ 0.6 or 0.7 can be used.

[0233] Therefore, by calculating the target weights of M graph nodes according to the above formula (5) for each graph node, the target weights of M graph nodes can be obtained.

[0234] In the above technical solution, when calculating the target weight of the graph node, two types of centrality indicators, degree centrality and betweenness centrality, are introduced, which can more comprehensively reflect the influence of the node at the local and global levels and improve the accuracy and reliability of the weight calculation.

[0235] 104. Based on the target weights of the M graph nodes, determine the code analysis results of the target code file.

[0236] After obtaining the target weights of the M graph nodes according to step 103, before generating the code analysis results of the target code file, the electronic device can first calculate the code activity of the target code knowledge graph to count the call frequency and modification number of each node, and then further obtain the code analysis report.

[0237] In one possible implementation, before determining the code analysis results of the target code file based on the target weights of the M graph nodes, the code analysis method further includes: Perform code activity analysis on the target code file to obtain a code activity report; Furthermore, based on the target weights of the M graph nodes, the code analysis results of the target code file are determined, including: Based on the target weights of the M graph nodes, determine the node classification labels of the M graph nodes and the importance ranking results of the M graph nodes; Based on the importance ranking of M graph nodes, the node classification labels of M graph nodes, and the code activity report, code analysis results are generated.

[0238] Specifically, electronic devices can break down each `import` / `require` statement in the code into import symbols, traverse the global code file, track all actual usage locations of the import symbol within the project, and statistically analyze the overall usage frequency and common usage patterns of the import item. If an import symbol, after completing a full project search, does not find any actual call, assignment, or reference scenarios, it is marked as an unused dead import. By comparing multiple import statements within the same module, duplicate imports and redundant alias imports of the same module member (e.g., executing `import{A}from module` and `import{AasA1}from module` sequentially) are identified and determined to be redundant imports.

[0239] In addition, the electronic device traverses the definition locations of all custom functions and methods, reverses the entire project call tree, and counts the number of times the function is explicitly called; when only the function definition exists and no upper-level code initiates the call, it is marked as an unused function.

[0240] For code blocks enclosed by conditional compilation directives such as #ifdef and #if, the compilation condition judgment logic is analyzed; combined with the project compilation configuration and platform compilation parameters, it is determined whether the corresponding condition has the possibility of triggering execution, and code blocks whose conditions are always false and can never be executed during program execution are marked as unreachable idle code.

[0241] This analysis covers dynamic imports and module loading, handling dynamic import expressions using `import()`, analyzing asynchronous loading methods like `require.ensure()` and `System.import()`, and identifying dynamic module loading based on configuration or user input. It constructs variable definition-usage chains through data flow analysis, identifies uninitialized variable usage, and analyzes variable lifecycles and scope escape. It identifies functions with side effects (modifying global state, performing I / O operations) and pure functions (no side effects, transparent references), and analyzes data dependencies between functions.

[0242] By summarizing all the above analysis results, a code activity report can be obtained.

[0243] When constructing the code analysis report, the electronic device first determines the node classification labels and importance ranking results of the M graph nodes based on the target weights of the M graph nodes.

[0244] Specifically, in this embodiment, different node classification labels are assigned according to different target weight values. For example, when the target weight ≥ P 95 At the 95th percentile, the node classification label is key; when P 95 >Target weight ≥ P 75 When P is active, the node classification label is considered important; when P is active, the node classification label is considered important. 75 >Target weight ≥ P 25 When P is in the general category, the node classification label is "general"; when P is in the general category, the node classification label is "general". 25 When the target weight is set, the node classification label is secondary.

[0245] The electronic device sorts the target weights of M graph nodes in descending order to obtain an importance ranking result. Furthermore, the electronic device integrates the importance ranking result, node classification labels, and code activity report to generate structured code analysis results. This allows developers to quickly locate core issues and optimization directions in the code based on the code analysis report, improving code maintenance efficiency and the overall code quality of the project.

[0246] In the above technical solution, the final code analysis result is generated based on the importance ranking of M graph nodes, node classification labels, and code activity analysis report. This can comprehensively evaluate code quality, maintainability, and potential risk levels, providing a quantitative basis for subsequent code refactoring and optimization. It can also help developers effectively identify key issues and high-risk areas in the code.

[0247] Figure 2 This is a schematic diagram of the structure of an electronic device provided in an embodiment of this application.

[0248] For example, such as Figure 2 As shown, the electronic device 200 includes a system for code analysis, which is divided into functional modules, specifically including a code parsing module 201, a semantic relationship extraction module 202, a knowledge graph construction module 203, a weight calculation module 204, and a result generation module 205.

[0249] The code parsing module 201 is used to parse the syntax structure of different programming languages ​​in the target code file to obtain a unified abstract syntax tree.

[0250] The semantic association extraction module 202 is used to extract entity information and its semantic relationships from the code based on the unified abstract syntax tree.

[0251] The knowledge graph construction module 203 is used to abstract code entities into graph nodes and semantic relationships into graph edges, thereby constructing a multi-level code knowledge graph structure.

[0252] The weight calculation module 204 is used to calculate the target weight of each graph node and to divide the importance ranking results and node classification labels.

[0253] The results generation module 205 is used to combine the code activity report, the importance ranking results of each graph node, and the node classification labels to generate structured code analysis results.

[0254] To facilitate understanding of the methods in the embodiments of this application, the following will further illustrate... Figure 3 The entire implementation process of the method is described.

[0255] Figure 3 This is a schematic flowchart illustrating another code analysis method provided in the embodiments of this application.

[0256] For example, such as Figure 3 As shown, the code analysis method 300 includes the following steps 301 to 312.

[0257] 301. Based on any source code in the target code file to be analyzed, the source code is parsed using the corresponding syntax parser to generate an initial abstract syntax tree for the source code.

[0258] 302. After the initial abstract syntax trees of multiple source codes have been generated, convert the multiple original nodes included in the initial abstract syntax trees of multiple source codes into multiple standard nodes.

[0259] 303. Construct a unified abstract syntax tree based on multiple standard nodes.

[0260] 304 indicates that the configuration files of various source codes are parsed to obtain a global path mapping table.

[0261] 305. Based on the unified abstract syntax tree, global path mapping table, and global node mapping table, extract the semantic relationships between multiple standard nodes.

[0262] 306. Construct an initial code knowledge graph based on multiple standard nodes and the semantic relationships between them.

[0263] 307. Perform a rationality check on the initial code knowledge graph to obtain the target code knowledge graph.

[0264] 308. For any graph node, determine the initial weight of the graph node.

[0265] 309. Based on the initial weights of the M graph nodes and the edge weights of each graph edge in the target code knowledge graph, the global importance score of the M graph nodes is iterated multiple times to obtain the target global importance score of the M graph nodes.

[0266] 310. Determine the target weights of M graph nodes based on the target global importance score of the graph nodes, the degree centrality and betweenness centrality of the graph nodes.

[0267] 311. Based on the target weights of the M graph nodes, determine the node classification labels of the M graph nodes and the importance ranking results of the M graph nodes.

[0268] 312. Generate code analysis results based on the importance ranking of M graph nodes, the node classification labels of M graph nodes, and the code activity report.

[0269] Steps 301 to 312 in the above code analysis method 300 have the same inventive concept as steps 101 to 104 in the code analysis method 100. For details, please refer to the description of the aforementioned code analysis method 100, which will not be repeated here.

[0270] In summary, this application provides a code analysis method that, during implementation, determines a unified abstract syntax tree (API) corresponding to the source code of multiple different programming languages ​​in the target code file. This process unifies the syntactic structures of different programming languages, eliminates differences between languages, and achieves a unified representation of cross-language code. Furthermore, this method is not limited by the number of programming languages ​​and can achieve cross-language analysis and understanding of complex code libraries. Further, based on the unified API and the target code file, a target code knowledge graph is constructed, enabling structured modeling of the relationships between code entities. This transforms complex code structures from text into a visual network of relationships, facilitating subsequent analysis. Finally, by calculating the node weights of each node in the target code knowledge graph, this application quantifies the importance of each code entity within the entire code library, providing reliable data support for code maintenance and optimization, thereby obtaining more reliable code analysis results and improving the accuracy of code analysis.

[0271] Figure 4 This is a schematic diagram of the structure of a code analysis device provided in an embodiment of this application.

[0272] For example, such as Figure 4 As shown, the code analysis device 400 includes: The determination module 401 is used to determine the unified abstract syntax tree corresponding to the target code file to be analyzed, which includes multiple source codes written in different programming languages. The construction module 402 is used to construct a target code knowledge graph based on the unified abstract syntax tree and the target code file. The graph nodes of the target code knowledge graph are the code entities in the target code file, and the graph edges of the target code knowledge graph are the association relationships between multiple code entities. The determining module 401 is also used to calculate the weights of M graph nodes in the target code knowledge graph to obtain the target weights of the M graph nodes, where M is a positive integer greater than 1. The determining module 401 is also used to determine the code analysis result of the target code file based on the target weights of the M graph nodes.

[0273] In one possible implementation, the determining module 401 is further configured to: for any one of the multiple source codes, parse the source code using the syntax parser corresponding to the source code to generate an initial abstract syntax tree for the source code; when the initial abstract syntax trees of the multiple source codes have been generated, convert the multiple original nodes included in the initial abstract syntax trees of the multiple source codes into multiple standard nodes; and generate the unified abstract syntax tree based on the multiple standard nodes.

[0274] In one possible implementation, before constructing the target code knowledge graph based on the unified abstract syntax tree and the target code file, the construction module 402 is further configured to: for any standard node among the multiple standard nodes, obtain the attribute information and identifier of the standard node; construct the mapping relationship of the standard node using the identifier of the standard node as the key and the attribute information of the standard node as the value; and, after all the mapping relationships of the multiple standard nodes have been constructed, obtain a global node mapping table based on the mapping relationships of the multiple standard nodes.

[0275] In one possible implementation, the building module 402 is further configured to: construct an initial code knowledge graph based on the unified abstract syntax tree, the global node mapping table, and the target code file; and perform a rationality check on the initial code knowledge graph to obtain the target code knowledge graph.

[0276] In one possible implementation, the building module 402 is further configured to: obtain configuration files for the various source codes; parse the configuration files for the various source codes to obtain a global path mapping table for the various source codes, wherein the configuration files define the path mapping rules for the source codes and the global path mapping table represents the correspondence between path aliases and base paths; extract the semantic relationships between the multiple standard nodes based on the unified abstract syntax tree, the global path mapping table, and the global node mapping table; and construct the initial code knowledge graph based on the multiple standard nodes and the semantic relationships between the multiple standard nodes.

[0277] In one possible implementation, the building module 402 is further configured to: for any import node in the unified abstract syntax tree, obtain the import path and identifier of the import node; if the import path of the import node is a path alias, determine the actual file path of the import node according to the import path of the import node and the global path mapping table; if the import path of the import node is not a path alias, determine the actual file path of the import node through the path mapping strategy corresponding to the import path of the import node; search the global node mapping table according to the identifier of the import node and the actual file path of the import node to determine a first definition node; construct a first semantic association relationship of the import node according to the import node and the first definition node; for any reference node in the unified abstract syntax tree other than multiple import nodes, obtain the identifier of the reference node, and search the global node mapping table according to the identifier of the reference node to determine a second definition node; construct a second semantic association relationship of the reference node according to the reference node and the second definition node; and determine the first semantic association relationship of the multiple import nodes and the second semantic association relationship of the multiple reference nodes as the semantic association relationship between the multiple standard nodes.

[0278] In one possible implementation, the determining module 401 is further configured to: for any graph node among the M graph nodes, obtain the multidimensional importance feature of the graph node in the target code knowledge graph, the multidimensional importance feature being used to represent the coreness of the graph node in the target code knowledge graph; perform weighted fusion on the multidimensional importance feature of the graph node to obtain the initial weight of the graph node; and, given the initial weights of the M graph nodes, determine the target weights of the M graph nodes based on the initial weights of the M graph nodes and the target code knowledge graph.

[0279] In one possible implementation, the multidimensional importance feature includes at least one of the graph structure weight, code feature weight, semantic feature weight, and usage pattern weight of the graph node. The determining module 401 is further configured to: calculate the graph structure weight of the graph node based on its topological features, where the topological features represent the connection state of the graph node in the target code knowledge graph; determine the code feature weight of the graph node based on the source code features corresponding to the graph node in the target code file; determine the semantic feature weight of the graph node based on its semantic keywords; and determine the usage pattern weight of the graph node based on its usage results in the target code knowledge graph.

[0280] In one possible implementation, the determining module 401 is further configured to: assign edge weights to each graph edge of the target code knowledge graph; perform multiple iterations on the global importance score of the M graph nodes based on the initial weights of the M graph nodes and the edge weights of each graph edge of the target code knowledge graph to obtain the target global importance score of the M graph nodes, the global importance score being used to represent the comprehensive influence of the graph nodes in the target code knowledge graph; and determine the target weight of the M graph nodes based on the target global importance score of the M graph nodes.

[0281] In one possible implementation, the determining module 401 is further configured to: during the i-th iteration, for any graph node among the M graph nodes, determine any upstream node among the M graph nodes pointing to that graph node, where i is a positive integer greater than or equal to 1; obtain the i-th round global importance score of the graph node based on the (i-1)-th round global importance score of the upstream node, the edge weight of the upstream node pointing to the graph node, the cumulative edge weight of the upstream node, and the initial weight of the graph node; when i=1, the (i-1)-th round global importance score of the upstream node is the initial weight of the upstream node. The renormalized weights are the sum of the weights of all outgoing edges of the upstream node. Given the i-th round global importance scores of the M graph nodes, if the i-th round global importance scores of the M graph nodes satisfy a preset convergence condition, then the i-th round global importance scores of the M graph nodes are determined as the target global importance scores of the M graph nodes. If the i-th round global importance scores of the M graph nodes do not satisfy the preset convergence condition, the (i+1)-th round of iteration is executed, setting i+1=i, and the steps for determining the i-th round global importance scores of the M graph nodes are repeated.

[0282] In one possible implementation, the determining module 401 is further configured to: obtain the (i-1)th round global importance score of the M graph nodes after obtaining the i-th round global importance score of the M graph nodes; determine the i-th round iteration error based on the i-th round global importance score and the (i-1)th round global importance score of the M graph nodes; determine that the i-th round global importance score of the M graph nodes satisfies the preset convergence condition if the i-th round iteration error is less than or equal to a preset error; and determine that the i-th round global importance score of the M graph nodes does not satisfy the preset convergence condition if the i-th round iteration error is greater than the preset error.

[0283] In one possible implementation, the determining module 401 is further configured to: for any graph node among the M graph nodes, obtain the degree centrality and betweenness centrality of the graph node; determine the fusion centrality of the graph node based on the degree centrality and betweenness centrality of the graph node; and determine the target weight of the graph node based on the fusion centrality of the graph node and the target global importance score of the graph node.

[0284] In one possible implementation, before determining the code analysis result of the target code file based on the target weights of the M graph nodes, the determining module 401 is further configured to: perform code activity analysis on the target code file to obtain a code activity report; and the determining module is further configured to: determine the node classification labels of the M graph nodes and the importance ranking result of the M graph nodes based on the target weights of the M graph nodes; and generate the code analysis result based on the importance ranking result of the M graph nodes, the node classification labels of the M graph nodes, and the code activity report.

[0285] Figure 5 This is a schematic diagram of the structure of another electronic device provided in an embodiment of this application.

[0286] For example, such as Figure 5 As shown, the electronic device 500 includes a memory 501 and a processor 502. The memory 501 stores executable program code 5011, and the processor 502 is used to call and execute the executable program code 5011 to perform a code analysis method.

[0287] This embodiment can divide the electronic device into functional modules according to the above method example. For example, each module can correspond to a separate functional module, or two or more functions can be integrated into one processing module. The integrated module can be implemented in hardware. It should be noted that the module division in this embodiment is illustrative and only represents one logical functional division. In actual implementation, there may be other division methods.

[0288] When functional modules are divided according to their respective functions, the electronic device may include: a determination module and a construction module, etc. It should be noted that all relevant content of each step involved in the above method embodiments can be referenced from the functional description of the corresponding functional module, and will not be repeated here.

[0289] The electronic device provided in this embodiment is used to execute the above-described code analysis method, and thus can achieve the same effect as the above-described implementation method.

[0290] When using integrated units, the electronic device may include a processing module and a storage module. The processing module is used to control and manage the operation of the electronic device. The storage module is used to support the execution of relevant program code and data by the electronic device.

[0291] The processing module may be a processor or a controller, which can implement or execute various exemplary logic blocks, modules, and circuits shown in conjunction with the disclosure of this application. The processor may also be a combination of functions that implement computing capabilities, such as a combination of one or more microprocessors, a combination of digital signal processing (DSP) and a microprocessor, etc., and the storage module may be a memory.

[0292] This embodiment also provides a computer-readable storage medium storing computer program code. When the computer program code is run on a computer, the computer executes the aforementioned related method steps to implement a code analysis method in the above embodiment.

[0293] This embodiment also provides a computer program product that, when run on a computer, causes the computer to perform the aforementioned related steps to implement a code analysis method as described in the above embodiment.

[0294] In addition, the electronic device provided in the embodiments of this application may specifically be a chip, component or module. The electronic device may include a connected processor and a memory. The memory is used to store instructions. When the electronic device is running, the processor may call and execute the instructions to make the chip execute a code analysis method in the above embodiments.

[0295] In this embodiment, the electronic device, computer-readable storage medium, computer program product or chip are all used to execute the corresponding methods provided above. Therefore, the beneficial effects that can be achieved can be referred to the beneficial effects of the corresponding methods provided above, and will not be repeated here.

[0296] Through the above description of the embodiments, those skilled in the art will understand that, for the sake of convenience and brevity, only the division of the above functional modules is used as an example. In actual applications, the above functions can be assigned to different functional modules as needed, that is, the internal structure of the device can be divided into different functional modules to complete all or part of the functions described above.

[0297] In the embodiments provided in this application, it should be understood that the disclosed apparatus and methods can be implemented in other ways. For example, the apparatus embodiments described above are merely illustrative. For instance, the division of modules or units is only a logical functional division, and in actual implementation, there may be other division methods. For example, multiple units or components may be combined or integrated into another device, or some features may be ignored or not executed. Furthermore, the coupling or direct coupling or communication connection shown or discussed may be through some interfaces; the indirect coupling or communication connection between devices or units may be electrical, mechanical, or other forms.

[0298] The above description is merely a specific embodiment of this application, but the scope of protection of this application is not limited thereto. Any variations or substitutions that can be easily conceived by those skilled in the art within the scope of the technology disclosed in this application should be included within the scope of protection of this application. Therefore, the scope of protection of this application should be determined by the scope of the claims.

Claims

1. A code analysis method, characterized in that, The code analysis method includes: Based on the target code file to be analyzed, determine the unified abstract syntax tree corresponding to the target code file, wherein the target code file includes multiple source codes written in different programming languages; Based on the unified abstract syntax tree and the target code file, a target code knowledge graph is constructed. The graph nodes of the target code knowledge graph are the code entities in the target code file, and the graph edges of the target code knowledge graph are the association relationships between multiple code entities. The target weights of the M graph nodes in the target code knowledge graph are calculated to obtain the target weights of the M graph nodes, where M is a positive integer greater than 1. Based on the target weights of the M graph nodes, the code analysis results of the target code file are determined.

2. The code analysis method according to claim 1, characterized in that, The step of determining the unified abstract syntax tree corresponding to the target code file based on the target code file to be analyzed includes: For any one of the multiple source codes, the source code is parsed using the syntax parser corresponding to the source code to generate an initial abstract syntax tree for the source code; Once the initial abstract syntax trees of the various source codes have been generated, the multiple original nodes included in the initial abstract syntax trees of the various source codes are converted into multiple standard nodes. The unified abstract syntax tree is generated based on the multiple standard nodes.

3. The code analysis method according to claim 2, characterized in that, Before constructing the target code knowledge graph based on the unified abstract syntax tree and the target code file, the code analysis method further includes: For any one of the plurality of standard nodes, obtain the attribute information and identifier of the standard node; Using the identifier of the standard node as the key and the attribute information of the standard node as the value, construct the mapping relationship of the standard node; Once the mapping relationships of all the standard nodes have been established, a global node mapping table is obtained based on these relationships.

4. The code analysis method according to claim 3, characterized in that, The step of constructing a target code knowledge graph based on the unified abstract syntax tree and the target code file includes: Based on the unified abstract syntax tree, the global node mapping table, and the target code file, an initial code knowledge graph is constructed. The initial code knowledge graph is validated for reasonableness to obtain the target code knowledge graph.

5. The code analysis method according to claim 4, characterized in that, The step of constructing an initial code knowledge graph based on the unified abstract syntax tree, the global node mapping table, and the target code file includes: Obtain the configuration files for the various source codes; The configuration files of the various source codes are parsed to obtain a global path mapping table for the various source codes. The configuration files are used to define the path mapping rules of the source codes, and the global path mapping table is used to represent the correspondence between path aliases and base paths. Based on the unified abstract syntax tree, the global path mapping table, and the global node mapping table, extract the semantic relationships between the multiple standard nodes; The initial code knowledge graph is constructed based on the multiple standard nodes and the semantic relationships between them.

6. The code analysis method according to claim 5, characterized in that, The step of extracting the semantic relationships between the multiple standard nodes based on the unified abstract syntax tree, the global path mapping table, and the global node mapping table includes: For any import node in the unified abstract syntax tree, obtain the import path and identifier of the import node; If the import path of the import node is a path alias, the actual file path of the import node is determined according to the import path of the import node and the global path mapping table; if the import path of the import node is not a path alias, the actual file path of the import node is determined through the path mapping strategy corresponding to the import path of the import node. Based on the identifier of the imported node and the actual file path of the imported node, the global node mapping table is searched to determine the first defined node; based on the imported node and the first defined node, the first semantic association relationship of the imported node is constructed. For any reference node in the unified abstract syntax tree other than multiple import nodes, obtain the identifier of the reference node, and search the global node mapping table according to the identifier of the reference node to determine the second definition node; construct the second semantic association relationship of the reference node according to the reference node and the second definition node; The first semantic association relationship of the multiple imported nodes and the second semantic association relationship of the multiple referenced nodes are determined as the semantic association relationship between the multiple standard nodes.

7. The code analysis method according to claim 1, characterized in that, The step of calculating the weights of the M graph nodes in the target code knowledge graph to obtain the target weights of the M graph nodes includes: For any of the M graph nodes, obtain the multidimensional importance feature of the graph node in the target code knowledge graph, where the multidimensional importance feature is used to represent the coreness of the graph node in the target code knowledge graph; The multidimensional importance features of the graph nodes are weighted and fused to obtain the initial weights of the graph nodes; Given the initial weights of the M graph nodes, the target weights of the M graph nodes are determined based on the initial weights of the M graph nodes and the target code knowledge graph.

8. The code analysis method according to claim 7, characterized in that, The multidimensional importance features include at least one of the graph structure weight, code feature weight, semantic feature weight, and usage pattern weight of the graph node. Obtaining the multidimensional importance features of the graph node in the target code knowledge graph includes: Based on the topological features of the graph nodes, the graph structure weights of the graph nodes are calculated, whereby the topological features are used to represent the connection state of the graph nodes in the target code knowledge graph. The code feature weight of the graph node is determined based on the source code features corresponding to the graph node in the target code file; The semantic feature weights of the graph nodes are determined based on their semantic keywords. The usage pattern weight of the graph node is determined based on the usage results of the graph node in the target code knowledge graph.

9. The code analysis method according to claim 7, characterized in that, The step of determining the target weights of the M graph nodes based on their initial weights and the target code knowledge graph includes: Assign edge weights to each edge of the target code knowledge graph; Based on the initial weights of the M graph nodes and the edge weights of each graph edge in the target code knowledge graph, the global importance scores of the M graph nodes are iterated in multiple rounds to obtain the target global importance scores of the M graph nodes. The global importance scores are used to represent the comprehensive influence of the graph nodes in the target code knowledge graph. The target weights of the M graph nodes are determined based on their global importance scores.

10. The code analysis method according to claim 9, characterized in that, The process of iterating the global importance score of the M graph nodes multiple times based on the initial weights of the M graph nodes and the edge weights of each graph edge of the target code knowledge graph to obtain the target global importance score of the M graph nodes includes: During the i-th iteration, for any graph node among the M graph nodes, determine any upstream node among the M graph nodes that points to the graph node, where i is a positive integer greater than or equal to 1; The global importance score of the graph node in the (i-1)th round is obtained based on the edge weights of the upstream node pointing to the graph node, the cumulative edge weights of the upstream node, and the initial weights of the graph node. When i=1, the global importance score of the upstream node in the (i-1)th round is the weight after normalization of the initial weights of the upstream node, and the cumulative edge weights are the sum of the edge weights of all outgoing edges of the upstream node. Given the i-th round global importance scores of the M graph nodes, if the i-th round global importance scores of the M graph nodes satisfy a preset convergence condition, the i-th round global importance scores of the M graph nodes are determined as the target global importance scores of the M graph nodes; if the i-th round global importance scores of the M graph nodes do not satisfy the preset convergence condition, the (i+1)-th round of iteration is executed, i+1=i, and the determination steps of the i-th round global importance scores of the M graph nodes are repeated.

11. The code analysis method according to claim 10, characterized in that, The code analysis also includes: Given the i-th round global importance score of the M graph nodes, obtain the (i-1)-th round global importance score of the M graph nodes; The iteration error of the i-th round is determined based on the global importance scores of the M graph nodes in the i-th round and the global importance scores of the M graph nodes in the (i-1)-th round. If the iteration error of the i-th round is less than or equal to the preset error, it is determined that the global importance score of the M graph nodes in the i-th round satisfies the preset convergence condition. If the iteration error in the i-th round is greater than the preset error, it is determined that the global importance score of the M graph nodes in the i-th round does not meet the preset convergence condition.

12. The code analysis method according to any one of claims 9 to 11, characterized in that, The step of determining the target weights of the M graph nodes based on their global target importance scores includes: For any of the M graph nodes, obtain the degree centrality and betweenness centrality of the graph node; The fusion centrality of the graph nodes is determined based on their degree centrality and betweenness centrality. The target weight of the graph node is determined based on the fusion centrality and the target global importance score of the graph node.

13. The code analysis method according to claim 1, characterized in that, Before determining the code analysis result of the target code file based on the target weights of the M graph nodes, the code analysis method further includes: Perform code activity analysis on the target code file to obtain a code activity report; And, determining the code analysis result of the target code file based on the target weights of the M graph nodes includes: Based on the target weights of the M graph nodes, determine the node classification labels of the M graph nodes and the importance ranking results of the M graph nodes; The code analysis results are generated based on the importance ranking of the M graph nodes, the node classification labels of the M graph nodes, and the code activity report.

14. A code analysis device, characterized in that, The code analysis device includes: The determination module is used to determine the unified abstract syntax tree corresponding to the target code file based on the target code file to be analyzed. The target code file includes multiple source codes written in different programming languages. The construction module is used to construct a target code knowledge graph based on the unified abstract syntax tree and the target code file. The graph nodes of the target code knowledge graph are the code entities in the target code file, and the graph edges of the target code knowledge graph are the association relationships between multiple code entities. The determining module is further configured to perform weight calculation on M graph nodes in the target code knowledge graph to obtain the target weights of the M graph nodes, where M is a positive integer greater than 1; The determining module is further configured to determine the code analysis result of the target code file based on the target weights of the M graph nodes.

15. An electronic device, characterized in that, The electronic device includes: Memory, used to store executable program code; A processor for calling and running the executable program code from the memory, causing the electronic device to perform the code analysis method as described in any one of claims 1 to 13.

16. A computer-readable storage medium, characterized in that, The computer-readable storage medium stores a computer program that, when executed, implements the code analysis method as described in any one of claims 1 to 13.

17. A computer program product, characterized in that, The computer program product includes computer program code, which, when run on a computer, implements the code analysis method as described in any one of claims 1 to 13.