A method for cross-programming language code analysis and refactoring that integrates large language models

By constructing a semantic equivalence graph and introducing a dual-constraint verification mechanism, the problem of unified modeling and intent understanding in code analysis and refactoring in cross-language projects is solved, achieving highly accurate and reliable automated refactoring.

CN123114538APending Publication Date: 2026-11-17TIANJIN QINGLIU SOFTWARE CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202511559117.8
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-10-29
Publication Date
2026-11-17

AI Technical Summary

Technical Problem

Existing technologies lack unified modeling capabilities in code analysis and refactoring of cross-language projects, making it difficult to understand high-level refactoring intentions. Furthermore, the refactoring schemes generated by large language models lack reliability verification, making automated refactoring difficult to implement.

Method used

By constructing a semantic equivalence graph, the source code of different programming languages ​​is uniformly converted into abstract semantic concepts. The natural language intent is converted into formal logical constraints using a large language model, and a dual constraint verification mechanism is introduced to ensure that the reconstructed graph satisfies equivalence and intent constraints.

Benefits of technology

It enables global code analysis across language projects, improving the accuracy and reliability of refactoring and ensuring that refactoring does not break the original functionality while achieving the expected goals.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123114538A_ABST
    Figure CN123114538A_ABST
Patent Text Reader

Abstract

This application relates to the fields of software engineering and artificial intelligence technology, and discloses a method for cross-programming language code analysis and reconstruction that integrates a large language model. The method includes: parsing the source code of a project containing one or more programming languages, constructing a unified semantic equivalence graph covering the source code; receiving reconstruction intentions in natural language form, and calling a preset intent parsing large language model to convert the intentions into formal logical constraints; extracting context subgraphs from the semantic equivalence graph based on the reconstruction intentions, constructing reasoning hints containing subgraph serialization descriptions and formal logical constraints, and calling a preset graph reasoning large language model to generate graph modification schemes to obtain candidate reconstruction graphs; finally, performing rigorous double constraint verification on the candidate reconstruction graphs. This invention solves the problems of existing technologies in handling cross-language projects, accurately understanding high-level intents, and the low reliability of model-generated results.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the fields of software engineering and artificial intelligence, specifically to a method for cross-programming language code analysis and refactoring that integrates a large language model. Background Technology

[0002] As modern software systems become increasingly larger and more complex, software maintenance, especially code refactoring, has become a crucial aspect of ensuring code quality, readability, and maintainability. Code refactoring aims to improve the internal structure of software without altering its external behavior.

[0003] However, contemporary software projects commonly employ a hybrid development model using multiple programming languages. For example, in microservice architectures or full-stack applications, the front-end, back-end, and data layers each use different languages. Existing static analysis tools and refactoring engines are typically designed for specific languages ​​(such as Java or C++), lacking the ability to model cross-language dependencies (such as relationships established through API calls, shared data storage, or remote procedure calls). This limitation in analytical capabilities means that when performing global refactoring involving multi-language modules, tools cannot provide an accurate dependency view, making automated refactoring difficult to implement.

[0004] On the other hand, developers' refactoring needs are often high-level and semantic, such as optimizing the performance of a data processing flow or fixing thread safety issues in a module. Traditional refactoring tools lack the ability to understand these high-level natural language intentions; they can usually only perform predefined, low-level refactoring operations (such as extracting methods or renaming variables). This forces developers to manually break down high-level intentions into a series of tedious and error-prone specific operations, resulting in very low automation.

[0005] In recent years, Large Language Models (LLMs) have demonstrated potential in code generation, and their ability to understand natural language offers new insights into solving the aforementioned intent understanding problems. Nevertheless, directly applying LLMs to code refactoring tasks still faces significant reliability challenges. LLMs are inherently probabilistic, and their generated results lack deterministic logical guarantees, easily leading to syntactically correct but logically flawed code or code that fails to fully realize its intent. In refactoring scenarios, existing technologies lack effective mechanisms to rigorously verify whether the refactoring solutions generated by LLMs simultaneously satisfy functional equivalence (without breaking the original functionality) and intent correctness (truly achieving the refactoring goal).

[0006] In summary, existing technologies have significant shortcomings in handling cross-language project analysis, high-level intent understanding, and ensuring the reliability of automated refactoring. Summary of the Invention

[0007] To address the shortcomings of existing technologies, this invention provides a cross-programming language code analysis and refactoring method that integrates a large language model. This method solves the problems of insufficient analytical capabilities, difficulty in accurately understanding the refactoring intent of natural language, and low reliability when using a large language model to refactor code in cross-language projects.

[0008] To achieve the above objectives, the present invention provides the following technical solution: a method for cross-programming language code analysis and refactoring that integrates a large language model, comprising: S1. Parse the source code of a project containing one or more programming languages, replace the syntax nodes in the source code with normalized abstract semantic concepts using a preset semantic and syntax mapping knowledge base, and establish semantic edges between the normalized abstract semantic concepts according to the dependencies of the source code, and construct a semantic equivalence graph covering the source code. S2. Receive the reconstruction intention in natural language form, and call a preset intent parsing large language model to convert the reconstruction intention into a formal logical constraint that can be executed on the semantic equivalence graph; S3. Extract a context subgraph from the semantic equivalence graph based on the code scope related to the refactoring intent; S4. Construct a reasoning hint that includes the serialized description of the context subgraph and the formal logical constraints, and call a preset graph reasoning big language model to generate a graph modification scheme. S5. Apply the graph modification scheme to the context subgraph to obtain a candidate reconstructed graph; S6. Perform dual constraint verification on the candidate reconstruction graph, the dual constraint verification including: Extract the semantic invariants of the context subgraph and perform equivalence verification based on the semantic invariants on the candidate reconstruction graph; Perform intent constraint verification based on the formal logic constraints on the candidate reconstruction graph; Reconstructed code is generated based on the candidate reconstruction graph only if both the equivalence verification and the intent constraint verification pass.

