Code optimization method and system based on knowledge graph
By constructing abstract syntax trees and context dependency graphs based on knowledge graphs and combining them with large language models for code refactoring, the problem of not being able to deeply understand code dependencies in existing technologies is solved, and flexible code optimization and high-quality refactoring solutions are achieved.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-12-19
- Publication Date
- 2026-03-31
AI Technical Summary
Existing code optimization methods cannot deeply understand the complex dependencies between code segments, resulting in limited optimization effects. They are unable to flexibly cope with diverse code scenarios and complex code problems, and have a narrow scope of application.
An abstract syntax tree is constructed based on a knowledge graph to identify code snippets to be optimized. A context dependency graph is then built in conjunction with the code optimization knowledge graph. Structured refactoring is performed through sliding window decomposition and a large language model to generate a high-quality refactoring solution.
It can dynamically adjust according to the specific context and dependencies of the code, expand the scope of code optimization, improve the optimization effect, and meet the current code optimization needs.
Smart Images

Figure CN121764474A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of artificial intelligence technology, and in particular to a code optimization method and system based on knowledge graphs. Background Technology
[0002] In the current software development field, with the continuous expansion of software system scale and the increasing complexity of its functions, software systems generally suffer from problems such as verbose code implementation, mixed languages, and high complexity. In particular, a large amount of repetitive and redundant code not only increases the size of the codebase and reduces code readability, but also leads to excessive logical branches and chaotic dependencies, resulting in a sharp increase in understanding and maintenance costs. Therefore, code optimization has become a key aspect of ensuring the stable operation of software systems and reducing maintenance costs.
[0003] Existing code optimization methods generally employ static analysis tools. These tools scan the code to identify syntax errors, potential vulnerabilities, and code smells, then match and refactor the code using pre-defined simple refactoring patterns. However, these methods only identify basic issues based on pre-defined rules. They lack a deep understanding of complex dependencies between code segments and cannot flexibly address diverse code scenarios and complex code problems. This limits their applicability and effectiveness, making them unsuitable for dynamic adjustments based on specific contexts and dependencies. Consequently, they fail to meet current code optimization needs. Summary of the Invention
[0004] This invention provides a knowledge graph-based code optimization method and system to overcome the shortcomings of existing methods in that they cannot deeply understand code dependencies and have a narrow scope of application, resulting in limited optimization effects and failing to meet current code optimization needs.
[0005] In a first aspect, the present invention provides a code optimization method based on knowledge graphs, including: The source code of the codebase to be optimized is parsed to construct an abstract syntax tree, and the code segment to be optimized is determined based on the code complexity of the corresponding code in the abstract syntax tree. Based on the code snippets to be optimized and the pre-built code optimization knowledge graph, the refactoring pattern corresponding to each code snippet to be optimized is determined, and the context dependency graph of each code snippet to be optimized is constructed based on the abstract syntax tree corresponding to each code snippet to be optimized and the code optimization knowledge graph. Based on the context dependency graph, a sliding window decomposition is performed to obtain multiple interrelated code blocks, which are then simplified and merged to obtain the current context. The refactoring pattern corresponding to each code segment to be optimized and the current context are input into the large language model for structured refactoring to obtain the target refactoring scheme output by the large language model. Based on the target refactoring scheme, the abstract syntax tree is optimized to obtain the optimized code library.
[0006] Secondly, the present invention also provides a knowledge graph-based code optimization system, applied to the knowledge graph-based code optimization method as described in the first aspect; the knowledge graph-based code optimization system includes: The code recognition module is used to parse the source code of the code library to be optimized, construct an abstract syntax tree, and determine the code segment to be optimized based on the code complexity of the corresponding code in the abstract syntax tree. The dependency graph construction module is used to determine the refactoring pattern corresponding to each code segment to be optimized based on the code segment to be optimized and the pre-built code optimization knowledge graph, and to construct the context dependency graph of each code segment to be optimized based on the abstract syntax tree corresponding to each code segment to be optimized and the code optimization knowledge graph. The context generation module is used to perform sliding window decomposition based on the context dependency graph to obtain multiple interrelated code blocks, and to simplify and merge the code blocks to obtain the current context; The refactoring and optimization module is used to input the refactoring mode corresponding to each code segment to be optimized and the current context into the large language model for structured refactoring, to obtain the target refactoring scheme output by the large language model, and to optimize the abstract syntax tree based on the target refactoring scheme to obtain the optimized code library.
[0007] Thirdly, the present invention also provides an electronic device, comprising: a memory for storing computer software programs; and a processor for reading and executing the computer software programs, thereby implementing the knowledge graph-based code optimization method as described above.
[0008] Fourthly, the present invention also provides a non-transitory computer-readable storage medium storing a computer software program, which, when executed by a processor, implements the knowledge graph-based code optimization method described above.
[0009] Fifthly, the present invention also provides a computer program product, including a computer program that, when executed by a processor, implements the knowledge graph-based code optimization method as described above.
[0010] The knowledge graph-based code optimization method provided in this invention constructs an abstract syntax tree by parsing the source code of the codebase to be optimized and determining the code segment to be optimized based on code complexity. This allows for precise location of the code area requiring optimization, avoiding blind optimization of the entire codebase. Based on the code segment to be optimized and a pre-constructed code optimization knowledge graph, a refactoring pattern is determined, and a context dependency graph is constructed. This allows for a deep understanding of complex dependencies between codes, overcoming the shortcomings of existing methods that cannot deeply understand code dependencies. Furthermore, by performing a sliding window decomposition on the context dependency graph, multiple interconnected code blocks are obtained. These blocks are then simplified and merged to obtain the current context, ensuring that the size of the current context does not exceed the context processing budget of the large language model. By inputting the refactoring pattern and the current context into the large language model for structured refactoring, a target refactoring scheme is obtained. Based on this scheme, the abstract syntax tree is optimized. This method not only flexibly addresses diverse code scenarios and complex code problems, enabling dynamic adjustments based on the specific context and dependencies of the code, but also leverages the powerful capabilities of the large language model to generate high-quality refactoring schemes, expanding the scope of code optimization and improving the optimization effect, thus meeting current code optimization needs. Attached Figure Description
[0011] Figure 1 This is a flowchart illustrating the code optimization method based on knowledge graphs provided in an embodiment of the present invention; Figure 2 This is a schematic diagram of the structure of the knowledge graph-based code optimization system provided in an embodiment of the present invention; Figure 3 An embodiment diagram of the electronic device provided in this invention; Figure 4 An embodiment diagram of a computer-readable storage medium provided in accordance with the present invention. Detailed Implementation
[0012] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.
[0013] In the description of this invention, the terms "first" and "second" are used for descriptive purposes only and should not be construed as indicating or implying relative importance or implicitly specifying the number of indicated technical features. Thus, a feature defined as "first" or "second" may explicitly or implicitly include one or more of the stated features. In the description of this invention, "a plurality of" means two or more, unless otherwise explicitly specified.
[0014] In the description of this invention, the term "for example" is used to mean "used as an example, illustration, or description." Any embodiment described as "for example" in this invention is not necessarily to be construed as being more preferred or advantageous than other embodiments. The following description is provided to enable any person skilled in the art to make and use the invention. Details are set forth in the following description for purposes of explanation. It should be understood that those skilled in the art will recognize that the invention can be made without using these specific details. In other instances, well-known structures and processes will not be described in detail to avoid obscuring the description of the invention with unnecessary detail. Therefore, the invention is not intended to be limited to the embodiments shown, but is consistent with the broadest scope of the principles and features disclosed herein.
[0015] See Figure 1 , Figure 1 This is a flowchart illustrating the knowledge graph-based code optimization method provided by the present invention. In this embodiment, the execution entity of the knowledge graph-based code optimization method is a code optimization system. Therefore, the knowledge graph-based code optimization method includes: Step 10: Perform source code parsing based on the codebase to be optimized, construct an abstract syntax tree, and determine the code segment to be optimized based on the code complexity of the corresponding code in the abstract syntax tree.
[0016] Optionally, the code optimization system first obtains full access permissions to the codebase to be optimized. After confirming permissions, it traverses all source code files (such as Java, SQL, Python, etc.) in the codebase and uses static analysis tools such as ANTLR and PMD to perform syntax parsing on different types of source code, transforming the source code into a structured abstract syntax tree (AST). This allows the AST to clearly present the syntactic structure, statement logic, and hierarchical relationships between code elements. Then, based on the AST, it extracts code complexity metrics (including cyclomatic complexity, cognitive complexity, and code smells). Specifically, when calculating cyclomatic complexity, it analyzes the number of decision nodes (such as if, for, while, switch, etc.) in the AST and counts the number of independent paths in the code. When calculating cognitive complexity, it comprehensively evaluates factors such as the nesting depth of the code in the AST, the frequency of jump statements (such as break, continue, goto), and the complexity of exception handling logic. When identifying code smells, it judges whether there are problems such as excessively long methods, huge classes, or duplicate code based on the characteristics of code elements in the AST (such as the number of lines of code in methods, the number of attributes and methods in classes, and the number of times code snippets are repeated). Finally, based on the pre-set thresholds for various complexity metrics (such as setting the cyclomatic complexity threshold to 10, the cognitive complexity threshold to 15, and classifying methods with more than 100 lines of code as excessively long methods), code segments exceeding any of the thresholds are identified as code segments to be optimized.
[0017] In one embodiment, it is assumed that the codebase to be optimized is a Java codebase for an e-commerce order management system. It includes modules for order creation, payment processing, and logistics tracking. The code optimization system traverses this codebase and locates the `createOrder` method in the `OrderService.java` file. The source code of the `createOrder` method is parsed using the ANTLR parsing tool, generating an Abstract Syntax Tree (AST). The AST clearly shows the method's parameter definitions, variable declarations, multiple `if` statements (checking if the order's inventory is sufficient, if the user's account balance is sufficient, etc.), `for` loop (iterating through the order's product list and calculating the total amount), and exception handling (throwing an exception when inventory is insufficient).
[0018] Next, the code complexity (i.e., cyclomatic complexity, cognitive complexity, and code smells) of the `createOrder` method was calculated. For cyclomatic complexity, the method contained 5 `if` statements and 2 `for` loops. According to the cyclomatic complexity formula (cyclomatic complexity = number of decision nodes + 1), the cyclomatic complexity = 5 + 2 + 1 = 8 (decision nodes include `if`, `for`, `while`, `switch`, etc., each of which is counted as one decision node). For cognitive complexity, the AST was analyzed using the cognitive complexity calculation method. It was found that the method had 3 levels of nesting (an `if` statement containing a `for` loop, and a `for` loop containing an `if` statement checking if the product is a special offer), 2 `break` statements, and 1 exception throwing logic. The overall cognitive complexity was 12. For code smells, the AST analysis revealed that the method had 180 lines of code. Based on the set thresholds of cyclomatic complexity (10), cognitive complexity (15), and number of lines of code (100), the `createOrder` method has more than 100 lines of code, indicating a "too long method" code smell. Therefore, the `createOrder` method is marked as a code snippet to be optimized.
[0019] Step 20: Based on the code snippet to be optimized and the pre-built code optimization knowledge graph, determine the refactoring pattern corresponding to each code snippet to be optimized, and construct the context dependency graph of each code snippet to be optimized based on the abstract syntax tree and code optimization knowledge graph corresponding to each code snippet to be optimized.
[0020] Optionally, the code optimization system uses a pre-built code optimization knowledge graph, which includes CodeElement nodes (classes, methods, interfaces, variables, etc.), Pattern nodes (refactoring patterns, such as extracting methods, extracting classes, moving methods, etc.), Requirement nodes (business requirements, functionalities), and relationships between nodes (such as hasFix relationships: mapping relationships between Issue and Pattern, dependsOn relationships: dependency relationships between CodeElement, etc.). Therefore, the features of the identified code segments to be optimized (such as code smell types, complexity metrics, etc.) are matched with Issue nodes in the knowledge graph. By querying the hasFix relationships between Issue nodes and Pattern nodes in the knowledge graph, the refactoring pattern corresponding to each code segment to be optimized is determined. The detailed construction process of the code optimization knowledge graph is described in steps 2011-2015.
[0021] Furthermore, the code optimization system constructs a context dependency graph based on the abstract syntax tree (AST) and code optimization knowledge graph corresponding to each code segment to be optimized. By recursively searching for all dependency nodes related to the code segment to be optimized, these nodes and the dependencies between nodes are presented in a graphical way, which can clearly show the complex dependencies between the code segment to be optimized and other code elements, as described in steps 2021-2026.
[0022] Continuing with the above embodiments, for the tagged createOrder method (which has a "too long method" code smell), the code optimization system queries the pre-built code optimization knowledge graph. In this knowledge graph, the "too long method" issue node is mapped to the "extractMethod" pattern node through the hasFix relationship. Therefore, the refactoring pattern corresponding to the createOrder method is determined to be "extractMethod".
[0023] Step 30: Perform sliding window decomposition based on the context dependency graph to obtain multiple interrelated code blocks, and simplify and merge the code blocks to obtain the current context.
[0024] Optionally, the code optimization system first sets the size of the sliding window (the specific size can be determined based on the complexity of the code and the density of dependencies, such as the window containing 10-15 nodes). Starting from the core node of the context dependency graph (i.e., the node corresponding to the code segment to be optimized), the system moves the sliding window sequentially according to the tightness of the dependencies between nodes (based on the weight of the dependOn relationship in the code optimization knowledge graph; the higher the weight, the tighter the dependency). This decomposes the context dependency graph into multiple interconnected code blocks. Each code block contains a certain number of nodes and the dependencies between them, and there are some overlapping nodes between adjacent code blocks to ensure the relevance between them. Then, each code block is simplified by removing nodes with low relevance to the code segment to be optimized (this can be determined by judging the dependency weight between the node and the core node; nodes with a weight below a set threshold are considered to have low relevance) and redundant dependencies (such as duplicate dependency edges). Finally, the streamlined code blocks are merged, overlapping nodes and dependencies in adjacent code blocks are combined, duplicate information is eliminated, and the current context is obtained that is concise, complete in information, and can accurately reflect the core context of the code segment to be optimized.
[0025] In one embodiment, based on the context dependency graph of the constructed `createOrder` method, the code optimization system sets the sliding window size to 12 nodes. Starting from the `createOrder` method node, this method node has a high dependency weight (all 0.9) with the `checkStock`, `calculateTotalAmount`, and `checkUserBalance` method nodes, a dependency weight of 0.8 with the `Order` class node, a dependency weight of 0.7 with the `Product` class node, a dependency weight of 0.7 with the `User` class node, and a dependency weight of 0.3 with other nodes with lower correlation (such as log recording class nodes). The first sliding window contains 12 nodes, including createOrder, checkStock, calculateTotalAmount, checkUserBalance, Order, Product, and User, along with their dependencies. After moving the window, the second sliding window contains 12 nodes, including checkStock, calculateTotalAmount, checkUserBalance, Order, Product, User, and associated nodes such as inventory database operation nodes and amount calculation utility nodes, along with their dependencies. There is overlap between the two windows, including nodes such as checkStock, calculateTotalAmount, checkUserBalance, Order, Product, and User. A dependency weight threshold of 0.5 is set, and nodes with dependency weights below 0.5 (such as log recording nodes) are removed from the code block. Duplicate dependency edges (such as duplicate dependency edges where the createOrder method calls the checkStock method) are also deleted. Finally, the two simplified code blocks are merged, overlapping nodes and dependencies are combined, and the current context is obtained, which includes nodes such as createOrder, checkStock, calculateTotalAmount, checkUserBalance, Order, Product, User, inventory database operations, and amount calculation utility class, as well as core dependencies.
[0026] Step 40: Input the refactoring pattern corresponding to each code segment to be optimized and the current context into the large language model for structured refactoring, obtain the target refactoring scheme output by the large language model, and optimize the abstract syntax tree based on the target refactoring scheme to obtain the optimized code library.
[0027] Optionally, the code optimization system takes the refactoring pattern (e.g., extraction method) and current context corresponding to each code segment to be optimized as input. Based on the feature constraint layer, semantic rule mapping layer, step generation layer, and integration verification layer of the large language model, combined with its learned code refactoring knowledge and logical reasoning ability, it performs structured refactoring analysis and finally generates a target refactoring scheme, as described in steps 401-404. This target refactoring scheme details the specific steps of refactoring, the code modification locations and content involved in each step, and the structural framework of the refactored code. Finally, based on the target refactoring scheme, the abstract syntax tree constructed in step 10 is modified (e.g., adding sub-method nodes in the AST, adjusting the calling relationship between the original method nodes and sub-method nodes, etc.) to complete the code optimization and generate the optimized code library.
[0028] This invention constructs an abstract syntax tree (AST) by parsing the source code of the codebase to be optimized and determining the code segments to be optimized based on code complexity. This allows for precise location of code areas requiring optimization, avoiding blind optimization of the entire codebase. Based on the code segments to be optimized and a pre-built code optimization knowledge graph, a refactoring pattern is determined, and a context dependency graph is constructed. This allows for a deep understanding of complex dependencies between codes, overcoming the limitations of existing methods. A sliding window decomposition of the context dependency graph yields multiple interconnected code blocks, which are then simplified and merged to obtain the current context. This ensures the current context's size does not exceed the context processing budget of the large language model. By inputting the refactoring pattern and the current context into the large language model for structured refactoring, a target refactoring scheme is obtained. Based on this scheme, the abstract syntax tree is optimized. This approach not only flexibly addresses diverse code scenarios and complex code problems, enabling dynamic adjustments based on the specific context and dependencies of the code, but also leverages the powerful capabilities of the large language model to generate high-quality refactoring schemes, expanding the scope of code optimization and improving its effectiveness, thus meeting current code optimization needs.
[0029] Furthermore, the knowledge graph-based code optimization system provided by the present invention will be described below. The knowledge graph-based code optimization system described below and the knowledge graph-based code optimization method described above can be referred to in correspondence.
[0030] In one embodiment, steps 2011-2015 are described as follows: Step 2011: Based on the project root directory and module boundary build files of the codebase to be optimized, and in conjunction with package management files or build files, determine the project scope; the project scope includes the project's dependency list and external library handling strategy; the external library handling strategy includes determining whether external libraries have symbolic metadata.
[0031] Optionally, the code optimization system starts from the root directory of the project in the code repository to be optimized, identifies the module boundary build files under the root directory (such as module-info.java in a Java project, pom.xml module hierarchy structure in a Maven multi-module project, module definitions in setup.py or pyproject.toml in a Python project, etc.), and clarifies the module division within the project. Simultaneously, it reads the project's package management files or build files (such as pom.xml in Java, requirements.txt in Python, package.json in Node.js, etc.) and extracts the project's dependency information, including the names, version numbers, and sources (such as Maven Central Repository, PyPI repository, etc.) of direct and indirect dependencies, forming a dependency list for the project.
[0032] Furthermore, for external libraries (i.e., third-party libraries in the dependency manifest), the code optimization system determines the processing strategy by checking whether the external library files contain symbolic metadata (such as bytecode metadata attached to Java's .class files, Python's .pyi type hint files, symbol declarations in C++ header files .h, etc.). Specifically, if symbolic metadata exists, it is included in the knowledge graph construction scope for resolving cross-library dependencies; if symbolic metadata does not exist (such as libraries that only provide binary files and no debugging information), it is marked as a "black-box external library," and only its call relationship with the project's internal code is recorded, without resolving the internal structure, ultimately determining the project scope.
[0033] In one embodiment, an e-commerce order management system (Java language, Maven multi-module project) to be optimized is used as an example. The code optimization system locates the pom.xml (parent module build file) in the project root directory, which is configured through... <modules>The tag defines three internal modules: order-core (order core module), payment-service (payment service module), and logistics-client (logistics client module), thus clarifying the module boundaries.
[0034] Read the pom.xml files of each module and extract the dependency list: direct dependencies include spring-boot-starter-web (version 2.7.0, web framework), mybatis-plus (version 3.5.3, ORM framework), and lombok (version 1.18.24, code generation tool); indirect dependencies include spring-core (version 2.7.0, introduced by spring-boot-starter-web) and mysql-connector-java (version 8.0.30, introduced by mybatis-plus).
[0035] For external libraries: the JAR packages of spring-boot-starter-web and mybatis-plus contain complete bytecode metadata (.class files), which are included in the knowledge graph construction scope; assuming that an internally developed encryption utility library crypto-util is introduced into the project, only crypto-util.jar is provided (no source code and debugging information), and it is found that it has no symbolic metadata, so it is marked as a "black box external library", and only the call relationship of its encrypt method in the project code is recorded.
[0036] Step 2012: Based on the project scope, determine the programming language type of the source code file by file extension, shebang, or configuration, obtain the language identifier corresponding to each source code file, and parse the source code file of each language based on the language identifier to obtain the parsing result corresponding to each source code file; the parsing result includes abstract syntax tree, symbol table, reference relationship, optional generated type information, and control flow summary.
[0037] Optionally, the code optimization system, based on the defined project scope, traverses all files within that scope. It determines the programming language type of the source code files by file extensions (e.g., .java, .py, .js), shebang declarations (e.g., the first line of a script file, #! / usr / bin / envpython3), or configuration file types (e.g., .xml, .json), and assigns a unique language identifier (e.g., "java", "python", "javascript") to each file. Then, for files with different language identifiers, it calls the corresponding parsing tools. For example, Java files are parsed using ANTLR combined with Java syntax rules, Python files are parsed using the ast module, and JavaScript files are parsed using Esprima. During the parsing process, it generates an Abstract Syntax Tree (AST) to represent the channel structure; constructs a symbol table to record the declaration location and type information of symbols such as variables, functions, and classes; extracts reference relationships (e.g., source-target associations for method calls and class inheritance); generates type information for statically typed languages (e.g., data types of variables, parameter and return types of methods); and generates a control flow summary (e.g., an overview of the execution path for branch conditions and loop structures). Finally, the above results are integrated into the parsing results for each type of source code file.
[0038] Continuing with the above embodiment, in the e-commerce order management system, the code optimization system traverses the src / main / java directory of the order-core module and finds OrderService.java (suffix .java, language identifier "java"), OrderValidator.js (suffix .js, language identifier "javascript"), and data_process.py (first line #! / usr / bin / envpython3, language identifier "python"). For OrderService.java, ANTLR is used to parse and generate an AST, which includes class definitions, createOrder method nodes, if condition nodes, etc.; the symbol table records the OrderService class (declared on line 3), the createOrder method (parameter List), etc. <product>The code snippet describes several functions and their associated data structures. It includes a return value (Order), a local variable `totalAmount` (of type `BigDecimal`), and references to `createOrder` (calling `Product.getStock()`) and `OrderService` (depending on the `User` class). Type information is generated to specify the data type of each symbol. The control flow summary records the execution path: "Check inventory → Calculate amount → Create order". For `OrderValidator.js`, Esprima is used to parse and generate the AST. The symbol table records the `validateOrder` function, and references include calls to `JSON.parse`. The control flow summary records the branch logic for parameter validation. For `data_process.py`, the ast module is used for parsing. The symbol table records the `process_order_data` function, and references include calls to `pandas.DataFrame`. The control flow summary records the loop logic for data filtering.
[0039] Step 2013: Based on the parsing results of multiple languages, the abstract syntax trees of different languages are normalized to a unified intermediate representation to obtain a unified intermediate representation result. Based on the unified intermediate representation result, the parsing success rate, parsing alarm information and degradation path are recorded to obtain a parsing quality control report.
[0040] Optionally, the code optimization system converts the ASTs of different languages into a unified intermediate representation (such as a general syntax structure based on Protocol Buffers, containing common node types such as "declaration," "expression," "statement," and "type") for the obtained multi-language parsing results. For example, Java's `publicclassOrder` and Python's `classOrder` are both represented as "ClassDeclaration" nodes in the unified intermediate representation, with differences only in attributes (such as access modifiers). After the conversion, the system calculates the parsing success rate (number of successfully parsed files / total number of files × 100%), records parsing alerts (such as syntax error locations and unrecognized syntax structures), and marks downgrade paths (such as extracting only the filename and reference relationships for files that cannot be fully parsed as downgraded files). This information is then integrated into a parsing quality control report to assess parsing completeness and provide a reference for subsequent steps.
[0041] Continuing with the above embodiments, in the e-commerce order management system, the code optimization system converts the Java OrderService class AST, the JavaScript validateOrder function AST, and the Python process_order_data function AST into a unified intermediate representation: Java's publicList <product>The `getProducts()` method declaration is converted to a "MethodDeclaration" node, containing "accessModifier: PUBLIC" and "returnType: List". <product>Attributes such as "name: getProducts".
[0042] The JavaScript function validateOrder(order) {...} is converted into a "FunctionDeclaration" node, which contains attributes such as "name: validateOrder" and "parameters: [order]" (without access modifiers).
[0043] Finally, a total of 120 files were analyzed, with 115 successfully parsed, resulting in a parsing success rate of 95.8%. Five parsing alerts were recorded (e.g., two Java files contained unclosed parentheses, and three JavaScript files used ES2023 syntax that caused some nodes to fail to parse). For files that failed to parse, the process was downgraded to only recording the filename and the call relationship. The final parsing quality control report clearly stated the above results for reference in subsequent knowledge graph construction.
[0044] Step 2014: Based on the abstract syntax tree and symbol table, extract symbols (functions / methods / classes / interfaces / fields / enumerations), types, files, modules, packages, and third-party libraries as nodes of the knowledge graph to obtain node groups of the knowledge graph. Based on the node groups, construct edges of call, overwrite, inheritance, implementation, import, read or write, dependency, event subscription, dependency injection binding, and reflection types to obtain edge groups of the knowledge graph.
[0045] Optionally, the code optimization system extracts symbols (functions / methods such as createOrder, classes such as Order, interfaces such as PaymentService, fields such as Order.totalAmount, and enumerations such as OrderStatus) and types (such as List) based on the AST and symbol table from step 2012. <product>The knowledge graph consists of nodes such as BigDecimal, files (e.g., OrderService.java), modules (e.g., order-core), packages (e.g., com.ecommerce.order), and third-party libraries (e.g., mybatis-plus). Each node contains a unique identifier (e.g., the fully qualified name of a class node) and attributes (e.g., the parameter list of a method node). Next, based on the node group and the reference relationship in step 2012, construct the following edge groups: call edge (e.g., createOrder → checkStock), overwrite edge (e.g., OrderServiceImpl.createOrder → OrderService.createOrder), inheritance edge (e.g., Order → BaseEntity), implementation edge (e.g., OrderServiceImpl → OrderService), import edge (e.g., OrderService.java → Product.java), read-write edge (e.g., createOrder → Order.totalAmount, read operation is R, write operation is W), dependency edge (e.g., order-core → payment-service), event subscription edge (e.g., OrderListener → OrderCreatedEvent), dependency injection binding edge (e.g., @AutowiredOrderService → OrderServiceImpl), and reflection type edge (e.g., Class.forName("Order") → Order).
[0046] Continuing with the above embodiment, in the e-commerce order management system, the node groups extracted by the code optimization system include: Symbol nodes: OrderService.createOrder (method), Order (class), PaymentService (interface), Order.totalAmount (field), OrderStatus (enumeration: PENDING, PAID). Type nodes: List <product>BigDecimal. File node: com / ecommerce / order / OrderService.java. Module node: order-core. Package node: com.ecommerce.order. Third-party library node: mybatis-plus. The constructed edge group includes: Call edge: OrderService.createOrder → Product.getStock (method call). Inheritance edge: Order → BaseEntity (Order class inherits from BaseEntity class). Implementation edge: OrderServiceImpl → OrderService (class implements interface). Read / write edge: OrderService.createOrder → Order.totalAmount (W, assignment operation). Dependency edge: order-core → payment-service (module dependency). Dependency injection binding edge: OrderController.@AutowiredorderService → OrderServiceImpl (Spring injection binding).
[0047] Step 2015: Based on the obtained node groups and edge groups of the knowledge graph, a stable identifier is generated for each node in combination with the preset node generation rules, version information and submission fingerprint are attached, and a code optimization knowledge graph is constructed.
[0048] Optionally, based on the node and edge groups obtained in step 2014, the code optimization system generates a stable identifier for each node: using a "type prefix + unique identifier" format (e.g., "class: com.ecommerce.order.Order" for class nodes, and "method: com.ecommerce.order.OrderService.createOrder" for method nodes), ensuring that the node identifier remains stable during code iteration (e.g., a new identifier is generated after a method is renamed, while the original identifier retains its historical version association). Version information (corresponding to the Git commit version number of the codebase) and a commit fingerprint (a unique identifier generated based on the commit hash value) are appended to each node and edge to record its evolution trajectory in the code history. Finally, the node groups, edge groups, and their attributes (stable identifier, version information, commit fingerprint) are stored in a graph database (e.g., Neo4j) to construct a complete code optimization knowledge graph.
[0049] Continuing with the above embodiments, in the e-commerce order management system, the code optimization system generates stable identifiers for nodes: The Order class node is identified as "class: com.ecommerce.order.Order".
[0050] The method node OrderService.createOrder is identified as "method: com.ecommerce.order.OrderService.createOrder".
[0051] These nodes are then appended with version information (e.g., "v1.2.0", corresponding to the Git tag of the code repository) and commit fingerprints (e.g., "f47ac10b38d97571d5945e0917d786d5702cc8", generated based on commit hashes). The edge call OrderService.createOrder→Product.getStock within the edge group is also appended with version information and commit fingerprints, indicating that this call relationship exists in version v1.2.0. Finally, all nodes, edges, and their attributes are stored in the Neo4j graph database to form a code optimization knowledge graph. This graph can visually display relationships such as "OrderService.createOrder method calls Product.getStock method" and "Order class inherits from BaseEntity class," and supports querying historical dependencies by version.
[0052] This invention ensures complete knowledge coverage by defining the project scope and external library strategy; supports multi-language parsing, preserving details of various code elements; normalizes multi-language ASTs to eliminate language differences; extracts comprehensive node and edge types, covering relationships such as calls, inheritance, and dependencies between codes; and assigns stable identifiers and version information to nodes, forming a historically traceable knowledge network. The final constructed knowledge graph can present the relationships between code elements across languages and the entire chain, breaking through the language and scope limitations of traditional tools.
[0053] In one embodiment, steps 2021-2026 are described as follows: Step 2021: Map each code snippet to be optimized to the smallest contained abstract syntax tree node to obtain the smallest abstract syntax tree node.
[0054] Optionally, for each identified code segment to be optimized (such as the `createOrder` method, which contains "overly long methods"), the code optimization system locates the corresponding syntax node in the constructed Abstract Syntax Tree (AST). By matching the start and end line numbers of the code segment with the position information of the AST node, the system finds the smallest AST node that completely contains the code segment and cannot be further divided; this is the smallest abstract syntax tree node. This node represents the precise mapping of the code segment to be optimized in the AST, reflecting its most basic syntactic structure (such as method nodes, code block nodes, etc.).
[0055] In one embodiment, the `createOrder` method in `OrderService.java` to be optimized is taken as an example. The source code of this method is located in lines 15-200. The code optimization system searches the AST of `OrderService.java` and finds that the syntax node corresponding to lines 15-200 is a `MethodDeclaration` node. This node contains child nodes such as the method name, parameter list, return type, and method body, and cannot be further divided into smaller nodes (if it were divided into code block nodes inside the method body, it would not be able to completely contain the entire `createOrder` method). Therefore, the `MethodDeclaration` node is determined as the smallest abstract syntax tree node corresponding to the `createOrder` method.
[0056] Step 2022: Based on the minimum abstract syntax tree node, trace upwards and lock onto the nearest semantic boundary to obtain the initial seed node group.
[0057] Optionally, the code optimization system starts with the minimum abstract syntax tree (AST) node obtained in step 2021 and traces upwards along the AST hierarchy (i.e., traversing towards the parent node) to identify and lock the nearest semantic boundary. Here, a semantic boundary refers to a code unit with independent semantic functionality (such as a class definition, interface definition, module definition, etc.). All code units logically constitute a complete functional entity, and their internal code shares a unified semantic context. Therefore, the AST node corresponding to the semantic boundary and its contained minimum AST node are combined to form an initial seed node group, which is the starting set for subsequent dependency traversals.
[0058] Continuing with the above example, for the smallest AST node (MethodDeclaration node) of the createOrder method, the code optimization system traces upwards through the AST hierarchy: the parent node of MethodDeclaration is the ClassBody node (class body node), and the parent node of ClassBody is the ClassDeclaration node (class declaration node, corresponding to the OrderService class). The ClassDeclaration node represents a complete class definition and is the nearest semantic boundary (the class, as an independent functional unit, contains all the semantic context of the method). Therefore, the seed node group contains the ClassDeclaration node (OrderService class) and the MethodDeclaration node (createOrder method).
[0059] Step 2023: Based on each seed node in the seed node group, traverse the code optimization knowledge graph to find the dependent and reverse dependencies of each seed node, and obtain the first dependency traversal result.
[0060] Optionally, the code optimization system maps each node in the seed node group obtained in step 2022 to a corresponding node in the constructed code optimization knowledge graph (such as the OrderService class node and the createOrder method node). For each seed node, a bidirectional traversal is performed in the knowledge graph: forward traversal finds dependent items (i.e., other nodes that the node directly or indirectly depends on, such as the checkStock method node called by the createOrder method, or the referenced Product class node); backward traversal finds reverse dependencies (i.e., other nodes that directly or indirectly depend on the node, such as the submitOrder method node of the OrderController class that calls the createOrder method). During the traversal process, the system follows the pointing relationships of edges in the knowledge graph (such as call edges, inheritance edges, dependency edges, etc.), records all traversed nodes and the edges between nodes, forming the first dependency traversal result.
[0061] Continuing with the above embodiments, the corresponding nodes of the seed node group in the knowledge graph are "class: com.ecommerce.order.OrderService" (OrderService class node) and "method: com.ecommerce.order.OrderService.createOrder" (createOrder method node).
[0062] During forward traversal: the createOrder method node depends on the call side "method: com.ecommerce.product.Product.getStock" (getStock method node) and the read / write side "field: com.ecommerce.order.Order.totalAmount" (totalAmount field node); the OrderService class node depends on the inheritance side "class: com.ecommerce.common.BaseService" (BaseService parent class node).
[0063] When performing reverse traversal: the createOrder method node is accessed via an edge dependency called by "method: com.ecommerce.controller.OrderController.submitOrder" (the submitOrder method node); the OrderService class node is accessed via an edge dependency called by "class: com.ecommerce.order.OrderServiceImpl" (the OrderServiceImpl implementation class node).
[0064] The code optimization system records all the nodes and edges mentioned above, forming the first dependency traversal result.
[0065] Step 2024: Based on the initial dependency traversal results, perform cycle detection and deduplication, duplicate node merging, and node pruning in sequence to obtain the second dependency traversal results after cycle removal and pruning.
[0066] Optionally, the code optimization system first performs cycle detection and deduplication on the obtained first dependency traversal result. That is, it identifies cyclic dependencies between nodes (such as A depending on B, B depending on C, and C depending on A) through depth-first search (DFS), marks redundant edges in the cycle (such as keeping A→B and B→C, and removing C→A), and avoids infinite loops in the dependency graph. Then, it merges duplicate nodes, that is, it checks whether there are multiple nodes of the same entity in the traversal result (such as the same method being recorded multiple times due to different call paths), merges them into a single node, and retains all related edges. Finally, it performs node pruning, that is, it sets a threshold (such as a threshold of 3) based on the dependency distance between the node and the seed node group (such as 1 for direct dependency and 2 for indirect dependency), removes nodes whose distance exceeds the threshold (these nodes are weakly related to the segment to be optimized), and obtains the second dependency traversal result.
[0067] Continuing with the above example, the first dependency traversal result contains a circular dependency: createOrder→checkStock→InventoryDAO→createOrder (checkStock depends on InventoryDAO, and InventoryDAO's initialization depends on the OrderService class where createOrder resides). The code optimization system detects this cycle through DFS, retains createOrder→checkStock and checkStock→InventoryDAO, and removes redundant edges from InventoryDAO→createOrder. The Product class node appears repeatedly because it is referenced by both createOrder and checkStock; it is merged into a single node, retaining the edges related to both methods. A dependency distance threshold of 3 is pre-set, and the database connection pool node that InventoryDAO depends on is 4 meters away from the seed node; the system prunes it accordingly. Finally, the second dependency traversal result after de-cyclicization and pruning is obtained.
[0068] Step 2025: Based on the dependency ambiguity present in the second dependency traversal result, perform polymorphism, generics, and overloading processing in sequence to obtain the third dependency traversal result.
[0069] Optionally, the code optimization system, based on the obtained second dependency traversal results, addresses dependency ambiguity issues arising from polymorphism, generics, and overloading. Specifically, for polymorphism, for call nodes of interfaces or parent classes (such as PaymentService.pay()), it searches all concrete implementation classes (such as AlipayService, WechatPayService) through implementation edges or inheritance edges in the knowledge graph to clarify the actual call node. For generics, for generic type nodes (such as List...), ... <t>), depending on the specific type of the reference in the context (such as List) <product>The `(int a)` parameter is replaced with an instantiated type node to eliminate ambiguity in the type parameter. For overload handling: for overloaded method nodes (such as `calculate(int a)` and `calculate(String b)`), a uniquely determined method node is matched based on the parameter type at the time of the call. After processing in sequence, the third dependency traversal result is obtained to ensure that the dependency relationship is accurate and unambiguous.
[0070] Continuing with the above example, in the second dependency traversal result, the `createOrder` method calls `PaymentService.pay(Orderorder)`, and `PaymentService` is an interface with two implementation classes: `AlipayService` and `WechatPayService` (polymorphic ambiguity). The code optimization system uses the implementation class edges from the knowledge graph, combined with the payment type parameter in `createOrder` (`order.getPayType() = ALIPAY`), to determine that the actual call is to `AlipayService.pay(Orderorder)`. The result contains a List. <t>Generic nodes, based on the List in createOrder <product>Replace the reference to products with a List. <product>Type nodes. When `createOrder` calls the `calculate` method with a parameter of type `BigDecimal`, it matches the `calculate(BigDecimalamount)` overloaded method, eliminating overload ambiguity. After processing in sequence, the third dependency traversal result is obtained.
[0071] Step 2026: Based on the third dependency traversal results, construct the context dependency graph for each code snippet to be optimized.
[0072] Optionally, the code optimization system constructs a context dependency graph for each code segment to be optimized based on the obtained third dependency traversal results, as detailed in steps 20261-20265.
[0073] The context dependency graph finally constructed in the embodiments of the present invention can accurately and completely reflect the relationship between the code segment to be optimized and other code elements, including fine-grained relationships such as calls, inheritance, reads and writes, providing a reliable context basis for subsequent refactoring. It solves the problem that traditional methods are difficult to handle complex dependency relationships in code, and often lead to inaccurate optimization due to the omission of key dependencies or the inclusion of irrelevant dependencies.
[0074] In one embodiment, steps 20261-20265 are described as follows: Step 20261: Based on the third dependency traversal result, determine whether there is symbolic meta-information in the external library. If it exists, the external library is included in the code optimization knowledge graph. If it does not exist, the entire external library is included in the knowledge graph as a single node, thus obtaining the fourth dependency traversal result after the external library and cross-module dependencies. The external library refers to third-party software libraries, toolkits, and frameworks that are directly or indirectly referenced by the code to be optimized, outside of the code library to be optimized.
[0075] Optionally, the code optimization system identifies the external libraries (third-party software libraries, toolkits, and frameworks outside the codebase to be optimized) involved in the obtained third dependency traversal results. For each external library, based on the external library processing strategy determined in step 2011, it determines whether it has symbolic metadata (such as Java's bytecode metadata, Python's type hint files, etc.): if symbolic metadata exists, the internal nodes (such as classes and methods) of the external library and the dependencies between nodes are fully incorporated into the code optimization knowledge graph and associated with the corresponding reference nodes in the third dependency traversal results; if symbolic metadata does not exist, the entire external library is regarded as an indivisible single node, and only its call or dependency relationship with the internal nodes of the codebase to be optimized is recorded. After processing, a fourth dependency traversal result containing external libraries and cross-module dependencies is obtained.
[0076] Continuing with the above example, the third dependency traversal result involves the external libraries spring-boot-starter-web (which has symbolic metadata) and crypto-util (which has no symbolic metadata).
[0077] For spring-boot-starter-web, the code optimization system incorporates its internal nodes (such as @RequestMapping annotated classes, RestController interfaces, and HttpServletRequest classes) and dependencies (such as the inheritance relationship between RestController and Controller) into the knowledge graph, and associates the reference edges of the OrderController class to @RestController.
[0078] For crypto-util, the code optimization system includes it as a single node "external:lib:crypto-util" in the result, retaining only the edge of the createOrder method's call to the encrypt method on that node. Meanwhile, cross-module dependencies (such as the order-core module's dependency on the payment-service module's PaymentService interface) are already included in the third dependency traversal result and are directly retained. This ultimately forms the fourth dependency traversal result.
[0079] Step 20262: Based on the fourth dependency traversal result, parse the framework annotations or configuration bindings to generate implicit dependency edges, collect the reflection string constants and patterns to construct low-confidence reflection edges, and supplement the implicit dependency edges and low-confidence reflection edges into the fourth dependency traversal result to obtain the fifth dependency traversal result.
[0080] Optionally, the code optimization system, based on the obtained fourth dependency traversal results, parses implicit dependency edges using framework annotations or configuration bindings, and collects reflection string constants and patterns to construct low-confidence reflection edges to supplement special dependency edges. Specifically, for implicit dependency edges, it parses framework annotations (such as Spring's @Autowired and @Service, and MyBatis' @Mapper) and configuration bindings (such as the binding of datasource.url and DataSource in application.yml), identifies dependencies not explicitly invoked in the code (such as @AutowiredOrderServiceorderService implying OrderController's dependency on OrderServiceImpl), and generates implicit dependency edges. For low-confidence reflection edges, it collects string constants from reflection calls in the code (such as the class name in Class.forName("com.ecommerce.order.Order")) and patterns (such as the parameter types of Method.invoke), matches them with nodes in the knowledge graph, constructs reflection edges, and marks them as "low-confidence" (because reflection calls may be dynamically generated at runtime, and the dependency relationship is uncertain). Finally, these two types of edges are added to the fourth dependency traversal result to obtain the fifth dependency traversal result.
[0081] Continuing with the above example, in the fourth dependency traversal result, the OrderController class contains the @AutowiredOrderServiceorderService annotation. The code optimization system parses this annotation and, in conjunction with Spring's dependency injection rules, determines that OrderController actually depends on OrderServiceImpl (the implementation class of OrderService), generating an implicit dependency edge: OrderController → OrderServiceImpl (dependency injection).
[0082] Meanwhile, the `createOrder` method contains a reflection call to `Class.forName("com.ecommerce.order.Order")`. The system extracts the string constant "com.ecommerce.order.Order", matches it with the `Order` class node in the knowledge graph, constructs a low-confidence reflection edge: `createOrder → Order` (reflection), and marks it with a confidence of 0.6 (lower than the 1.0 of an explicit call). After supplementing these two special edges, the fifth dependency traversal result is obtained.
[0083] Step 20263: Perform a traversal termination check based on the fifth dependency traversal result to obtain the sixth dependency traversal result that meets the stopping condition.
[0084] Optionally, the code optimization system performs a termination check on the fifth dependency traversal result, setting stopping conditions, including dependency depth thresholds: if the maximum dependency depth between the currently traversed node and the seed node group (e.g., 1 for direct dependency, 2 for indirect dependency) reaches a preset threshold (e.g., 5), the traversal terminates; node number thresholds: if the total number of nodes in the result exceeds a preset threshold (e.g., 500), the traversal terminates (to avoid the dependency graph becoming too large and reducing analysis efficiency); core dependency coverage: if the core dependencies of the seed node (e.g., directly called methods, inherited parent classes) are all included, and the correlation between the newly added node and the segment to be optimized is lower than a set threshold (e.g., 0.2), the traversal terminates. When any stopping condition is met, the current result is retained as the sixth dependency traversal result; otherwise, the system returns to step 2023 to continue traversing. Continuing with the above embodiments, for the fifth dependency traversal result of the createOrder method, the system pre-sets the dependency depth threshold to 5, the number of nodes threshold to 500, and the core dependency coverage threshold to 0.2.
[0085] The current maximum dependency depth is 4 (createOrder→checkStock→InventoryDAO→DataSource→HikariCP), which has not reached the threshold of 5.
[0086] The total number of nodes is 120, which is less than 500.
[0087] All core dependencies (checkStock, calculateTotalAmount, Order class, etc.) have been included. The newly added node is an internal configuration class of HikariCP, with an affinity of 0.15 with createOrder (below 0.2), satisfying the core dependency coverage condition. Therefore, the system terminates the traversal and determines the current result as the sixth dependency traversal result.
[0088] Step 20264: Based on the sixth dependency traversal result, the nodes and edges are scored, sorted, and filtered using multiple dimensions to obtain the target dependency traversal result.
[0089] Optionally, the code optimization system scores edges and nodes from multiple dimensions (node dimension and edge dimension) based on the sixth dependency traversal result determined after the traversal terminates. Specifically, for the node dimension, this includes dependency distance from the seed node (the smaller the distance, the higher the score), importance in the business process (e.g., core business methods score higher than auxiliary tool methods), and reference frequency (nodes called multiple times score higher). For the edge dimension, this includes dependency type (explicitly called edges score higher than implicitly dependent edges, and implicitly dependent edges score higher than low-confidence reflected edges), and necessity in the control flow (e.g., dependent edges in branch conditions score higher than ordinary called edges). After scoring, the nodes and edges are sorted according to the scoring results, retaining the top N nodes and associated edges (e.g., the top 80%), and removing low-scoring edge nodes and weakly dependent edges to obtain the target dependency traversal result.
[0090] Continuing with the above example, in the sixth dependency traversal result, the dependency distance of the `createOrder` method (seed node) is 0, scoring 10 points; the directly called `checkStock` method (distance 1) scores 8 points; the `Product` class (referenced by `checkStock`, distance 2) scores 6 points; and the `HikariCP` configuration class (distance 4, low association) scores 2 points. In terms of edge scores, `createOrder→checkStock` (explicit call) scores 9 points; `OrderController→OrderServiceImpl` (implicit dependency injection) scores 7 points; and `createOrder→Order` (low-confidence reflection) scores 4 points. The code optimization system pre-sets to retain the top 80% of nodes and edges, removes the `HikariCP` configuration class (score 2, in the bottom 20%) and its associated edges, and retains the high-scoring nodes and edges to obtain the target dependency traversal result.
[0091] Step 20265: Based on the target dependency traversal results, generate a JSON file or graph database subgraph containing node identifiers, node types, node positions, node weights, node confidence, and edge information. Then, verify and encapsulate the JSON file or graph database subgraph to obtain the context dependency graph for each code snippet to be optimized.
[0092] Optionally, the code optimization system generates node information based on the determined target dependency traversal results. This information includes node identifiers (e.g., "method: com.ecommerce.order.OrderService.createOrder"), node types (e.g., "method", "class", "external library"), node positions (e.g., file path and line number), node weights (based on the score from step 20264), and node confidence (e.g., 0.6 confidence for nodes associated with a reflection edge). Simultaneously, edge information is generated, including the starting node identifier, target node identifier, edge type (e.g., "call", "inheritance", "reflection"), and edge confidence (1.0 for explicit edges, 0.8 for implicit edges, and 0.6 for reflection edges). Finally, the JSON file or graph database subgraph is validated and encapsulated to obtain the context dependency graph for each code snippet to be optimized, as described in steps 202651-202653.
[0093] The context dependency graph constructed in this embodiment of the invention fully covers explicit / implicit and internal / external dependencies, and accurately focuses on core associations, avoiding the problem of incomplete dependency graphs caused by traditional methods that often ignore external library dependencies and implicit dependencies (such as framework annotations and reflection).
[0094] In one embodiment, steps 202651-202653 are described as follows: Step 202651: Perform integrity and compliance checks on the JSON file or graph database subgraph to obtain a structured subgraph that passes the checks.
[0095] Optionally, the code optimization system performs integrity and compliance checks on the generated JSON file or graph database subgraph. Integrity checks include: verifying whether the node set contains seed node groups (e.g., the `createOrder` method node to be optimized and its class nodes), whether core dependency nodes (e.g., the directly called `checkStock` method node) are missing, and whether the edge set covers the main dependency types (e.g., call, inheritance, read / write edges), ensuring no critical dependencies are missing. Compliance checks include: verifying whether the node identifier format is consistent (e.g., "method: fully qualified name" "class: fully qualified name"), whether the node type and attributes match (e.g., the "external library" node does not contain a line number attribute), whether the starting and target nodes of the edges exist in the node set, and whether the confidence score is within the range [0, 1], ensuring the structured subgraph conforms to the preset data specifications. Finally, after successful verification, a structured subgraph is obtained; if there are failed verification items (e.g., missing core nodes, incorrect identifier format), the system returns to the previous steps for correction and re-verification.
[0096] Continuing with the above examples, the code optimization system performs verification on the JSON file of the createOrder method: Integrity verification: The node set was confirmed to contain "method: com.ecommerce.order.OrderService.createOrder" (seed node) and "method: com.ecommerce.product.Product.getStock" (core dependency node), and the edge set contained the main types such as call and inheritance. No critical missing parts were found.
[0097] Compliance verification: Check that all node identifiers follow the format "type:fully qualified name" (e.g., "class:com.ecommerce.order.Order"), that "external:lib:crypto-util" (external library node) does not contain line number attributes (compliant with specifications), that the starting / target nodes of all edges are in the node set, and that confidence scores (e.g., 1.0, 0.6) are all within the range [0, 1].
[0098] After the verification is passed, the structured subgraph is obtained.
[0099] Step 202652: Associate the structured subgraph with the code snippet to be optimized to obtain the target subgraph after association mapping.
[0100] Optionally, the code optimization system performs an association mapping between the obtained structured subgraph and the corresponding code snippet to be optimized. Specifically, using the unique identifier of the code snippet to be optimized (e.g., file path + start-end line number: OrderService.java: 15-200), the corresponding seed node (e.g., "method: com.ecommerce.order.OrderService.createOrder") is located in the structured subgraph, establishing a mapping relationship between "code snippet to be optimized - seed node". Simultaneously, attribute information of the code snippet to be optimized (e.g., code complexity metrics: cyclomatic complexity 8, cognitive complexity 12, code smell type "overly long method") is added to the metadata of the structured subgraph, directly associating the subgraph with the features of the snippet to be optimized, facilitating rapid location of the object to be optimized and its context in subsequent steps. Finally, the mapped target subgraph is obtained.
[0101] Continuing with the above embodiment, the code snippet to be optimized is the `createOrder` method in lines 15-200 of `OrderService.java`, uniquely identified as `OrderService.java:15-200`. The code optimization system locates the corresponding seed node "method: com.ecommerce.order.OrderService.createOrder" in the structured subgraph, establishes a mapping relationship, adds attribute information to the subgraph metadata, forming the target subgraph after association mapping, thus directly binding the subgraph to the characteristics of the `createOrder` method.
[0102] Step 202653: Based on the target subgraph, encapsulate it according to the pre-built dependency graph standard format to obtain the context dependency graph corresponding to each code fragment to be optimized.
[0103] Optionally, the code optimization system encapsulates the obtained target subgraph according to a pre-built dependency graph standard format. This standard format defines: fixed top-level fields (e.g., id: unique identifier of the dependency graph, target: identifier of the associated code snippet to be optimized, nodes: array of nodes, edges: array of edges, metadata: metadata), required / optional fields for nodes and edges (e.g., nodes must have id / type, location is optional; edges must have from / to / type, confidence is optional), and data type and format constraints for fields (e.g., id is a string, confidence is a floating-point number). Finally, the content of the target subgraph is reorganized according to the standard format, supplementing any missing optional fields (unless otherwise specified, the edge confidence defaults to 1.0), ensuring format consistency. After encapsulation, the context dependency graph corresponding to each code snippet to be optimized is obtained.
[0104] Continuing with the above embodiments, the pre-built dependency graph standard format requires the top layer to include id, target, nodes, edges, and metadata fields. The code optimization system encapsulates the target subgraph of the createOrder method: Generate a unique ID: dep_graph_123; Enter the code identifier to be optimized in the target field: OrderService.java:15-200; Organize the nodes and edges arrays according to the standard format, and supplement the default confidence of the edges (e.g., set to 0.8 if implicitly dependent edges are not specified). Preserve complexity and code smell information in metadata; The final encapsulated context dependency graph is obtained.
[0105] This invention eliminates issues such as missing key nodes and format errors in the dependency graph through integrity and compliance checks, ensuring the accuracy of dependencies and data standardization. By using association mapping, the dependency graph is uniquely bound to the code segment to be optimized, avoiding confusion between the subgraph and the target object. Finally, the structure of the dependency graph is unified by a standard format, ensuring that the dependency graphs of different segments to be optimized can be consistently parsed in subsequent steps.
[0106] In one embodiment, steps 401-404 are described as follows: Step 401: Input the refactoring pattern corresponding to each code segment to be optimized and the current context into the large language model for structured refactoring. In the feature constraint layer, a matrix is constructed for the syntactic structure features of each code segment to be optimized and the applicable boundary conditions of the corresponding refactoring pattern to obtain the refactoring constraint matrix. Based on the code block correlation degree contained in the current context and the matching result of the refactoring constraint matrix, the refactoring priority sequence is determined. The code block correlation degree refers to the frequency of call dependencies and the number of data transfers between code blocks in the current context.
[0107] Optionally, the code optimization system inputs the refactoring pattern corresponding to each code segment to be optimized, along with the current context, into the large language model for structured refactoring. Specifically, in the feature constraint layer of the large language model, for each code segment to be optimized, its syntactic structure features (such as the number of method parameters, nesting level, and statement type ratio) and the applicable boundary conditions of the corresponding refactoring pattern (such as "extracting methods" requiring the code block to have independent functionality and no cross-block variable modification) are extracted. A refactoring constraint matrix is constructed using syntactic structure features as row vectors and applicable boundary conditions as column vectors, where the matrix element values represent the degree to which the syntactic feature satisfies the corresponding boundary conditions (0 indicates not satisfied, 1 indicates fully satisfied). Simultaneously, the code optimization system calculates the code block correlation degree of each code block within the current context: it counts the frequency of call dependencies between code blocks (such as the number of times code block A calls code block B) and the number of data transfers (such as the number of times code block A passes parameters to code block B), and uses the sum of the two as the correlation metric. The matching results of the reconstruction constraint matrix (i.e., the proportion of elements in the matrix that meet the conditions) are weighted and adjusted according to the correlation degree, and sorted from high to low according to the adjusted values to obtain the reconstruction priority sequence.
[0108] In one embodiment, the `createOrder` method to be optimized (refactoring pattern "Extract Method") is taken as an example. The extracted syntactic structure features include: the parameter list contains a List. <product>The context contains User (row vector 1), has 3 levels of nesting (row vector 2), and contains 5 if statements (row vector 3). The applicable boundary conditions for the "extraction method" include: independent code block functionality (column vector 1), no local variables modified across blocks (column vector 2), and more than 10 lines of code (column vector 3). The current context contains 3 code blocks: inventory check block (A), amount calculation block (B), and balance check block (C). Code block relevance: A and B are called twice and data is transferred once (relevance 3); B and C are called once and data is transferred once (relevance 2); A and C have no direct relevance (relevance 0). Therefore, the matrix matching result (percentage of elements satisfying the conditions) is: A = 100%, B = 80%, and C = 90%. After adjusting for relevance, the priority sequence is A (100% × 3) > C (90% × 2) > B (80% × 2).
[0109] Step 402: In the semantic rule mapping layer, based on the semantic features of high-priority code blocks in the refactoring priority sequence and the mapping relationship between refactoring patterns and code features in the code optimization knowledge graph, refactoring association rules are determined, and based on the associated objects of each rule in the refactoring association rules and the dependency relationship of code blocks in the current context, a refactoring dependency directed graph is determined; high-priority code blocks refer to code blocks in the refactoring priority sequence that exceed the preset priority threshold.
[0110] Optionally, in the semantic rule mapping layer of the large language model, the code optimization system first presets a priority threshold (e.g., 60%). Therefore, it filters out high-priority code blocks (e.g., A and C) from the refactoring priority sequence. It then extracts the semantic features of these high-priority code blocks (e.g., A's "inventory verification logic" and C's "user balance verification logic") and queries the mapping relationship between refactoring patterns ("extraction methods") and code features in the code optimization knowledge graph (e.g., "inventory verification logic → extracted as checkStock method" and "balance verification logic → extracted as checkBalance method") to form refactoring association rules. Next, based on the associated objects in the refactoring association rules (e.g., A corresponds to the checkStock method and C corresponds to the checkBalance method) and the dependencies between code blocks in the current context (e.g., B can only be executed after A, and C can only be executed after B), a refactoring dependency directed graph is constructed with code blocks as nodes and dependencies as directed edges. The direction of the edges indicates the order of refactoring execution.
[0111] Continuing with the above embodiment, the preset priority threshold is 60%, and the high-priority code blocks are A (inventory check block) and C (balance check block). The semantic feature of A is "verify whether the product inventory is sufficient; if insufficient, throw an exception." Matching the "extraction method" mapping relationship in the knowledge graph, rule 1 is generated: A → Extract as checkOrderStock(List <product>The semantic feature of C is "verify whether the user's balance covers the order amount; if insufficient, return an error." Matching the mapping relationship, rule 2 is generated: C → extracted as the `checkUserBalance(User, BigDecimal)` method. The current context code block dependencies are: A → B (the amount can only be calculated after inventory check), B → C (the balance can only be checked after the amount is calculated). The final refactored dependent directed graph is constructed as follows: nodes are A, B, and C, and directed edges are A → B and B → C.
[0112] Step 403: In the step generation layer, based on the strong connectivity of the refactoring dependency directed graph and the priority distribution of code blocks in the refactoring priority sequence, a refactoring subgroup is determined. Based on the interaction logic of code elements within the refactoring subgroup and the rule content in the refactoring association rules that matches the refactoring subgroup, a refactoring step group within the refactoring subgroup is determined. Strong connectivity refers to the largest subgraph in the refactoring dependency directed graph that satisfies the condition that there is a bidirectional path between any two nodes.
[0113] Optionally, in the step generation layer of the large language model, the code optimization system performs strong connectivity analysis on the obtained refactoring dependency directed graph: First, it identifies strong connectivity (the largest subgraph that can be reached bidirectionally between any two nodes) in the graph using the Tarjan algorithm, and each strong connectivity is considered as a refactoring subgroup (if there are no cycles in the graph, each node is an independent subgroup). Then, for each refactoring subgroup, it analyzes the interaction logic of code elements within the subgroup (such as the data transfer method between A and B, and the dependency conditions of B on the result of A) by combining the priority distribution of code blocks in the refactoring priority sequence (e.g., A has a higher priority than C), matches the rule content corresponding to the subgroup in the refactoring association rules (e.g., A corresponds to rule 1), generates a refactoring step group within the refactoring subgroup, and clarifies the operation object (e.g., the code line range of A), operation type (e.g., creating a new method, moving code), and operation order of each step.
[0114] Continuing with the above embodiments, the reconstruction depends on the acyclic directed graph (A→B→C are all unidirectional edges), and the strong connectivity consists of three independent reconstruction subgroups: A, B, and C.
[0115] For subgroup A (highest priority): the code element interaction logic is "iterate through the Product list and call getStock() to determine if the inventory is greater than or equal to the purchase quantity", matching rule 1, generating step group 1: 1. Create a new checkOrderStock(List) function in the OrderService class. <product>)method; 2. Move lines 20-50 of code in A to the new method; 3. Add the checkOrderStock(products) call to the original location A.
[0116] For subgroup C (lower priority): the interaction logic is "get the User's balance and compare it with the total order amount", matching rule 2, generating step group 3 (the step number reflects the order, because B depends on A, step group 2 must be after step group 1).
[0117] For subgroup B (lowest priority): Although no high-priority rule was matched, step group 2 was generated based on the dependency relationship (executed after step group 1).
[0118] Step 404: In the integration and verification layer, the scheme is generated and verified based on the reconstruction constraint matrix, reconstruction association rules, reconstruction subgroups, reconstruction step groups, and reconstruction dependency directed graph to obtain the target reconstruction scheme.
[0119] Optionally, in the integration and verification layer of the large language model, the code optimization system generates and verifies a scheme based on the determined reconstruction constraint matrix, reconstruction association rules, reconstruction subgroups, reconstruction step groups, and reconstruction dependency directed graph, to obtain the target reconstruction scheme, as described in steps 4041-4044.
[0120] This invention, through a combination of a refactoring constraint matrix and code block associativity, ensures a precise match between the refactoring pattern and code features. It divides the code into subgroups and generates steps based on semantic rules and dependencies, ensuring the solution aligns with the actual logical flow of the code. Multi-dimensional verification further eliminates conflicts and violations. The final generated target refactoring solution accurately adapts to the syntax structure, semantic features, and contextual dependencies of the code to be optimized, avoiding logical breakdowns caused by a "one-size-fits-all" refactoring approach.
[0121] In one embodiment, steps 4041-4044 are described as follows: Step 4041: Based on the number of steps in each refactoring subgroup and the dependency relationships between refactoring subgroups in the directed graph of refactoring dependencies, determine the refactoring order between refactoring subgroups.
[0122] Optionally, the code optimization system uses the dependencies between refactoring subgroups in the refactoring dependency directed graph as its core basis, combined with the number of steps in each refactoring step group, to determine the execution order between refactoring subgroups. Specifically, first, based on the topological sorting of the refactoring dependency directed graph (ensuring that all predecessor subgroups are executed before subsequent dependent subgroups are executed), a preliminary order framework is determined; then, if there are parallel subgroups without dependencies (i.e., no direct or indirect dependencies between subgroups), the number of steps within each subgroup is compared, and the subgroup with more steps is executed first (reducing the overall refactoring time loss and avoiding the accumulation of subsequent steps). This ultimately forms a unique refactoring order between refactoring subgroups.
[0123] Continuing with the above embodiment, the reconstructed subgroups include subgroup A (inventory check block, step group 1 containing 3 steps), subgroup B (amount calculation block, step group 2 containing 2 steps), and subgroup C (balance check block, step group 3 containing 3 steps). In the reconstructed dependent directed graph, the subgroup dependency relationship is A→B→C (A is the predecessor of B, and B is the predecessor of C), with no parallel subgroups. Based on topological sorting, the initial order is A→B→C; since there are no parallel subgroups, there is no need to compare the number of steps. The final determined reconstructed subgroup order is: subgroup A (step group 1) → subgroup B (step group 2) → subgroup C (step group 3).
[0124] Step 4042: Determine the current reconstruction scheme based on the reconstruction order between reconstruction subgroups and the reconstruction step groups within each reconstruction subgroup.
[0125] Optionally, the code optimization system, based on the determined refactoring order among the refactoring subgroups, uses the refactoring subgroup order as the overall framework. It then embeds the refactoring steps within each subgroup into this framework according to their original logical order (e.g., the order of "create method → move code → add call" in step group 1 of subgroup A), forming a coherent sequence of steps. Simultaneously, the system supplements the solution with specific operational details for each step: including the operation object (e.g., the operation object of step 1 in subgroup A is the OrderService class), the scope of code modification (e.g., the modification scope of step 2 in subgroup A is lines 20-50 of the createOrder method), and the expected output (e.g., after step 3 in subgroup A is completed, line 20 of the original code is replaced with the checkOrderStock(products) call statement). The integrated solution yields the current refactoring solution.
[0126] Continuing with the above embodiments, based on the subgroup order A→B→C, embedding each step group yields: I. Subgroup A, Step 1: Step 1: Create a new checkOrderStock(List) function in the OrderService class. <product>The method returns a boolean value. Step 2: Move lines 20-50 (inventory check logic) from the createOrder method to the checkOrderStock method; Step 3: Add the statement `booleanstockSufficient=checkOrderStock(products);` to line 20 of the `createOrder` method.
[0127] II. Subgroup B, Step 2: Step 1: Create a new `calculateOrderTotal(List< ... <product>The method returns a BigDecimal. Step 2: Move lines 55-70 (the amount calculation logic) of the createOrder method to this method, and add BigDecimaltotal=calculateOrderTotal(products); in the original position to call it.
[0128] III. Subgroup C, Step 3: Step 1: Create a new method checkUserBalance(User, BigDecimal) in the OrderService class, with a return value of boolean; Step 2: Move lines 75-95 (balance check logic) of the createOrder method to this method; Step 3: Add the statement `boolean balanceSufficient = checkUserBalance(user, total);` to line 75 of the `createOrder` method.
[0129] Integrating the above steps, the current restructuring plan is formed.
[0130] Step 4043: Based on the reconstruction constraint matrix and reconstruction association rules, perform constraint matching and compliance verification on the current reconstruction scheme to obtain preliminary verification results of matching and compliance.
[0131] Optionally, the code optimization system performs dual verification of the current refactoring scheme based on the refactoring constraint matrix and refactoring association rules. Specifically, during constraint matching verification, it checks whether each step in the scheme meets the boundary conditions of the refactoring constraint matrix (e.g., whether the code block moved in step 2 of subgroup A has no local variables modified across blocks, corresponding to the condition in the "no cross-block variable modification" column of the matrix). If a step does not meet these conditions, it is marked as a constraint conflict. During compliance verification, it checks whether the steps in the scheme comply with the refactoring association rules (e.g., whether the name of the newly created method in step 1 of subgroup A is consistent with "checkOrderStock" in rule 1, and whether the parameter list in step C of subgroup C matches "User, BigDecimal" in rule 2). If there are inconsistencies, it is marked as a compliance violation. When all steps pass both constraint matching and compliance verification, a preliminary verification result indicating that matching and compliance have passed is obtained.
[0132] Continuing with the above embodiment, during constraint matching verification: check the code block moved in step 2 of subgroup A to confirm that there are no local variables modified across blocks (meets the condition of "no cross-block variable modification" in the matrix); the amount calculation logic moved in step 2 of subgroup B has 15 lines of code (meets the condition of "number of lines of code > 10" in the "extraction method") and has no constraint conflicts.
[0133] During compliance verification: In step 1 of subgroup A, create a new method named checkOrderStock that matches rule 1, with a parameter list of List. <product>Matching; Subgroup C, step 1, creates a new method `checkUserBalance` that matches rule 2, with parameters `User` and `BigDecimal` meeting the requirements, showing no compliance or violation. The final preliminary verification result is obtained.
[0134] Step 4044: Based on the directed graph of the refactored dependencies, perform dependency conflict verification on the preliminary verification results to obtain the target refactoring scheme that passes dependency compatibility.
[0135] Optionally, the code optimization system performs dependency conflict verification on the preliminary verification results based on the constructed refactoring dependency directed graph. Specifically, it checks whether the execution order of the steps in the solution is consistent with the dependency relationship in the refactoring dependency directed graph (e.g., whether there is a reverse order such as "execute subgroup B step first, then execute subgroup A step"); it checks whether there are resource dependency conflicts between steps (e.g., two steps simultaneously modify the same line of code in the createOrder method, or the code element dependent on by the subsequent step is mistakenly deleted by the preceding step). If there are no order conflicts or resource dependency conflicts, the preliminary verification result passes the dependency conflict verification and is determined as the target refactoring solution; if conflicts exist, it returns to step 4042 to adjust the current refactoring solution and re-verify until the dependency conflict verification passes and the target refactoring solution is obtained.
[0136] Continuing with the above embodiments, when performing verification based on the reconstructed dependent directed graph (A→B→C): Sequence conflict check: The solution steps are in the order A→B→C, which is consistent with the dependency relationship of the directed graph, and there is no reverse order.
[0137] Resource dependency conflict check: Subgroup A steps modify lines 20-50 of `createOrder`, subgroup B steps modify lines 55-70, and subgroup C steps modify lines 75-95, with no overlapping code modifications. Subgroup B steps call the `checkOrderStock` method created in subgroup A steps, which has already been created in subgroup A steps and has no missing dependencies. Finally, no dependency conflicts were determined, and the preliminary verification results were selected as the target refactoring solution.
[0138] This invention determines the order of subgroups based on dependencies and the number of steps, ensuring the overall process conforms to code logic. It also performs layer-by-layer verification from three dimensions: constraints, rules, and dependencies, eliminating constraint violations, compliance deviations, and dependency conflicts. The final generated target refactoring solution is logically coherent and can be directly executed, avoiding refactoring failures due to solution defects.
[0139] Optional, refer to Figure 2 , Figure 2 This is a schematic diagram of the knowledge graph-based code optimization system provided by the present invention. The knowledge graph-based code optimization system includes: The code recognition module 210 is used to parse the source code based on the code library to be optimized, construct an abstract syntax tree, and determine the code segment to be optimized based on the code complexity of the corresponding code in the abstract syntax tree. The dependency graph construction module 220 is used to determine the refactoring pattern corresponding to each code segment to be optimized based on the code segment to be optimized and the pre-built code optimization knowledge graph, and to construct the context dependency graph of each code segment to be optimized based on the abstract syntax tree and code optimization knowledge graph corresponding to each code segment to be optimized. The context generation module 230 is used to perform sliding window decomposition based on the context dependency graph to obtain multiple interrelated code blocks, and to simplify and merge the code blocks to obtain the current context; The refactoring and optimization module 240 is used to input the refactoring mode corresponding to each code segment to be optimized and the current context into the large language model for structured refactoring, to obtain the target refactoring scheme output by the large language model, and to optimize the abstract syntax tree based on the target refactoring scheme to obtain the optimized code library.
[0140] This invention constructs an abstract syntax tree (AST) by parsing the source code of the codebase to be optimized and determining the code segments to be optimized based on code complexity. This allows for precise location of code areas requiring optimization, avoiding blind optimization of the entire codebase. Based on the code segments to be optimized and a pre-built code optimization knowledge graph, a refactoring pattern is determined, and a context dependency graph is constructed. This allows for a deep understanding of complex dependencies between codes, overcoming the limitations of existing methods. A sliding window decomposition of the context dependency graph yields multiple interconnected code blocks, which are then simplified and merged to obtain the current context. This ensures the current context's size does not exceed the context processing budget of the large language model. By inputting the refactoring pattern and the current context into the large language model for structured refactoring, a target refactoring scheme is obtained. Based on this scheme, the abstract syntax tree is optimized. This approach not only flexibly addresses diverse code scenarios and complex code problems, enabling dynamic adjustments based on the specific context and dependencies of the code, but also leverages the powerful capabilities of the large language model to generate high-quality refactoring schemes, expanding the scope of code optimization and improving its effectiveness, thus meeting current code optimization needs.
[0141] Please see Figure 3 , Figure 3 An embodiment diagram of an electronic device provided in accordance with the present invention. For example... Figure 3 As shown, this embodiment of the invention provides an electronic device 300, including a memory 310, a processor 320, and a computer program 311 stored in the memory 310 and executable on the processor 320. When the processor 320 executes the computer program 311, it performs the following steps: The source code of the codebase to be optimized is parsed, an abstract syntax tree is constructed, and the code segment to be optimized is determined based on the code complexity of the corresponding code in the abstract syntax tree. Based on the code snippets to be optimized and the pre-built code optimization knowledge graph, the refactoring pattern corresponding to each code snippet to be optimized is determined, and the context dependency graph of each code snippet to be optimized is constructed based on the abstract syntax tree and code optimization knowledge graph corresponding to each code snippet to be optimized. The sliding window decomposition based on the context dependency graph yields multiple interrelated code blocks, which are then simplified and merged to obtain the current context. The refactoring pattern corresponding to each code segment to be optimized and the current context are input into the large language model for structured refactoring. The target refactoring scheme output by the large language model is obtained, and the abstract syntax tree is optimized based on the target refactoring scheme to obtain the optimized code library.
[0142] Please see Figure 4 , Figure 4 An embodiment diagram of a computer-readable storage medium provided in accordance with an embodiment of the present invention is shown. Figure 4 As shown, this embodiment provides a computer-readable storage medium 400 on which a computer program 311 is stored. When the computer program 311 is executed by a processor, it performs the following steps: The source code of the codebase to be optimized is parsed, an abstract syntax tree is constructed, and the code segment to be optimized is determined based on the code complexity of the corresponding code in the abstract syntax tree. Based on the code snippets to be optimized and the pre-built code optimization knowledge graph, the refactoring pattern corresponding to each code snippet to be optimized is determined, and the context dependency graph of each code snippet to be optimized is constructed based on the abstract syntax tree and code optimization knowledge graph corresponding to each code snippet to be optimized. The sliding window decomposition based on the context dependency graph yields multiple interrelated code blocks, which are then simplified and merged to obtain the current context. The refactoring pattern corresponding to each code segment to be optimized and the current context are input into the large language model for structured refactoring. The target refactoring scheme output by the large language model is obtained, and the abstract syntax tree is optimized based on the target refactoring scheme to obtain the optimized code library.
[0143] On the other hand, the present invention also provides a computer program product, which includes a computer program that can be stored on a non-transitory computer-readable storage medium. When the computer program is executed by a processor, the computer is able to execute the knowledge graph-based code optimization methods provided by the above methods, the method comprising: The source code of the codebase to be optimized is parsed, an abstract syntax tree is constructed, and the code segment to be optimized is determined based on the code complexity of the corresponding code in the abstract syntax tree. Based on the code snippets to be optimized and the pre-built code optimization knowledge graph, the refactoring pattern corresponding to each code snippet to be optimized is determined, and the context dependency graph of each code snippet to be optimized is constructed based on the abstract syntax tree and code optimization knowledge graph corresponding to each code snippet to be optimized. The sliding window decomposition based on the context dependency graph yields multiple interrelated code blocks, which are then simplified and merged to obtain the current context. The refactoring pattern corresponding to each code segment to be optimized and the current context are input into the large language model for structured refactoring. The target refactoring scheme output by the large language model is obtained, and the abstract syntax tree is optimized based on the target refactoring scheme to obtain the optimized code library.
[0144] The system embodiments described above are merely illustrative. The units described as separate components may or may not be physically separate, and the components shown as units may or may not be physical units; that is, they may be located in one place or distributed across multiple network units. Some or all of the modules can be selected to achieve the purpose of this embodiment according to actual needs. Those skilled in the art can understand and implement this without any creative effort.
[0145] Through the above description of the embodiments, those skilled in the art can clearly understand that each embodiment can be implemented by means of software plus necessary general-purpose hardware platforms, and of course, it can also be implemented by hardware. Based on this understanding, the above technical solutions, in essence or the part that contributes to the prior art, can be embodied in the form of a software product. This computer software product can be stored in a computer-readable storage medium, such as ROM / RAM, magnetic disk, optical disk, etc., including several instructions to cause a computer device (which may be a personal computer, server, or network device, etc.) to execute the methods of various embodiments or some parts of embodiments.
[0146] Finally, it should be noted that the above embodiments are only used to illustrate the technical solutions of the present invention, and not to limit them; although the present invention has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that modifications can still be made to the technical solutions described in the foregoing embodiments, or equivalent substitutions can be made to some of the technical features; and these modifications or substitutions do not cause the essence of the corresponding technical solutions to deviate from the spirit and scope of the technical solutions of the embodiments of the present invention.< / product> < / product> < / product> < / product> < / product> < / product> < / product> < / product> < / t> < / product> < / t> < / product> < / product> < / product> < / product> < / product> < / modules>
Claims
1. A code optimization method based on a knowledge graph, characterized in that, The method comprises the following steps: based on the source code library to be optimized, performing source code analysis, constructing an abstract syntax tree, and determining a code segment to be optimized based on the code complexity of the corresponding code in the abstract syntax tree; based on the code segment to be optimized and a pre-constructed code optimization knowledge graph, determining a corresponding refactoring mode for each code segment to be optimized, and based on the abstract syntax tree corresponding to each code segment to be optimized and the code optimization knowledge graph, constructing a context dependency graph for each code segment to be optimized; based on the context dependency graph, performing sliding window decomposition to obtain a plurality of code blocks associated with each other, and performing simplification and fusion on the code blocks to obtain a current context; inputting the refactoring mode corresponding to each code segment to be optimized and the current context into a large language model to perform structured refactoring, obtaining a target refactoring scheme output by the large language model, and performing code optimization on the abstract syntax tree based on the target refactoring scheme to obtain an optimized code library. 2.The knowledge graph based code optimization method of claim 1, wherein, The method comprises the following steps: mapping each code segment to be optimized to a minimum containing abstract syntax tree node to obtain a minimum abstract syntax tree node; based on the minimum abstract syntax tree node, tracing upwards and locking to the nearest semantic boundary to obtain an initial seed node group; based on each seed node in the seed node group, performing traversal in the code optimization knowledge graph to find the dependent items and reverse dependencies of each seed node, and obtaining a first dependency traversal result; based on the preliminary dependency traversal result, sequentially performing ring detection deduplication, repeated node merging and node pruning to obtain a second dependency traversal result after ring removal and pruning; based on the dependency ambiguity existing in the second dependency traversal result, sequentially performing polymorphism, generic and overload processing to obtain a third dependency traversal result; based on the third dependency traversal result, constructing a context dependency graph for each code segment to be optimized. 3.The knowledge graph based code optimization method of claim 1, wherein, The method comprises the following steps: based on the third dependency traversal result, determining whether there is symbol meta information in the external library, if there is, the external library is included in the code optimization knowledge graph, if not, the entire external library is included in the knowledge graph as a single node, obtaining a fourth dependency traversal result after external library and cross-module dependency; the external library refers to a third-party software library, tool package and framework outside the code library to be optimized, which is directly or indirectly referenced by the code to be optimized; based on the fourth dependency traversal result, performing analysis on the framework annotation or configuration binding to generate implicit dependency edges, collecting and constructing low-confidence reflection edges for reflection string constants and patterns, and supplementing the implicit dependency edges and low-confidence reflection edges to the fourth dependency traversal result to obtain a fifth dependency traversal result; based on the fifth dependency traversal result, performing traversal termination verification to obtain a sixth dependency traversal result that meets the stopping condition; based on the sixth dependency traversal result, combining multiple dimensions to score, sort and filter nodes and edges to obtain a target dependency traversal result; Based on the target dependency traversal result, a JSON file or a graph database subgraph containing node identification, node type, node position, node weight, node confidence and edge information is generated, and the JSON file or the graph database subgraph is checked and packaged to obtain a context dependency graph of each code segment to be optimized.
4. The knowledge graph based code optimization method of claim 3, wherein, The JSON file or the graph database subgraph is checked and packaged to obtain the context dependency graph of each code segment to be optimized, including: Perform integrity and compliance checking on the JSON file or the graph database subgraph to obtain a structured subgraph that passes the checking; Associate and map the structured subgraph with the code segment to be optimized to obtain a target subgraph after association and mapping; Based on the target subgraph, the dependency graph standard format is packaged to obtain the context dependency graph corresponding to each code segment to be optimized. 5.The knowledge graph based code optimization method of claim 1, wherein, The construction process of the code optimization knowledge graph includes: Based on the engineering root directory and module boundary construction file of the code to be optimized, the project scope is determined in combination with the package management file or the construction file; the project scope includes the dependency list of the project and the external library processing strategy; the external library processing strategy includes determining whether the external library has symbol metadata information; Based on the project scope, the programming language type of the source code file is determined through the file suffix, shebang or configuration, to obtain the language identification corresponding to each source code file, and the source code file of each language is parsed based on the language identification to obtain the parsing result corresponding to each source code file; the parsing result includes an abstract syntax tree, a symbol table, a reference relationship, an optional generated type information and a control flow abstract; Based on the parsing results of multiple languages, the abstract syntax trees of different languages are normalized to a unified intermediate representation to obtain a unified intermediate representation result, and the parsing success rate, parsing alarm information and degradation path are recorded based on the unified intermediate representation result to obtain a parsing quality control report; Based on the abstract syntax tree and the symbol table, symbols (functions / methods / classes / interfaces / fields / enumerations), types, files, modules, packages, and third-party libraries are extracted as nodes of the knowledge graph to obtain a node group of the knowledge graph, and based on the node group, edges of call, override, inheritance, implementation, import, read or write, dependency, event subscription, dependency injection binding and reflection type are constructed to obtain an edge group of the knowledge graph. Based on the obtained node group and edge group of the knowledge graph, a stable identifier is generated for each node in combination with a preset node generation rule, version information and commit fingerprint are attached, and the code optimization knowledge graph is constructed. 6.The knowledge graph based code optimization method of claim 1, wherein, The large language model includes a feature constraint layer, a semantic rule mapping layer, a step generation layer and an integration and verification layer. The reconstruction mode corresponding to each code segment to be optimized and the current context are input into the large language model for structured reconstruction to obtain a target reconstruction scheme output by the large language model, including: The reconstruction mode corresponding to each code segment to be optimized and the current context are input into the large language model for structured reconstruction, wherein, in the feature constraint layer, the syntax structure features of each code segment to be optimized and the applicable boundary conditions of the corresponding reconstruction mode are matrix constructed to obtain a reconstruction constraint matrix, and based on the code block correlation degree contained in the current context, the matching result of the reconstruction constraint matrix is combined to determine a reconstruction priority sequence; the code block correlation degree refers to the calling dependency frequency and data transmission times between code blocks in the current context; In the semantic rule mapping layer, based on the semantic features of the high-priority code blocks in the reconstruction priority sequence and the mapping relationship between the reconstruction mode and the code features in the code optimization knowledge graph, the reconstruction association rules are determined, and based on the dependency relationship between the associated objects of each rule in the reconstruction association rules and the code blocks in the current context, a reconstruction dependency directed graph is determined; the high-priority code block refers to a code block in the reconstruction priority sequence that exceeds a preset priority threshold; In the step generation layer, based on the strong connectivity of the reconstruction dependency directed graph and the priority distribution of the code blocks in the reconstruction priority sequence, a reconstruction subgroup is determined, and based on the interaction logic of the code elements in the reconstruction subgroup and the rule content in the reconstruction association rules matched with the reconstruction subgroup, a reconstruction step group in the reconstruction subgroup is determined; the strong connectivity refers to the maximum subgraph in the reconstruction dependency directed graph that satisfies that there is a bidirectional path between any two nodes; In the integration and verification layer, the scheme generation and verification are performed based on the reconstruction constraint matrix, the reconstruction association rules, the reconstruction subgroup, the reconstruction step group, and the reconstruction dependency directed graph, to obtain the target reconstruction scheme.
7. The knowledge graph based code optimization method of claim 6, wherein, The scheme generation and verification based on the reconstruction subgroups, the reconstruction step groups, and the reconstruction dependency directed graph to obtain the target reconstruction scheme, includes: Based on the number of reconstruction step groups in each reconstruction subgroup and the dependency relationship between the reconstruction subgroups in the reconstruction dependency directed graph, the reconstruction order between the reconstruction subgroups is determined; Based on the reconstruction order between the reconstruction subgroups and the reconstruction step groups in each reconstruction subgroup, a current reconstruction scheme is determined; Based on the reconstruction constraint matrix and the reconstruction association rules, the current reconstruction scheme is subjected to constraint matching and compliance verification to obtain a preliminary verification result that passes the matching and compliance; Based on the reconstruction dependency directed graph, the preliminary verification result is subjected to dependency conflict verification to obtain the target reconstruction scheme that passes the dependency compatibility.
8. A code optimization system based on a knowledge graph, characterized by, The method is applied to the code optimization method based on the knowledge graph as claimed in any one of claims 1 to 7; The code optimization system based on the knowledge graph includes: A code recognition module is configured to parse source code based on a code library to be optimized, construct an abstract syntax tree, and determine code segments to be optimized based on the code complexity of the corresponding codes in the abstract syntax tree. A dependency graph construction module is configured to determine a reconstruction mode corresponding to each code segment to be optimized based on the code segment to be optimized in combination with a pre-constructed code optimization knowledge graph, and construct a context dependency graph of each code segment to be optimized based on an abstract syntax tree corresponding to each code segment to be optimized and the code optimization knowledge graph; A context generation module is configured to perform sliding window decomposition based on the context dependency graph to obtain a plurality of code blocks that are associated with each other, and perform simplification and fusion on the code blocks to obtain a current context; A reconstruction and optimization module is configured to input the reconstruction mode corresponding to each code segment to be optimized and the current context into a large language model to perform structured reconstruction, obtain a target reconstruction scheme output by the large language model, and perform code optimization on the abstract syntax tree based on the target reconstruction scheme to obtain an optimized code library.
9. An electronic device, characterized by Comprise: A memory is configured to store a computer software program; A processor is configured to read and execute the computer software program, and when the processor executes the computer software program, the method for optimizing code based on a knowledge graph according to any one of claims 1 to 7 is implemented.
10. A non-transitory computer readable storage medium, characterized in that, The storage medium stores a computer software program, and when the computer software program is executed by the processor, the method for optimizing code based on a knowledge graph according to any one of claims 1 to 7 is implemented.
Citation Information
Cited By
Code sequence compression method, device and equipment combining semantic analysis with attention
CN122285016A