[0009] Preferably, the cross-programming language code analysis and refactoring method further includes an execution code comment generation workflow, the workflow comprising: Receive a request to generate comments for a target code segment; Extract the context subgraph corresponding to the target code segment from the semantic equivalence graph. The context subgraph contains the data flow direction, cross-language caller, or path security attributes of the target code segment. Construct a semantically enhanced hint that includes the syntactic information of the target code segment and the serialized semantic information of the context subgraph; The document is invoked to generate a large language model to generate code comments that reveal the contextual role or potential risks of the target code segment; Inject the code comments into the target code segment according to the specified style.

[0010] This invention provides a method for cross-programming language code analysis and refactoring that integrates a large language model. It has the following beneficial effects: 1. This invention constructs a semantic equivalence graph to uniformly convert the source code of different programming languages ​​into normalized abstract semantic concepts, and uses API call matching or shared data storage matching to establish cross-language link edges. This solves the technical problem that existing tools are unable to perform overall analysis of mixed language projects, enabling code analysis and refactoring to be carried out across the entire project scope, and significantly improving the ability to handle complex systems.

[0011] 2. This invention utilizes a pre-defined intent parsing large language model to automatically convert the user's input natural language form of reconstruction intent into formal logical constraints that can be executed on a semantic equivalence graph. This method accurately compiles fuzzy natural language requirements into machine-verifiable logical goals, providing clear and unambiguous guidance for subsequent automated reconstruction and improving the accuracy of reconstruction.

[0012] 3. This invention verifies the candidate reconstruction graph generated by the graph reasoning large language model by introducing a rigorous dual-constraint verification mechanism. This mechanism performs equivalence verification by extracting semantic invariants to ensure that the reconstruction does not destroy the original functionality; at the same time, it performs intent constraint verification through formal logical constraints to ensure that the reconstruction achieves the expected goal. This closed-loop design of post-generation verification effectively suppresses random errors in the model and greatly improves the reliability of automated code reconstruction. Attached Figure Description

[0013] Figure 1 This is a flowchart illustrating the overall process of the method of the present invention. Figure 2 This is a system functional module architecture diagram of the present invention; Figure 3 This is a flowchart illustrating workflow one of the present invention; Figure 4 This is a schematic diagram of the SEG-based graph reasoning process of the present invention; Figure 5 This is a schematic diagram of the dual-constraint formal verification process of the present invention; Figure 6 This is a schematic diagram of the trusted code reverse generation process of the present invention; Figure 7 This is a schematic diagram of the code comment generation process of the present invention.

[0014] The modules are as follows: 10. Source code parsing and normalization module; 20. Semantic equivalence graph construction and storage module; 30. Intent parsing and constraint formalization module; 40. Graph reasoning and reconstruction module; 50. Dual constraint verification module; 60. Code generation and integration module; 70. Document generation module; 80. Knowledge base and model management module. Detailed Implementation

[0015] 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.

[0016] See attached document Figure 2 This invention provides a method for cross-programming language code analysis and refactoring that integrates a large language model, which can be implemented by a system deployed on one or more computing devices. The system may include a processor (e.g., CPU and / or GPU), memory, storage, and a network interface. The storage is used to persistently store program instructions, a semantic and syntactic mapping knowledge base (…). ) and the generated semantic equivalence graph ( In one embodiment, the system may include the following functional modules: Source code parsing and normalization module 10: Used to receive project source code. The source code It may include one or more programming languages ​​(e.g.) (Source file) Source code analysis and normalization module 10 calls various programming languages. The corresponding parser generates an abstract syntax tree. and control flow graph Furthermore, the source code analysis and normalization module 10 accesses the semantic and syntactic mapping knowledge base. , and syntax nodes in Replace with normalized abstract semantic concepts .

[0017] Semantic Equivalence Graph (SEG) Construction and Storage Module 20: Used to receive normalized semantic concept nodes output by the source code parsing and normalization module 10. and according to and Data flow, control dependencies, and invocation relationships in the normalized semantic concept nodes Establish semantic edges between This allows for the construction of a semantic equivalence graph covering the entire project. The semantic equivalence graph construction and storage module 20 is also responsible for... It is persistently stored in memory.

[0018] Intent parsing and constraint formalization module 30: Used for analyzing or reconstructing intents in the natural language form of user input. (For example, checking for SQL injection or making it thread-safe). The Intent Parsing and Constraint Formalization module 30 calls a large language model for intent parsing. ,Will Automatic translation available Formal logical constraints of execution .

[0019] Graph Reasoning and Reconstruction Module 40: Used to... The relevant code range, from Extracting context subgraphs The graph reasoning and reconstruction module 40 will... , and Together, we can create a prompt. And invoke a graph reasoning large language model .

[0020] The output is a graph modification scheme. (For example, a set of graph manipulation instructions). Graph reasoning and reconstruction module 40 will... Applied to The candidate reconstruction graph is obtained. .

[0021] Dual Constraint Verification Module 50: Used to generate in-graph reasoning and reconstruction module 40 The verification is then performed. First, the dual constraint verification module 50 verifies the data by... Perform analysis (e.g., data flow analysis or symbolic execution) to extract semantic invariants corresponding to its core logic. Next, the dual constraint verification module 50 calls the constraint solver to perform the verification. Two checks are performed simultaneously: equivalence verification. and intent constraint verification .

[0022] Code generation and integration module 60: Used to receive verification decisions from dual-constraint verification module 50 If and only if When true, the code generation and integration module 60 initiates the reverse generation process. It utilizes a knowledge base. Inverse mapping and target language The syntax template will include the validated abstract graph. Translate back to the specific target language source code And integrate it into the project.

[0023] Documentation generation module 70: Used to execute a separate code comment generation workflow. When a source file is received... When a request to generate annotations is received, the document generation module 70 retrieves the annotations from... Extract the corresponding context subgraph The document generation module 70 constructs a document containing... (Grammar information) and Semantic enhancement tips for (semantic information) And call a document to generate a large language model. To generate high-quality code comments Subsequently, the document generation module 70 will... Injected according to the standard format middle.

[0024] Knowledge Base and Model Management Module 80: Used for storing, updating, and managing the semantic and syntactic mapping knowledge base. Meanwhile, the knowledge base and model management module 80 is responsible for managing the multiple large language models described in this embodiment of the invention. It performs loading, version control, and resource scheduling.

[0025] In practical applications, the interactions between the above modules collectively constitute the technical solution of this invention. For example, the source code parsing and normalization module 10 and the semantic equivalence graph construction and storage module 20 are constructed... Assets. When a user initiates a refactoring request, the graph analysis and constraint formalization module 30, the graph reasoning and refactoring module 40, the double constraint verification module 50, and the code generation and integration module 60 are activated sequentially, executing the analysis and refactoring workflow. When a user initiates an annotation request, the documentation generation module 70 is activated, executing the documentation generation workflow. The knowledge base and model management module 80 provides basic data and model support for all other modules.

[0026] The core implementation steps of the method of the present invention will be described in detail below with reference to the accompanying drawings. First, the specific implementation method for constructing the semantic equivalence graph, which is the core asset of the present invention, will be described. This step corresponds to... Figure 2 The functional implementation of the source code parsing and normalization module 10 and the semantic equivalence graph construction and storage module 20 is shown.

[0027] See attached document Figure 1 In the initial stage of SEG construction, the source code parsing and normalization module 10 receives the input project source code. . It can contain one or more source files. ,and They can belong to different programming languages (For example , ).

[0028] The source code analysis and normalization module 10 first identifies each source file. programming languages Subsequently, the source code parsing and normalization module 10 uses its internally configured set of parsers to perform parsing for the code. Invoke the corresponding syntax parser. For example, for The file calls the Java syntax parser for... The file invokes the Python syntax parser.

[0029] Parser pairs The execution results of syntax analysis and control flow analysis are as follows: ; in, yes An abstract syntax tree, which represents the hierarchical syntax structure of code. yes The control flow graph represents the basic blocks and jump relationships of code execution. Representative of the source file The parsing operation performed.

[0030] Semantic and Syntax Mapping Knowledge Base ( ) and normalization: To eliminate differences in programming languages To address the grammatical differences between them, this invention introduces a semantic-syntax mapping knowledge base. This semantic and grammatical mapping knowledge base The knowledge base and model management module 80 is responsible for storage and management.

[0031] It is a pre-built data structure (e.g., a key-value database or hash table) used to store syntactic elements from a specific language. To a unified, abstract semantic type The mapping relationship can be expressed as: ; in, It is a programming language Syntax elements in the byte array, such as an API call signature (e.g., 'java.util.concurrent.ReentrantLock.lock()') or an AST node type (e.g., 'java:ForStatement'). It is an abstract semantic concept identifier that is independent of language (such as...) or ).

[0032] The following mapping rules can be stored in the middle: ; ; ; ; Source code analysis and normalization module 10 in obtaining and Then, traverse its primitives (nodes and edges) and use... The knowledge base normalizes the primitives. For or One of the syntax elements Source code analysis and normalization module 10 query If a mapping exists, replace the type identifier of the node with its corresponding one. As shown in the example above, after normalization, Java's 'lock()' call and Python's 'acquire()' call are both uniformly identified as... .

[0033] The semantic equivalence graph construction and storage module 20 is responsible for receiving all normalized primitives from the source code parsing and normalization module 10 and assembling them into a unified semantic equivalence graph covering the entire project. The following is the process of generating the elements in the diagram: node Generation: Each node in This represents a normalized semantic concept. The semantic equivalence graph construction and storage module 20 creates a node for each normalized primitive. Its data structure can be defined as: ; in, It is the globally unique identifier of this node. It is a set of attributes (such as key-value pairs) used to store the metadata of the node. It should include at least: the location of the original code (source file path, start and end line numbers), the original syntax text, and the range of variables (if applicable).

[0034] side Generation: Each edge in Represents the semantic relationships between nodes. The semantic equivalence graph construction and storage module 20 is based on... and The implicit dependencies in Establish edges between nodes in Its data structure can be defined as: ; in, It is the source node. It is the target node. It is the relationship type of this edge.

[0035] The semantic equivalence graph construction and storage module 20 supports generating at least the following types of graphs. (Data flow edge): through Data flow analysis (such as arrival and definition analysis) is performed on the source node. The variable value defined at this location can reach the target node. If a location is used, then a path is established from arrive of side.

[0036] (Controlling Dependency Edges): Based on The post-dominator relationship is generated. If Whether execution occurs depends on The execution result of (for example, a conditional branch node) then establishes a path from arrive of side.

[0037] (Calling edge): According to Function call expression generation in this function For the call point, This is the entry point for the called function.

[0038] Cross-language links ( Generation of semantic equivalence graphs: To enable cross-language analysis, the semantic equivalence graph construction and storage module 20 also includes a linking submodule for generating... Edges of type [type]. Used to connect languages ​​that belong to different languages ​​(e.g.) and )of Subgraphs. Their generation mechanisms include, but are not limited to: API call matching: Linked submodule identification (For example, the fetch( / api / data) call in the front-end JavaScript, its for )and (For example, the `@app.route( / api / data)` definition in the backend Python, its...) for By matching its API path ( / api / data), HTTP method, and other characteristics, a path is established from... arrive of side.

[0039] Shared data storage matching: Linked submodule identification (For example, publishing a message to message queue topic Topic-A) and (For example, subscribing to messages from Topic-A). Establish a system by matching the shared resource identifier Topic-A. Edges. This mechanism also applies to the identification of shared database tables.

[0040] Finally, the semantic equivalence graph construction and storage module 20 will generate... The entire (or fragmented) data is persistently stored in the graph database for querying and analysis by other modules in the system.

[0041] See attached document Figure 3 The intent parsing and constraint formalization process of this invention is as follows. This step describes the initial stage of workflow one (analysis and reconstruction), the function of which is executed by the intent parsing and constraint formalization module 30. The goal of this step is to process the unstructured natural language intent input by the user. This is transformed into a machine-readable formal logical constraint that can be executed on a semantic equivalence graph. .

[0042] When this process starts, the intent parsing and constraint formalization module 30 receives the natural language intent provided by the user through the input interface. The intent parsing and constraint formalization module 30 then calls a large language model for intent parsing managed by the knowledge base and model management module 80. .Should The model can adopt a sequence-to-sequence architecture (such as Transformer) and be pre-trained on data pairs containing (natural language descriptions and formal logical expressions) to enable it to map natural language to structured logical outputs.

[0043] Intent parsing and constraint formalization module 30 will As The input to the model, the execution of the transformation function by the model, can be represented as follows: ; in, Representing the user's natural language intent, such as checking for all SQL injection vulnerabilities; This represents the transformation operation performed by the large language model to interpret the intended meaning; The formal logical constraints representing the output of the model are a set based on Logical predicates defined by graph attributes and topology.

[0044] It is defined using a formal, structured data format (e.g., JSON, XML, or a domain-specific language based on first-order logic) to ensure that it can be unambiguously parsed and executed by the double-constraint validation module 50. The predicates and variables in the text directly correspond to The constituent elements include nodes, edges, the semantic type of nodes, and the relational type of edges.

[0045] The following is given Several specific implementations: Example 1: Constraints for SQL Injection Vulnerability Detection ( ) when =When checking for all SQL injection vulnerabilities, Model output .

[0046] The formal definition first depends on the definition of the following node set: (HTTP input source node set); (Database query for destination node set); (Data purification node set); A function that returns a value. All from From any node in The data flow path (i.e., the edges on the path) of any node in the data flow path. All A set of ).

[0047] The constraint is defined as: ; in, yes The set of all nodes in; It is a node; , , It is a specific semantic type identifier; It is a subset of nodes; It is a set of data flow paths; It is a specific data flow path; It is a path A node on; Represents a universal quantifier; Quantifiers representing existence; This represents logical equivalence.

[0048] Constraint Explanation: This constraint stipulates that for each... The data flow path from the HTTP input source to the database query destination. It must exist At least one node In this path Above, and the node Belongs to the data purification node set .

[0049] Example 2: Thread-safe refactoring intent constraints ( ) when =When refactoring this function to be thread-safe, Model output .

[0050] The formal definition depends on the following definitions of predicates: Access Operation (A node) reads or writes shared resources (Another node); :access and Concurrent execution is possible (depending on) (Derivation of control flow and call relationships in the text). :access It is a write operation; :access and exist They are all locked by the same mutex (e.g., .

[0051] The constraint is defined as: ; in, It is a shared resource node; It is a resource access operation node; , , , It is a formal logic predicate; Represents logical NOT; Represents logical AND; Represents logical OR.

[0052] Constraint definition: This constraint stipulates that there is no ( Such a pair of visits They access the same resource It may be concurrent, at least one of which is a write operation, and ( They do not ( They are protected by the same mutex lock.

[0053] Example 3: Cyclic Performance Optimization Constraints ( ) when =Optimize this loop by removing loop-invariant queries. Model output .

[0054] The formal definition depends on the following predicates and sets: The set of nodes within the target loop body; : predicate, when a node The data input on which the execution depends It is true if it does not change during the iteration process.

[0055] The constraint is defined as: ; in, It is the set of nodes in the loop body; It is a collection of database query nodes; It is a database query node; It is a loop invariant predicate.

[0056] Constraint Explanation: This constraint stipulates that there is no (¬∃) database query node. It is simultaneously located (∧) in Inside, and ( () is a loop invariant.

[0057] Intent parsing and constraint formalization module 30 in generation Then, output it. For analysis-type tasks (such as Example 1), It is passed to the dual-constraint verification module 50 for immediate verification. This applies to refactoring tasks (such as those in Examples 2 and 3). It is simultaneously passed to the graph reasoning and reconstruction module 40 (used to guide the generation of reconstruction schemes) and the dual constraint verification module 50 (used for subsequent intent verification).

[0058] See attached document Figure 4 The steps of SEG-based graph reasoning are based on obtaining formal intent constraints. (Specifically referring to the refactoring intent) is executed after this step, and its functionality is mainly implemented by the graph reasoning and refactoring module 40. The goal of this step is to perform the refactoring after the abstract semantic equivalence graph ( Reasoning is performed at the ) level to generate a satisfying Image modification scheme Instead of directly generating source code, its specific content is as follows: The graph reasoning and reconstruction module 40 first performs the context subgraph extraction operation. The input to this operation is a complete... (From the semantic equivalence graph construction and storage module 20) and Implicit code scope (e.g., function names, file names, or line numbers). Graph reasoning and refactoring module 40 utilizes... Middle node of Metadata (including the location of the original code) is used to locate the initial node set corresponding to the code scope. This operation can be expressed as the following formula: ; in, The function represents the extraction algorithm.

[0059] In one embodiment, the algorithm from Departure, at The above performs a graph traversal (e.g., breadth-first search or depth-first search), with the traversal depth being a preset value. Alternatively, the process can be repeated until a boundary node of a specific type is encountered (e.g., the entry / exit node of a module's public API). The nodes traversed and the edges between them together form the context subgraph. . It contains the relevant logic required to perform the reasoning.

[0060] After completing the context subgraph extraction operation, the graph reasoning and reconstruction module 40 then constructs a structured reasoning hint. This prompt was used as a graph reasoning large language model. Input. The model is managed and invoked by the knowledge base and model management module 80. It can adopt a graph-to-sequence or large Transformer model structure, and its mathematical form is: ; in, It is a function used to convert graph structures Serialization to text The serialization format can be GML (Graph Modeling Language), JSON (describing node sets and adjacency lists), or a linear text description (e.g., node A (type...)). )pass Connect to node B (type) )); These are formal constraints from the Intent Resolution and Constraint Formalization module 30.

[0061] The model is trained to understand The graph structure described, and in and Under joint guidance, output a function for modification The instruction sequence.

[0062] The model's output is a structured graph modification scheme. It can be represented as: ; It is a data structure containing instructions for manipulating atomic graphs, not code. In one instance, The data structure is defined as follows: ; in, The new set of nodes to be added (e.g., a set with...) (New node); The new set of edges to be added (e.g., new edges used to redirect data flow or control flow) or side); It is the set of nodes to be deleted; It is the set of edges to be deleted; It is a set of instructions for modifying the attributes of nodes or edges.

[0063] The graph application logic inside the graph reasoning and reconstruction module 40 receives... And it is deterministically applied to the original subgraph. Above, to generate candidate reconstruction graphs. It can be represented as: ; in: This represents the operation to modify the application diagram. This operation follows... The instruction set in (e.g., first execute) , Execute again )Revise The graph structure is obtained .

[0064] The graph reasoning and reconstruction module 40 generates... Then, the original subgraph Candidate Reconstruction Graph And intent constraints from the intent parsing and constraint formalization module 30 They are then passed together to the dual constraint verification module 50 to perform subsequent dual verification steps.

[0065] See attached document Figure 5 The dual-constraint formal verification step is the core of achieving trusted reconstruction, and its function is executed by the dual-constraint verification module 50. The input to the dual-constraint verification module is the original context subgraph from the graph reasoning and reconstruction module 40. and candidate reconstruction graph And intent constraints from intent parsing and constraint formalization module 30. .

[0066] The goal of this step is to ensure, through formal methods, that before any code changes are applied... Simultaneously satisfying two independent constraints: Its core functional logic and Preserving equivalence (by semantic invariants) definition); Its structure satisfies the user-specified refactoring intent (by... definition).

[0067] Before performing the verification, the dual constraint verification module 50 first verifies the original subgraph. Perform analysis to extract its semantic invariants. It can be represented as: ; in: Represents the invariant extraction function. It is input. It is the formal invariant of the output.

[0068] Yes Logical description of core functionality. In one example... The function is achieved by... This is achieved through symbolic execution. The function will... Input nodes (such as) Symbolize, and along the diagram and Through reasoning, a set of descriptions is eventually obtained. Output node ( Symbolic expressions of ). This is defined as the functional mapping of this set of inputs and outputs: ,in It is the function expression obtained by symbolic execution.

[0069] In another example, The function identifies data streams through analysis. All from arrive The main data flow path and the key computing nodes along it. It is defined as the set of these data flow paths and their computational topologies that must be retained.

[0070] The dual constraint verification module 50 contains a general verification function. Used to inspect a graph Does a constraint satisfy? In one embodiment, The function will draw graphs (For example ) and constraints (For example or This is translated together into a logical formula acceptable to a satisfiability modulo theory (SMT) solver (e.g., Z3). The function then calls the SMT solver to solve the formula. If the formula is satisfiable (or its negation is unsatisfiable, depending on the verification objective), then... The function returns true otherwise.

[0071] After performing analysis on the original subgraph, the following verification was performed: The dual constraint verification module 50 first examines the candidate reconstruction graph. Performing equivalence verification can be represented as: ; in: It is the Boolean result of the equivalence verification. Functions are checked here. Does it still satisfy the requirement from Extracted semantic invariants For example, if Obtained through symbolic execution , The function will be used for Similarly, executing the symbolic command yields the following result. Then, the SMT solver is required to prove... .

[0072] This step ensures Modifications made to the model (e.g. in) Add to task The node was not destroyed. The original core computing logic.

[0073] 50 pairs of dual-constraint verification modules were passed through equivalence verification (or in parallel). Execution intent constraint validation, which can be represented as ; in: It is a Boolean result intended for verification. Functions are checked here. Does it satisfy the formal intent from the Intent Resolution and Constraint Formalization Module 30? For example, if The thread safety constraints defined above , The function will Formula applied because (Theoretically) it has been Added lock node , The result of the predicate calculation will change, making The final evaluation result of the formula is true.

[0074] The dual-constraint verification module 50 ultimately generates the final acceptance decision signal by combining the two verification results through logical AND operations. It can be represented as: ; If and only if True (i.e.) When both equivalence verification and intent verification pass, the dual constraint verification module 50 will... Signal (True) and Verified Passed to the code generation and integration module 60.

[0075] like It is false (i.e.) or (At least one is false), Double Constraint Validation Module 50 blocks Enter the code generation phase. At this point, the dual constraint verification module 50 will generate a code containing failure information (e.g., indicating that it is...). still A feedback signal indicating verification failure is sent back to the graph reasoning and reconstruction module 40. Upon receiving this signal, the graph reasoning and reconstruction module 40 can adjust its... And call back The model is used to initiate a correction cycle until a model that passes dual verification is generated. Or reach the maximum number of attempts.

[0076] See attached document Figure 6 The trusted code reverse engineering step outlines the final stage of Workflow One (Analysis and Refactoring), performed by the code generation and integration module 60. The goal of this step is to transform the language-independent candidate refactoring graphs that have passed dual-constraint verification into a single, more robust and integrated framework. Switch back to the target programming language Specific source code .

[0077] The execution of this step is subject to strict conditions. The code generation and integration module 60 first receives a decision signal from the dual constraint verification module 50. And verified The code generation and integration module 60 is only available in [location 60]. The code generation process only begins when the value of is true. If the value is false, this step is terminated and no code is generated, thus ensuring that only modifications that pass formal verification can be applied.

[0078] when When true, the code generation and integration module 60 first determines the target language for generation. . It can be specified by the user, or through parsing. Middle node of Metadata (which stores file type or language information of the original code) is used to automatically infer this.

[0079] Subsequently, the code generation and integration module 60 sends a request to the knowledge base and model management module 80 to obtain two key datasets: Reverse semantics and syntax mapping knowledge base ; For the target language Syntax template library .

[0080] Reverse mapping knowledge base It stores the mapping relationship from abstract semantic types to specific syntactic elements of a particular programming language, and its definition can be expressed as: ; Syntax Template Library Defined The program structure skeleton of the language. It specifies how to... The edge in (its type) include (etc.) to organize and splice Syntax elements obtained from the query For example, a Type of node Its related The subgraph pointed to by the edge will be It is wrapped by the corresponding for loop or while loop template.

[0081] The code generation and integration module 60 contains a code generation function. This function performs the operation on... Graph traversal (e.g., based on) Perform a depth-first traversal, or based on (Perform topological sorting on the edges).

[0082] ; in, It is the output source code text.

[0083] During the traversal, for Each node in , The function performs the following operations: extract semantic types and attributes (e.g., variable names); Query Retrieve the corresponding syntax element; Check connection edge (and (type), from Choose the appropriate syntax structure template; Will and Information from the template (such as variable names) is filled into the selected template and combined in the traversal order to form the final template. text; This process ensures New nodes added in (e.g.) Added Nodes) and modified edges (e.g., redirected edges) (edge) is accurately translated as The specific syntax (e.g., 'myLock.lock()' calls and the correct order of variable assignments).

[0084] Code generation and integration module 60 generation After refactoring the source code (i.e., the refactored source code text), output it. This output can be used to show the suggested changes to the user in the integrated development environment (IDE), or to automatically replace the changes in the project after user confirmation. The corresponding original code segment.

[0085] See attached document Figure 7 The code comment generation steps illustrate the second independent workflow provided by this invention, whose function is mainly executed by the document generation module 70. The goal of this workflow is to utilize the semantic equivalence graph constructed in this invention (…). The rich semantic information provided allows for the generation of high-quality, in-depth code comments or documentation for user-specified code segments.

[0086] This process can be triggered by the user on demand and executed independently of Workflow 1 (Refactoring Process). When the process starts, the document generation module 70 receives the code segment specified by the user. Code snippet The specification method can be to add start and end line numbers to the filename, function signature, or file path.

[0087] The context subgraph extraction and document generation module 70 first needs to obtain the code segment. The corresponding semantic context. It sends a query to the semantic equivalence graph construction and storage module 20 to request the acquisition of... Zhongyu Context subgraph corresponding to code location .

[0088] ; in: It is a context extraction function.

[0089] Similar to context extraction in the refactoring process, this function first, based on... Code location metadata, in A set of initial nodes was located in the middle. .

[0090] Subsequently, the function from Departure, at The algorithm performs a graph traversal. For document generation tasks, this traversal algorithm prioritizes expanding the graph with... Edges that are closely related in function, for example: Inbound / outbound data flow edge ( To determine Data source (e.g., whether it comes from) (Nodes) and data destination (e.g., whether it flows to) node).

[0091] Calling the edge ( ):Sure Other functions called internally.

[0092] Cross-language link edges ( ):Sure Is it a participant in cross-language calls (e.g., an API endpoint called by a frontend)? The nodes and edges visited together form the context subgraph. .

[0093] Semantic augmentation suggestion construction: Get Then, the document generation module 70 constructs a semantically enhanced hint. This is a crucial step in generating high-quality documents because it simultaneously provides the syntactic representation and semantic essence of the code to a large language model, which can be represented as: ; in, yes The graph structure is serialized and described (semantic information). It is a user-specified document style (e.g., 'JavaDoc', 'PythonDocstring', 'LineComment').

[0094] The function will The graph information is converted into text. This text is not merely a list of nodes, but rather a... A structured description of key semantic patterns. For example, the serialized text may contain the following information: Core functions: The core semantic type of the corresponding node.

[0095] Data source: The key input depends on which upstream nodes.

[0096] Data impact: Which downstream nodes does the output flow to?

[0097] And issued as: Does it contain The node indicates that it involves concurrency control.

[0098] Cross-language interaction: Whether it passes An edge connects to another service (e.g., this node). It is ,quilt (from) (Call).

[0099] The document generation module 70 then calls the large language model for document generation provided by the knowledge base and model management module 80. .

[0100] ; in: yes The natural language annotation text output by the model.

[0101] The model was specifically trained to understand this grammar. and semantics Combined inputs. It provides accurate variable names and implementation details, while Provided The role and purpose within the entire system.

[0102] therefore, It can generate comments that go beyond the literal meaning of lines of code. For example, for a database query function, the model can not only explain that the function executes an SQL query, but also that the function is the data query logic of an API endpoint whose input comes from an HTTP request, and that potential SQL injection risks should be noted (based on...). In and information).

[0103] Annotation injection and output: Document generation module 70 received Return Then, its internal annotation injection submodule is called. .

[0104] ; in: It is the final generated source code file containing comments.

[0105] The function first depends on (e.g., 'JavaDoc') and The language type will Format the comment block as conforming to the language and style specifications (e.g., / **…* / or / / … / / ).

[0106] Then, the function inserts the formatted comment block into At the appropriate location (e.g., before the declaration of a function or class), generate the final [image / description]. The file can then be presented to the user or saved back to the code repository.

[0107] To illustrate more specifically how the technical solutions disclosed in this invention, particularly the aforementioned workflow one (analysis and refactoring), works collaboratively within the system architecture of this invention using semantic equivalence graphs, detailed explanations will be provided below through specific embodiments.

[0108] Example 4: Cross-language vulnerability detection (SQL injection) This embodiment details how the system executes the analysis task in Workflow 1 (Analysis and Refactoring) to detect an SQL injection vulnerability that spans the front-end and back-end.

[0109] Implementation Scenarios and SEG Construction: This embodiment assumes a web application project that includes: front end( A main.js file contains a function that retrieves user input from an HTML input field and executes fetch(' / api / user?id='+input) to call the backend API.

[0110] rear end( ): An app.py file (using the Flask framework) contains an API endpoint definition @app.route(' / api / user').

[0111] This endpoint is executed through the following steps: The parameter is obtained by using `user_id=flask.request.args.get('id')`; then the SQL query is constructed by concatenating the strings: `query="SELECT * FROM usersWHERE id='"+user_id+"'"`; finally, the query is executed by `db.execute(query)`.

[0112] In this embodiment, the system performs the following operations: Parsing and Normalization: Module 10 of the source code parsing and normalization module calls the JavaScript parser and the Python parser respectively to process the code. and .

[0113] Semantic Mapping: Source Code Analysis and Normalization Module 10 Normalize key APIs: ; ; ; ; Graph Generation and Linking: Semantic Equivalence Graph Construction and Storage Module 20 .

[0114] Data flow ( Semantic equivalence graph construction and storage module 20 Data flow analysis is performed on the control flow graph to identify taint propagation in the user_id variable. It establishes a path from... (Data source) to (Data dormitory) path The path involved string concatenation operations.

[0115] Cross-language links ( The semantic equivalence graph construction and storage module 20's linking submodule matches the API path / api / user. and A line was established between them side.

[0116] The final Includes a from (Front-end) arrive (Backend), then through (Control Dependency) to (HTTP input), finally via path arrive The complete cross-language call chain for (database execution).

[0117] The user provides the system with natural language intent. Check for all SQL injection vulnerabilities originating from HTTP input to the database.

[0118] Intent resolution and constraint formalization module 30 call The model will Convert to formal logical constraints The core logic of this constraint is: ; in, Include node, Include node, It is the set of nodes corresponding to all data cleansing functions (e.g., parameterized query API).

[0119] Since this is an analytical task, the Intent Resolution and Constraint Formalization module 30 will... The constraints are directly passed to the dual constraint verification module 50.

[0120] The dual constraint verification module 50 received Constraints. Because there are no... (i.e., no intention to refactor), the dual constraint verification module 50 skips the equivalence verification. (Only for the current) (or its related subgraphs) Perform intent constraint verification ( ; Double constraint validation module 50 executes a validation query. ; The query first in Find all and gather; Then, it searches all from arrive Data flow path ; In this embodiment, the query found the path constructed in the foregoing. ; The dual constraint verification module 50 then checks Does it meet the requirements? Existential quantifier conditions in: st ; because The path only contains string concatenation operations and has no nodes. of Type belongs to The set is such that the condition evaluates to False.

[0121] Since there is at least one path This makes the constraint condition false, resulting in the universal quantifier. This cannot be satisfied. Therefore, The function's final return value is False, indicating the intended meaning. If the condition is not met, then a vulnerability exists.

[0122] The dual constraint verification module 50 will display the result of the verification failure. =False and the specific path that led to failure As an output of the analysis report.

[0123] The system presents the report to the user, explicitly pointing out that there is a line in app.py that retrieves data from flask.request.args.get(id)( ) to db.execute(query)( The unpurified data stream path, whose source can be traced back to main.js via the API. The user input was used to locate a complete, cross-language SQL injection vulnerability.

Claims

1. A method for cross-programming language code analysis and refactoring that integrates a large language model, characterized in that, Includes the following steps: S1. Parse the source code of a project containing one or more programming languages, replace the syntax nodes in the source code with normalized abstract semantic concepts using a preset semantic and syntax mapping knowledge base, and establish semantic edges between the normalized abstract semantic concepts according to the dependencies of the source code, and construct a semantic equivalence graph covering the source code. S2. Receive the reconstruction intention in natural language form, and call a preset intent parsing large language model to convert the reconstruction intention into a formal logical constraint that can be executed on the semantic equivalence graph; S3. Extract a context subgraph from the semantic equivalence graph based on the code scope related to the refactoring intent; S4. Construct a reasoning hint that includes the serialized description of the context subgraph and the formal logical constraints, and call a preset graph reasoning big language model to generate a graph modification scheme. S5. Apply the graph modification scheme to the context subgraph to obtain a candidate reconstructed graph; S6. Perform dual constraint verification on the candidate reconstruction graph, the dual constraint verification including: Extract the semantic invariants of the context subgraph and perform equivalence verification based on the semantic invariants on the candidate reconstruction graph; Perform intent constraint verification based on the formal logic constraints on the candidate reconstruction graph; Reconstructed code is generated based on the candidate reconstruction graph only if both the equivalence verification and the intent constraint verification pass.

2. The method for cross-programming language code analysis and reconstruction based on a large language model according to claim 1, characterized in that, In step S1, the semantic edge specifically includes: By analyzing data flow, control dependency, and invocation relationship, data flow edges, control dependency edges, and invocation edges are established between the normalized abstract semantic concepts. Cross-language links can be established between subgraphs belonging to different programming languages ​​by matching API calls or sharing data storage.

3. The method for cross-programming language code analysis and refactoring based on a large language model according to claim 1, characterized in that, In step S2, the formal logical constraints are defined as a set of logical predicates based on the nodes, edges, semantic types, or topological structures of the semantic equivalence graph, used to formally define the target state that the reconstruction intention must satisfy.

4. The method for cross-programming language code analysis and refactoring based on a large language model according to claim 3, characterized in that, When the refactoring intent is thread-safe refactoring, the logical predicate is defined as: The rules stipulate that there is no pair of concurrent access operations that access the same shared resource, at least one of which is a write operation, and the pair of access operations are not protected by the same mutex lock.

5. The method for cross-programming language code analysis and reconstruction based on a large language model according to claim 1, characterized in that, In step S4, the step of constructing the reasoning hint includes: The context subgraph is serialized into a graph-structured text. The graph structure text, the formal logical constraints, and the reconstruction intent in the natural language form are combined to form the reasoning hint.

6. The method for cross-programming language code analysis and refactoring based on a large language model according to claim 1, characterized in that, In step S4, the graph modification scheme is a data structure containing atomic graph operation instructions, which at least include: The set of new nodes to be added, the set of new edges to be added, the set of nodes to be deleted, and the set of edges to be deleted.

7. The method for cross-programming language code analysis and refactoring based on a large language model according to claim 1, characterized in that, In step S6, the step of extracting the semantic invariants of the context subgraph includes: By performing symbolic execution or data flow analysis on the context subgraph, the functional relationship mapping or core data flow path topology between the input and output nodes of the context subgraph is extracted as the semantic invariant.

8. The method for cross-programming language code analysis and refactoring based on a large language model according to claim 1, characterized in that, In step S6, when the equivalence verification or the intent constraint verification fails, the cross-programming language code analysis and refactoring method further includes: Prevent the candidate reconstruction graph from entering the code generation stage; A feedback signal indicating verification failure is sent to the step used to construct the inference hint, initiating a correction loop.

9. The method for cross-programming language code analysis and refactoring based on a large language model according to claim 1, characterized in that, In step S6, the step of generating the refactored code includes: Determine a target language; The reverse mapping of the semantic and grammar mapping knowledge base and the grammar template library of the target language are utilized; Traverse the candidate reconstruction graph and translate the normalized abstract semantic concept nodes and semantic edges of the candidate reconstruction graph back into the specific source code text of the target language.

10. The method for cross-programming language code analysis and refactoring based on a large language model according to claim 1, characterized in that, The cross-programming language code analysis and refactoring method also includes a workflow for generating code comments, the workflow comprising: Receive a request to generate comments for a target code segment; Extract the context subgraph corresponding to the target code segment from the semantic equivalence graph. The context subgraph contains the data flow direction, cross-language caller, or path security attributes of the target code segment. Construct a semantically enhanced hint that includes the syntactic information of the target code segment and the serialized semantic information of the context subgraph; The document is invoked to generate a large language model to generate code comments that reveal the contextual role or potential risks of the target code segment; Inject the code comments into the target code segment according to the specified style.