A code generation method and system
Patent Information
- Application Number
- CN202611339862.6
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-08-31
- Publication Date
- 2026-10-16
AI Technical Summary
[0003]然而,上述方法在处理结构复杂的大型工程时,难以捕捉到深层次的跨文件、跨模块的深层次逻辑关系系,造成输入的上下文信息与当前开发意图的契合度不足,生成代码的准确率低;且缺乏对代码信息价值的有效评估与分级,未经筛选的原始代码全量输入会显著造成计算资源与Token的过度消耗,且易引发推理偏差
Smart Images

Figure CN122924748A_ABST
Abstract
Description
Technical Field
[0001] This manual relates to the field of automated code generation, and in particular to a code generation method and system. Background Technology
[0002] In current software engineering development, code auto-completion and generation technologies based on large language models have been widely applied. When developers write code in an Integrated Development Environment (IDE), the system extracts context information by obtaining text fragments near the current editing position or by using simple retrieval algorithms (such as keyword matching and text similarity retrieval) from the current file. This context information is then input into a pre-trained code generation model. The code generation model infers based on the received context information, predicts and outputs possible subsequent code logic, thereby helping developers improve coding efficiency.
[0003] However, when dealing with large-scale projects with complex structures, the above methods struggle to capture deep-seated logical relationships across files and modules, resulting in insufficient alignment between the input context information and the current development intent, leading to low accuracy in generated code. Furthermore, the lack of effective evaluation and grading of the value of code information means that inputting the entire amount of unfiltered raw code will significantly lead to excessive consumption of computing resources and tokens, and is prone to inference bias.
[0004] Therefore, it is desirable to provide a code generation method and system that can break through the limitations of a single file, reduce interference from irrelevant code and semantic loss across files, and improve the semantic relevance and logical consistency of the code generation context in complex engineering scenarios. Summary of the Invention
[0005] One embodiment of this specification provides a code generation method, the method comprising: constructing an engineering structure diagram model of a target project; obtaining the current editing position based on a code generation request, and determining a candidate code set based on the current editing position and the engineering structure diagram model; determining a comprehensive weight score for each candidate code unit in the candidate code set, and determining a target context code from the candidate code set based on the comprehensive weight score; and performing reasoning based on the target context code to determine a code result.
[0006] One embodiment of this specification provides a code generation system, the system comprising: a model building module configured to build an engineering structure diagram model of a target project; a first determining module configured to obtain the current editing position based on a code generation request, and determine a candidate code set based on the current editing position and the engineering structure diagram model; a second determining module configured to determine a comprehensive weight score for each candidate code unit in the candidate code set, and determine a target context code from the candidate code set based on the comprehensive weight score; and an inference module configured to perform inference based on the target context code to determine the code result. Attached Figure Description
[0007] This specification will be further described by way of exemplary embodiments, which will be described in detail with reference to the accompanying drawings. These embodiments are not limiting; in these embodiments, the same reference numerals denote the same structures, wherein:
[0008] Figure 1 This is an exemplary block diagram of a code generation system according to some embodiments of this specification; Figure 2 This is an exemplary flowchart of a code generation method shown in some implementations of this specification; Figure 3 This is an exemplary schematic diagram illustrating the determination of a comprehensive weighted score according to some embodiments of this specification; Figure 4 This is an exemplary flowchart illustrating the updating and modification of the weights of the activity dimension according to some implementations of this specification; Figure 5 This is an exemplary schematic diagram illustrating the updating target context code according to some embodiments of this specification. Detailed Implementation
[0009] To more clearly illustrate the technical solutions of the embodiments in this specification, the accompanying drawings used in the description of the embodiments will be briefly introduced below. Obviously, the drawings described below are merely some examples or embodiments of this specification. For those skilled in the art, these drawings can be applied to other similar scenarios without creative effort. Unless obvious from the context or otherwise specified, the same reference numerals in the drawings represent the same structures or operations.
[0010] It should be understood that the terms “system,” “device,” “unit,” and / or “module” used herein are one way to distinguish different components, elements, parts, sections, or assemblies at different levels. However, if other terms can achieve the same purpose, they may be replaced by other expressions.
[0011] As indicated in this specification and claims, unless the context clearly indicates otherwise, the words "a," "an," "an," and / or "the" do not specifically refer to the singular and may also include the plural. Generally speaking, the terms "comprising" and "including" only indicate the inclusion of expressly identified steps and elements, which do not constitute an exclusive list, and the method or apparatus may also include other steps or elements.
[0012] Flowcharts are used in this specification to illustrate the operations performed by the system according to embodiments of this specification. It should be understood that the preceding or following operations are not necessarily performed in exact order. Instead, the steps can be processed in reverse order or simultaneously. Furthermore, other operations can be added to these processes, or one or more steps can be removed from them.
[0013] Figure 1 This is an exemplary block diagram of a code generation system according to some embodiments of this specification. For example... Figure 1 As shown, the code generation system 100 may include a model building module 110, a first determining module 120, a second determining module 130, and an inference module 140. In some embodiments, the model building module 110, the first determining module 120, the second determining module 130, and the inference module 140 may be integrated on a processor. The processor may include one or more combinations of a microcontroller (MCU), an embedded processor, a graphics processing unit (GPU), etc.
[0014] In some embodiments, the model building module 110 can be configured to build an engineering structure diagram model of the target project.
[0015] In some embodiments, the first determining module 120 may be configured to: obtain the current editing position based on the code generation request, and determine a set of candidate codes based on the current editing position and the engineering structure diagram model.
[0016] In some embodiments, the second determining module 130 may be configured to: determine a comprehensive weight score for each candidate code unit in the candidate code set, and determine a target context code from the candidate code set based on the comprehensive weight score. The candidate code set includes multiple candidate code units.
[0017] In some embodiments, the second determining module 130 may be further configured to: perform weighted fusion of at least two dimensions on each candidate code unit in the candidate code set to determine the comprehensive weight score of the candidate code unit; wherein the dimensions include at least two of the following: a call relationship dimension, the score corresponding to the call relationship dimension being determined based on the call in-degree and call out-degree of the candidate code unit; a modification activity dimension, the score corresponding to the modification activity dimension being determined based on the submission frequency and time decay factor of the candidate code unit; a structural distance dimension, the score corresponding to the structural distance dimension being determined based on the path distance between the current editing position and the candidate code unit in the engineering structure diagram model; a module importance dimension, the score corresponding to the module importance dimension being determined based on the core module identifier or business priority; and a context relevance dimension, the score corresponding to the context relevance dimension being determined based on the semantic matching degree between the current editing content and the candidate code set.
[0018] In some embodiments, the second determining module 130 may be further configured to: determine the upstream node of the changed node and the target code unit pointed to by the changed node based on the engineering structure diagram model and the historical engineering structure diagram model; determine the topology injection energy of the target code unit based on the activity score of the upstream node; and update the score corresponding to the modification activity dimension of the target code unit based on the topology injection energy.
[0019] In some embodiments, the second determining module 130 may be further configured to: sort the plurality of candidate code units in descending order based on the comprehensive weight score of the plurality of candidate code units, select at least one first code unit that meets the preset conditions; and preprocess the at least one first code unit to obtain at least one second code unit, and update the target context code.
[0020] In some embodiments, the second determining module 130 may be further configured to: extract the interface definition in the at least one first code unit and hide the implementation logic; merge similar code fragments in the at least one first code unit; and generate a structural summary of the at least one first code unit based on an abstract syntax tree.
[0021] In some embodiments, the inference module 140 may be configured to: perform inference based on the target context code to determine the code result.
[0022] For further explanation of the above content, please refer to Figures 2-5 And related content.
[0023] Figure 2 This is an exemplary flowchart illustrating a code generation method according to some implementations of this specification. For example... Figure 2 As shown, process 200 is an exemplary process of code generation method. Process 200 includes steps 210-240.
[0024] Step 210: Construct the engineering structure diagram model of the target project.
[0025] A target project refers to the codebase of a software project that needs to be developed or maintained. For example, a target project could be the codebase for an e-commerce system backend project, a client application project, or a microservice project. A target project can consist of multiple code units. A code unit is the smallest logical module or physical unit that constitutes the project. The types of code units can include, but are not limited to, files, classes, methods, or functions.
[0026] An engineering structure diagram model is a graph structure representation model used to characterize multiple code units of a target project and their relationships.
[0027] In some embodiments, the engineering structure diagram model includes graph nodes and associated edges. Graph nodes can be code units, and associated edges can be the relationships between code units. Relationships refer to the logical relationships between code units, such as calls, dependencies, or hierarchical relationships. Associated edges are directed edges, with arrows pointing to the called, depended upon, or subordinate code unit.
[0028] As an example only, for a Java project, graph nodes can correspond to a three-tier structure of files, classes, and methods, where file nodes are the top-level nodes, class nodes are attached to their respective file nodes, and method nodes are attached to their respective class nodes. For a Python project, graph nodes can correspond to a three-tier structure of module files, classes, and functions. Graph nodes of the same code unit at different granularities are connected by belonging-related edges.
[0029] In some embodiments, the model building module 110 can parse the source files in the target project, extract the files, classes, methods or functions in the source files as graph nodes, build associated edges between nodes with relationships, and build a directed graph based on the graph nodes and associated edges as the project structure graph model.
[0030] In some embodiments, the model building module 110 can be configured to: extract the association relationships of code units corresponding to the target project, including file dependency relationships, function call relationships, module reference relationships, and directory hierarchy relationships; use code units as graph nodes, and determine the association edges between graph nodes based on file dependency relationships, function call relationships, module reference relationships, and directory hierarchy relationships; and build an engineering structure graph model of the target project based on the graph nodes and association edges.
[0031] File dependency refers to the dependency relationship formed between different files based on references, imports, or inclusions when the code unit is a file.
[0032] Function call relationships refer to the logical relationships between different functions or methods when the code unit is a function or method.
[0033] Module reference relationships refer to the reference relationships formed between different classes based on usage, dependency, or ownership when the code unit is a class (such as a layer, business component, class library, etc.). For example, if the Service layer references the DAO layer, then in the project structure diagram model, the Service layer points to the DAO layer.
[0034] Directory hierarchy refers to the hierarchical and organizational relationship of a code unit within the project directory structure (such as a disk). For example, a code unit named src / main / java / com / utils belongs to the utility directory.
[0035] In some embodiments, the model building module 110 can use static code analysis tools to parse the source files of the target project, generate an abstract syntax tree (AST), traverse import statements or include statements in the AST, extract file dependencies, identify function call nodes and extract function call relationships, analyze the package name, namespace, or component ownership information of the source files to obtain module reference relationships, and read the system metadata of code units (such as files) to obtain directory hierarchy relationships. This specification does not impose any special limitations on the static code analysis tools used in the embodiments; any operation familiar to those skilled in the art can be employed.
[0036] In some embodiments, the model building module 110 can map each code unit to a graph node; and establish associated edges between the graph nodes corresponding to the code units according to the file dependencies, function call relationships, module reference relationships and directory hierarchy relationships between the code units.
[0037] Some embodiments in this specification, by extracting multi-dimensional relationships between code units, can reconstruct the complex topological structure of the target project. The fusion of multi-dimensional relationships facilitates subsequent context filtering and global consistency in code generation. Simultaneously, the structured graph model accurately reflects the logical tightness between code units. For example, directory hierarchy reflects the architectural design, and function call relationships reflect the runtime logic. The fusion of this information makes subsequent context filtering more accurate, ensuring global consistency in code generation.
[0038] Step 220: Based on the code generation request, obtain the current editing position, and determine the candidate code set based on the current editing position and the project structure diagram model.
[0039] A code generation request is a request that triggers code generation or completion. Users initiate code generation requests to the code generation system via keyboard shortcuts, comments, or automatic triggering mechanisms.
[0040] The current editing position refers to the editing point corresponding to the code to be generated or completed during the code editing process. For example, the current editing position can be the cursor position in the integrated development environment (IDE), the insertion position inside a function, or the area to be completed in a class definition.
[0041] The candidate code set refers to the collection of code units identified from the engineering structure diagram model that are associated with the current editing position. The candidate code set includes multiple candidate code units. A candidate code unit refers to any code unit within the candidate code set.
[0042] In some embodiments, the first determining module 120 can read the current editing position based on the code generation request through the integrated development environment plugin corresponding to the code generation request; locate the graph node corresponding to the current editing position in the engineering structure diagram model; traverse outwards along the associated edges at a depth of N using the breadth-first search (BFS) algorithm; collect the code units corresponding to all nodes traversed on the traversal path; deduplicate and summarize the above code units, and output them as a candidate code set. The value of N can be set according to requirements or experience.
[0043] Step 230: Determine the comprehensive weight score of each candidate code unit in the candidate code set, and determine the target context code from the candidate code set based on the comprehensive weight score.
[0044] The overall weight score is a comprehensive evaluation score used to quantify the relevance of candidate code units to the code generation request. The higher the overall weight score, the higher the relevance of the candidate code unit to the code generation request.
[0045] In some embodiments, for each candidate code unit, the second determining module can extract multiple feature values of the candidate code unit in the engineering structure diagram model; assign a corresponding weight coefficient to each feature value, the weight coefficient representing the degree of contribution of the feature value to the code generation relevance; perform a weighted summation on multiple feature values to obtain an initial weight score; normalize the initial weight score through a normalization algorithm; and output a comprehensive weight score between 0 and 1.
[0046] In some implementations, features include the path steps between the candidate code unit and the current editing position, the number of times the candidate code unit is referenced, and the number of file modifications to the candidate code unit. Feature values can be determined using preset algorithms. For example, the path steps can be determined by calling a graph algorithm; the number of references can be obtained by querying the symbol index; and the number of file modifications can be obtained from the Git cache or API. The weight corresponding to each feature value can be set according to requirements or experience.
[0047] The target context code refers to the collection of code units selected from the candidate code set to support subsequent code reasoning.
[0048] In some embodiments, the second determining module 130 may select candidate code units one by one based on a comprehensive weight score from high to low; in response to the total character length (token count) of at least one selected candidate code unit reaching a first preset threshold, the selected candidate code unit is output as the target context code. In other embodiments, the second determining module 130 may also select candidate code units one by one based on a comprehensive weight score from high to low; in response to the number of selected candidate code units being greater than or equal to a second preset threshold, the selected candidate code units are output as the target context code. The first preset threshold and the second preset threshold may be system default values, empirical values, manually preset values, or any combination thereof, and can be set according to actual needs; this specification does not impose any restrictions on this.
[0049] In some embodiments, the second determining module 130 may further: perform a weighted fusion of at least two dimensions on each candidate code unit in the candidate code set to determine the comprehensive weight score of the candidate code unit. For more details, please refer to... Figure 3 And its related descriptions.
[0050] In some embodiments, the second determining module 130 may further: sort the multiple candidate code units in descending order based on the comprehensive weight score of the multiple candidate code units, select at least one first code unit that meets preset conditions; preprocess the at least one first code unit to obtain at least one second code unit, and update the target context code. For more details, please refer to... Figure 5 And its related descriptions.
[0051] Step 240: Perform reasoning based on the target context code to determine the code result.
[0052] The code result refers to the code snippet that is finally output by the code generation system.
[0053] In some embodiments, the inference module 140 may: encapsulate the target context code, the current code content, and the code generation request into a prompt; input the prompt into a pre-trained Large Language Model (LLM), which performs autoregressive prediction to generate the code content; and perform text processing on the code content to obtain the code result. The Large Language Model can be a Transformer-based decoder model. Text processing may include syntax formatting, indentation correction, etc. The current code content refers to the code unit corresponding to the current editing position.
[0054] In some embodiments, the inference module 140 may also determine the code result in other ways. For example, the inference module 140 may construct a feature vector based on the target context code, query a preset code table, and take the reference code result corresponding to the reference vector with the highest similarity to the feature vector as the final code result. The preset code table includes reference vectors and corresponding reference code results. The reference vectors may be constructed based on historical context codes, and the reference code results are the historical code results corresponding to the historical context codes.
[0055] Some embodiments in this specification, by constructing an engineering structure diagram model, can be extended in association, thereby breaking through the limitations of a single file; by obtaining deep dependencies across files, comprehensive weight scoring, and contextual reasoning, it can effectively reduce interference from irrelevant code and semantic loss across files, reduce reasoning costs, and thus improve the consistency between generated code and engineering specifications and business logic.
[0056] Figure 3 This is an exemplary schematic diagram illustrating the determination of a comprehensive weighted score according to some embodiments of this specification.
[0057] In some embodiments, such as Figure 3 As shown, the second determining module 130 can: perform weighted fusion of at least two dimensions on each candidate code unit in the candidate code set to determine the comprehensive weight score of the candidate code unit. The dimensions include at least two of the following: call relationship dimension, modification activity dimension, structural distance dimension, module importance dimension, and context relevance dimension.
[0058] The call relationship dimension is used to measure the frequency and pivotal role of candidate code units in the code generation system. In some embodiments, the score corresponding to the call relationship dimension is determined based on the in-degree and out-degree of the candidate code unit.
[0059] In-call degree refers to the number of calls to a candidate code unit in a call relationship, which is used to characterize the degree to which a candidate code unit is called by other code units.
[0060] Call out-degree refers to the number of calls made by a candidate code unit in a call relationship, which is used to characterize the extent to which a candidate code unit calls other code units.
[0061] In some embodiments, for a candidate code unit, the second determining module 130 can statistically analyze the in-degree and out-degree of the candidate code unit in the engineering structure diagram model; based on the in-degree and out-degree, a score for the calling relationship dimension corresponding to the candidate code unit is determined by a preset algorithm. The preset algorithm can be expressed as formula (1), as shown below: W1 = a × logA + b × logB (1)
[0062] Where W1 represents the score corresponding to the call relationship dimension; A and B represent the in-degree and out-degree of the call; a and b are coefficients greater than 0, and a+b=1. a and b can be set based on experience. For example, for business development projects, a=0.6 and b=0.4 can be set, and for basic tool projects, a=0.4 and b=0.6 can be set.
[0063] Modification activity dimension refers to an evaluation dimension used to reflect the degree of modification activity of candidate code units in historical data.
[0064] In some embodiments, the score corresponding to the activity dimension is determined based on the submission frequency of candidate code units and the time decay factor.
[0065] Submission frequency refers to the number of times a candidate code unit is submitted within a preset time period (such as the past week to the present).
[0066] The time decay factor is a coefficient that indicates how much the impact of a candidate code unit's code submission diminishes over time. The time decay factor can be a system default value, an empirical value, a manually preset value, or any combination thereof. It can be set according to actual needs, and this manual does not impose any restrictions on it.
[0067] In some embodiments, the second determining module 130 can obtain the historical submission records of candidate code units within a preset time period and determine the average time difference between the historical submission time and the current time; based on the average time difference and the time decay factor, a preset algorithm is used to determine the score corresponding to the modification activity dimension. The preset algorithm can be expressed as formula (2), which is shown below: (2)
[0068] in, This indicates a modification to the score corresponding to the activity level dimension; Indicates the candidate code unit in the preset time period. The time difference between the two submissions Take 1~ , The submission frequency of candidate code units within a preset time period; This represents the time decay factor.
[0069] In some embodiments, the second determining module 130 may, based on the engineering structure diagram model and the historical engineering structure diagram model, determine the upstream node of the changed node and the target code unit pointed to by the changed node; determine the topology injection energy of the target code unit based on the activity score of the upstream node; and update the score corresponding to the modification activity dimension of the target code unit based on the topology injection energy. For further details, see [link to documentation]. Figure 4 And its related descriptions.
[0070] The structural distance dimension refers to the dimension that measures the distance between the current editing position and the candidate code unit in the graph model of the engineering structure diagram. In some embodiments, the score corresponding to the structural distance dimension is determined based on the path distance between the current editing position and the candidate code unit in the engineering structure diagram model.
[0071] Path distance can be represented as the number of associated edges contained in the shortest path between the current editing position and the graph node corresponding to the candidate code unit in the engineering structure diagram model.
[0072] In some embodiments, the processor uses a graph search algorithm to determine the shortest path distance d between the current editing position node and the candidate code unit node in the engineering structure graph model, and then calculates the score corresponding to the structural distance dimension according to a preset algorithm. The preset algorithm can be that the score corresponding to the structural distance dimension is 1 / (d+1).
[0073] The module importance dimension reflects the importance of candidate code units in the project. For example, if a candidate code unit has a core module identifier or high business priority, it will have a higher score on the module importance dimension.
[0074] In some embodiments, the score corresponding to the module importance dimension is determined based on the core module identifier or business priority.
[0075] Core module identifiers are information used to identify core business modules, key directories, or important components in a target project. Core module identifiers can be manually or automatically assigned. Business priority reflects the importance level of a module. The business priorities of different modules can be preset according to requirements or configuration.
[0076] In some embodiments, the second determining module 130 can extract the path string corresponding to the candidate code unit from the engineering structure diagram model, perform string matching between the path string and the path prefix in the preset core module table, determine the business priority corresponding to the path prefix whose similarity to the path string is greater than a preset threshold, and determine the score corresponding to the module importance dimension through a preset algorithm. The preset algorithm can be expressed as formula (3), as shown below: W3=(L max -L1+1)÷L max (3)
[0077] Where W3 represents the score corresponding to the module importance dimension; L max L1 represents the maximum value among the business priorities matched by the string; L1 represents the business priority of the module where the current editing position is located, which can be obtained by searching the preset core module table.
[0078] The context relevance dimension reflects the degree of semantic consistency or content matching between the currently edited content and the candidate code unit.
[0079] In some embodiments, the score corresponding to the context relevance dimension is determined based on the degree of semantic matching between the currently edited content and the candidate code set.
[0080] The currently edited content refers to the content of the code cell corresponding to the current editing position. The currently edited content can be code or a comment.
[0081] Semantic matching degree refers to the degree of semantic similarity between two pieces of code or text. Semantic matching degree can be related to the semantic similarity between the currently edited content and the candidate code unit. Semantic similarity is negatively correlated with the vector distance between the semantic vectors corresponding to the currently edited content and the candidate code unit. The vector distance can be cosine distance.
[0082] In some embodiments, the second determining module 130 may use a vectorization model (such as BERT, CodeBERT, etc.) to convert the currently edited content into a first semantic vector and the candidate code unit into a second semantic vector; the inverse of the cosine distance between the first semantic vector and the second semantic vector is used as the similarity, and the similarity is used as the score corresponding to the context relevance dimension.
[0083] In some embodiments, for each candidate code unit, the second determining module 130 can use the weighted sum of the scores of at least two dimensions corresponding to the candidate code unit as the initial weight score, normalize the initial weight scores corresponding to multiple candidate code units, and output values between 0 and 1 as the comprehensive weight score of each candidate code unit. The weight corresponding to each dimension can be set according to needs or experience.
[0084] This specification presents several embodiments that employ a multi-dimensional scoring weighted fusion to form a unified scoring mechanism, constructing a comprehensive code evaluation system. Specifically, the call relationship dimension filters out high-frequency utility classes, the modification activity dimension identifies ongoing business hotspots, the structural distance dimension ensures logical coherence, the module importance dimension ensures core logic is not lost, and the context relevance dimension achieves precise content alignment. This multi-dimensional fusion avoids the limitations of a single indicator and dynamically adjusts the comprehensive weight score of candidate code units based on the developer's actual development context (e.g., refactoring core logic or writing auxiliary tools), significantly enhancing the applicability and accuracy of code generation.
[0085] In some embodiments, after the code generation process 200 generates code results, users (such as developers) may provide feedback on the code results. Based on the user's feedback, the weights of different dimensions can be adjusted in reverse, so that the code results subsequently generated by the code generation process 200 better meet the user's needs.
[0086] In some embodiments, the second determining module 130 is configured to: receive adoption feedback information of the code result; and adjust the weights corresponding to different dimensions based on the adoption feedback information.
[0087] Acceptance feedback information refers to information reflecting the developer's feedback on the code results, such as acceptance, modification, or deletion. In some embodiments, the second determining module 130 can obtain acceptance feedback information through a user terminal. The user terminal may include a mobile phone, laptop computer, desktop computer, tablet computer, etc.
[0088] In some embodiments, the second determining module 130 can extract at least two dimensions and their corresponding weights involved in generating the current code result; update the weights corresponding to each dimension using a gradient descent algorithm or a weight penalty mechanism, and save the updated weights for the next code reasoning. For example, if the feedback information is "accept", the weight is increased accordingly; if the feedback information is "modify" or "delete", the weight is decreased accordingly.
[0089] In some embodiments, the weights corresponding to different dimensions can also be adjusted in other ways. For example, the second determining module 130 can map different adoption feedback information to different adjustment coefficients based on a preset rule table, and multiply the weights corresponding to each dimension by the adjustment coefficients to obtain the adjusted weights. The preset rule table includes the type of adoption feedback information (such as acceptance, modification, deletion, etc.) and the corresponding adjustment coefficients. The preset rule table can be set based on experience.
[0090] Some embodiments in this specification form a closed-loop optimization mechanism by receiving adoption feedback information and updating the weights of each dimension, making subsequent code generation more in line with developer habits and project specifications, and improving the usability and matching degree of the code results.
[0091] Figure 4 This is an exemplary flowchart illustrating the updating and modification of the weights of the activity dimension according to some implementations of this specification. For example... Figure 4 As shown, process 400 is an exemplary process for updating and modifying the weights of the activity dimension. Process 400 includes steps 410-430.
[0092] Step 410: Based on the engineering structure diagram model and the historical engineering structure diagram model, determine the upstream node of the changed node and the changed target code unit.
[0093] The historical project structure diagram model is the project structure diagram model of the most recent historical moment in the history record. The historical project structure diagram model can represent the call relationships and dependencies in the previous version of the code.
[0094] A change node is a graph node in the engineering structure model that has changed compared to the historical engineering structure model. Changes include changes in file dependencies, function call relationships, module reference relationships, and directory hierarchy relationships. For example, if the call target of a function node is replaced, that function node can be considered a change node.
[0095] An upstream node is a graph node that points to a change node.
[0096] The target code unit refers to the code unit corresponding to the graph node pointed to by the change node.
[0097] In some embodiments, the second determining module 130 can align the graph nodes and associated edges in the engineering structure graph model and the historical engineering structure graph model; identify the graph nodes that have changed as change nodes; for each change node, extract the graph node pointed to by the change node as the target code unit, and determine the graph node pointing to the change node as the upstream node. For example, if the logical chain "start function → function A → function C..." consisting of multiple graph nodes and multiple associated edges in the historical engineering structure graph model is changed to "start function → function B → function C..." in the engineering structure graph model, then the change node is the graph node where function B is located, the upstream node is the start function, and the target code unit is function B.
[0098] In some embodiments, in response to a change node being a graph node whose function call relationship has changed, the second determining module 130 may determine the source node based on the logical chain in which the change node is located; in response to the call connection between the source node and the third code unit being broken within a preset time window and a connection being established between the source node and the fourth code unit, the source node is determined as the upstream node; and the fourth code unit pointed to by the upstream node is determined as the target code unit.
[0099] The preset time window can be a system default value, an empirical value, a manually preset value, or any combination thereof, and can be set according to actual needs. This manual does not impose any restrictions on this. For example, the preset time window can be up to the seven days most recent from the current time.
[0100] A source node is the starting graph node that has changed within the logical chain containing the changing node.
[0101] The third code unit refers to the old code unit that had a call connection with the source node before the function call relationship changed.
[0102] A call connection refers to a link between a source node and another code unit based on function calls, method calls, or procedure calls. A call connection being broken means that the call relationship to the code unit has been deleted after a change in the function call relationship. A call connection being established means that a call to the code unit has been added after a change in the function call relationship.
[0103] The fourth code unit refers to a new code unit that has a call connection with the source node after the call relationship changes.
[0104] In some embodiments, the second determining module 130 may: extract the abstract syntax tree (AST) call table of the source node from the historical engineering structure diagram model and the engineering structure diagram model; in response to the following: if there is an associated edge in the historical engineering structure diagram model pointing to the third code unit, but the associated edge does not exist in the engineering structure diagram model, and an associated edge in the engineering structure diagram model pointing to the fourth code unit appears, then it is determined that the call connection between the source node and the third code unit is broken, and a connection is established between the source node and the fourth code unit, and the source node is determined as the upstream node, and the fourth code unit is determined as the target code unit.
[0105] Some embodiments in this specification identify the disconnection of old calls and the establishment of new calls by comparing the old and new versions of the code, and locate the upstream node and target code unit along the current valid call edge, thereby reducing interference from outdated relationships and improving the accuracy of change path identification.
[0106] Step 420: Determine the topology injection energy of the target code unit based on the activity score of the upstream node.
[0107] The activity score is a score used to quantify the frequency of changes to the corresponding code unit of the upstream node. In some embodiments, the second determining module 130 can... Figure 3 The method related to formula (2) determines the score corresponding to the modification activity dimension of the code unit of the upstream node, and uses the score as the activity score of the upstream node.
[0108] Topology-injected energy refers to the active quantification value that is transmitted from upstream nodes to target code units along the relationships in the engineering structure diagram model.
[0109] In some embodiments, the second determining module 130 may: determine the topology injection energy of the target code unit by querying a preset mapping table based on the activity score of the upstream node. The preset mapping table includes the mapping relationship between the activity score of the upstream node and the topology injection energy. The preset mapping table can be set based on experience.
[0110] In some embodiments, the second determining module 130 is further configured to: determine the reference strength weight based on the association between the upstream node and the target code unit; determine the weighted activity score based on the reference strength weight and the activity score of the upstream node; and determine the topology injection energy based on the weighted activity score.
[0111] Reference strength weight is a weighting coefficient used to characterize the strength of the influence of different associations on activity transmission.
[0112] In some embodiments, the second determining module 130 can statically analyze the engineering structure diagram model to identify the association edge types between target code units as the association relationships between upstream nodes and target code units; based on the association relationships, it can search a preset weight table to determine the reference strength weight. The preset weight table includes the mapping relationship between association relationships and reference strength weights. The preset weight table can be preset based on experience or requirements.
[0113] The weighted activity score refers to the activity score of an upstream node under the influence of the relationship between the upstream node and the target code unit.
[0114] In some embodiments, the second determining module 130 may use the node activity score of the upstream node and the statistical value of the reference strength weight (such as the product) as the weighted activity score of the upstream node.
[0115] In some embodiments, the second determining module 130 can determine the weighted activity scores of all upstream nodes pointing to the target unit; and determine the statistical values (such as summation results) of all weighted activity scores as the topology injection energy of the target code unit.
[0116] In some embodiments of this specification, different reference strength weights are assigned based on the association between upstream nodes and target code units, and the topology injection energy is determined according to the weighted activity score, so that strongly coupled nodes can transmit a higher amount of influence, thereby improving the accuracy of code association recommendations.
[0117] Step 430: Based on the topology injection energy, update the score corresponding to the modification activity dimension of the target code unit.
[0118] In some embodiments, the second determining module 130 can perform a weighted summation of the score of the modification activity dimension corresponding to the target code unit and the topology injection energy. The weights of the weighted summation can be preset based on experience. In response to the result of the weighted summation being less than or equal to the truncation upper limit, the score of the modification activity dimension of the target code unit is updated to the above-mentioned weighted summation result. In response to the result of the weighted summation being greater than the truncation upper limit, the weight of the modification activity dimension of the target code unit is updated to the truncation upper limit. The truncation upper limit can be a system default value, an empirical value, a manually preset value, or any combination thereof, and can be set according to actual needs. This specification does not impose any restrictions on this.
[0119] In some embodiments, the second determining module 130 may further: in response to the submission frequency of the target code unit being lower than a preset frequency threshold, determine the topology injection energy as an initial score of the modification activity of the target code unit; and update the score of the modification activity dimension of the target code unit based on the initial score.
[0120] The preset frequency threshold can be a system default value, an empirical value, a manually preset value, or any combination thereof, and can be set according to actual needs. This manual does not impose any restrictions on this. Different types of code units can correspond to different preset frequency thresholds. For example, functions, classes, and files can each correspond to different preset frequency thresholds.
[0121] Modifying the initial activity score refers to assigning a score value to a target code unit when its original commit activity level is low.
[0122] In some embodiments, the second determining module 130 can extract the type of the target code unit from the metadata, look up a preset frequency table to determine a preset frequency threshold for that type, and in response to the target code unit's commit frequency being lower than the preset frequency threshold, determine the topology injection energy as the initial score for the target code unit's modification activity; update the score of the target code unit's modification activity dimension to the initial score. The preset frequency table includes different code unit types and corresponding preset frequency thresholds. The preset frequency table can be set based on experience or requirements.
[0123] Some embodiments in this specification improve the completeness of generated content by writing topology injection energy into the initial score and updating the activity dimension under low submission frequency conditions, thereby enabling recently called code to obtain effective weights.
[0124] In some embodiments of this specification, the activity scores of upstream nodes and topology injection energy are used to enable the underlying units that are relied upon by frequently modified code to increase their activity in advance and obtain high weights, thereby reducing the lag in activity scores and providing more accurate underlying references during code generation, thus improving the accuracy of code generation references.
[0125] Figure 5 This is an exemplary schematic diagram illustrating the updating target context code according to some embodiments of this specification. In some embodiments, such as Figure 5 As shown, the second determining module 130 is further configured to: sort the multiple candidate code units in descending order based on the comprehensive weight score of the multiple candidate code units, select at least one first code unit that meets the preset conditions; and preprocess the at least one first code unit to obtain at least one second code unit, and update the target context code.
[0126] The first code unit refers to the candidate code unit that meets the preset conditions among multiple candidate code units.
[0127] In some embodiments, the preset condition can be to select the top K candidate code units in the descending sorted results. The value of K can be set empirically, for example, K is 5. The second determining module 130 can select the top K candidate code units in the descending sorted results as the first code unit.
[0128] In other embodiments, the preset conditions may further include candidate code units whose comprehensive weight score in the descending sort results is greater than a preset weight threshold. The preset weight threshold can be set empirically. The second determining module 130 may select the candidate code unit whose comprehensive weight score in the descending sort results is greater than the preset weight threshold as the first code unit.
[0129] Preprocessing refers to the optimization operations performed on the first code unit. For example, preprocessing can include structured trimming and compression, thereby reducing the size of the code while retaining key information.
[0130] The second code unit refers to the first code unit after preprocessing.
[0131] In some embodiments, the second determining module 130 preprocesses at least one first code unit (e.g., structured trimming and compression) by: parsing the first code unit into an abstract syntax tree (AST) using a static analysis tool; traversing the nodes in the abstract syntax tree, deleting function body nodes (BlockStmt) while retaining function names, parameters, and return values to hide the specific implementation logic; performing redundancy elimination on the retained content, such as using an identification algorithm (e.g., a hash fingerprinting algorithm) to identify and delete identical retained content; calculating the number of tokens in the abstract syntax tree after the above processing; and, in response to the number of tokens being greater than a preset threshold, recursively deleting non-core comments and private member fields in the retained content until the number of tokens is less than or equal to the preset threshold, and outputting the second code unit. The preset threshold refers to the maximum context length limit for a single processing operation of the code generation system. The preset threshold can be a system default value, an empirical value, a manually preset value, or any combination thereof, and can be set according to actual needs. This specification does not impose any restrictions on this, such as 4096 tokens.
[0132] In some embodiments, preprocessing includes at least one of the following operations: extracting interface definitions from at least one first code unit and hiding implementation logic; merging similar code snippets from at least one first code unit; and generating a structural summary of at least one first code unit based on an abstract syntax tree.
[0133] An interface definition refers to the information used to characterize how a code unit is exposed to the outside world. For example, an interface definition may include function names, parameters, return values, etc.
[0134] Implementation logic refers to the code content within a code unit used to complete specific processing procedures. For example, conditional statements, loops, function calls, and data processing statements within a function body can constitute implementation logic.
[0135] In some embodiments, the second determining module 130 can parse the first code unit into a syntax tree (AST); traverse the nodes in the syntax tree (such as function definition nodes or method definition nodes); extract and retain the function name, parameters, and return value from the function header (MethodHeader) and documentation comments corresponding to the nodes; and replace the function body with ellipses, placeholders, or empty characters. The second determining module 130 can output the processed code text as the second code unit.
[0136] Similar code snippets refer to code snippets that are similar in structure, semantics, or functional expression to a given first code unit.
[0137] In some embodiments, the second determining module 130 can perform hash comparison or fingerprint comparison on each first code unit, identify at least two code segments whose similarity exceeds a similarity threshold, randomly retain one of the at least two code segments, and replace the remaining code segments with reference identifiers; output the merged code segment as the second code unit. The similarity threshold can be a system default value, an empirical value, a manually preset value, or any combination thereof, and can be set according to actual needs. This specification does not limit it, such as setting it to 90%. Similarity is negatively correlated with vector distance. The second determining module 130 can output the processed code text as the second code unit.
[0138] In some embodiments, the second determining module 130 generates a structural summary of at least one first code unit based on an abstract syntax tree. The second determining module 130 may output the processed code text as a second code unit.
[0139] Abstract syntax tree (AST) is a tree-like structure that represents the source code of the first code unit hierarchically according to its syntax structure.
[0140] A structural summary is a concise description formed by extracting the main structural information of the first code unit.
[0141] In some embodiments, the second determining module 130 may use a static analysis tool to parse each first code unit into an abstract syntax tree; extract key identifiers (such as class names, key field names, and core method names) from the abstract syntax tree; reorganize the key identifiers according to indentation format; and output a structural summary as the second code unit. Key identifiers are identifiers that reflect key code segments, such as class names, key field names, and core method names. The structural summary can be structured text in the form of "class-field-method".
[0142] Some embodiments in this specification reduce code redundancy by retaining interface definitions, compressing duplicate code, or extracting structural summaries, allowing the entire project's API contract and module structure to be understood only through key information. This approach saves token consumption and makes the generated code more compliant with calling conventions.
[0143] In some embodiments, the second determining module 130 may replace the target context code with a second code unit, or append the second code unit to the target context code, thereby completing the update of the target context code.
[0144] In some embodiments of this specification, high-value code is first sorted by comprehensive weight and then preprocessed to remove redundant information, thereby retaining more key information in a limited context, reducing calling costs and improving code generation quality.
[0145] The basic concepts have been described above. Obviously, for those skilled in the art, the detailed disclosure above is merely illustrative and does not constitute a limitation of this specification. Although not explicitly stated herein, those skilled in the art may make various modifications, improvements, and corrections to this specification. Such modifications, improvements, and corrections are suggested in this specification and therefore remain within the spirit and scope of the exemplary embodiments described herein.
[0146] Furthermore, this specification uses specific terms to describe embodiments thereof. For example, "an embodiment," "one embodiment," and / or "some embodiments" refer to a particular feature, structure, or characteristic associated with at least one embodiment of this specification. Therefore, it should be emphasized and noted that references to "an embodiment," "one embodiment," or "an alternative embodiment" in different locations throughout this specification do not necessarily refer to the same embodiment. Moreover, certain features, structures, or characteristics in one or more embodiments of this specification can be appropriately combined.
[0147] Furthermore, unless expressly stated in the claims, the order of processing elements and sequences, the use of numbers and letters, or other names described in this specification are not intended to limit the order of the processes and methods described herein. Although various examples have been discussed in the foregoing disclosure of some embodiments of the invention that are currently considered useful, it should be understood that such details are for illustrative purposes only, and the appended claims are not limited to the disclosed embodiments; rather, the claims are intended to cover all modifications and equivalent combinations that conform to the spirit and scope of the embodiments described herein. For example, while the system components described above can be implemented using hardware devices, they can also be implemented solely using software solutions, such as installing the described system on existing servers or mobile devices.
[0148] Similarly, it should be noted that, in order to simplify the description disclosed herein and thus aid in the understanding of one or more embodiments of the invention, the foregoing description of embodiments in this specification may sometimes combine multiple features into a single embodiment, drawing, or description thereof. However, this method of disclosure does not imply that the subject matter of this specification requires more features than those mentioned in the claims. In fact, the embodiments contain fewer features than all the features of a single embodiment disclosed above.
[0149] In some embodiments, numbers describing the quantity of components and attributes are used. It should be understood that such numbers used in the description of embodiments are modified in some examples with the terms "approximately," "approximately," or "generally." Unless otherwise stated, "approximately," "approximately," or "generally" indicates that the numbers are allowed to vary by ±20%. Accordingly, in some embodiments, the numerical parameters used in the specification and claims are approximate values, which may be changed depending on the characteristics required by individual embodiments. In some embodiments, numerical parameters should take into account specified significant digits and employ a general method of digit reservation. Although the numerical ranges and parameters used to confirm their breadth of range in some embodiments of this specification are approximate values, in specific embodiments, such values are set as precisely as feasible.
[0150] For each patent, patent application, patent application publication, and other material such as articles, books, specifications, publications, and documents referenced in this specification, the entire contents of which are incorporated herein by reference. This excludes historical application documents that are inconsistent with or conflict with the content of this specification, as well as documents that limit the broadest scope of the claims in this specification (currently or subsequently appended to this specification). It should be noted that in the event of any inconsistency or conflict between the descriptions, definitions, and / or terminology used in the supplementary materials to this specification and the content of this specification, the descriptions, definitions, and / or terminology used in this specification shall prevail.
[0151] Finally, it should be understood that the embodiments described in this specification are merely illustrative of the principles of the embodiments described herein. Other variations may also fall within the scope of this specification. Therefore, alternative configurations of the embodiments described herein are intended to be illustrative rather than limiting, and are considered consistent with the teachings of this specification. Accordingly, the embodiments described herein are not limited to those explicitly introduced and described herein.
Claims
1. A code generation method, characterized in that, include: Construct an engineering structure diagram model of the target project; Based on the code generation request, the current editing position is obtained, and a candidate code set is determined based on the current editing position and the engineering structure diagram model. The candidate code set includes multiple candidate code units. Determine the comprehensive weight score of each candidate code unit in the candidate code set, and determine the target context code from the candidate code set based on the comprehensive weight score; as well as Reasoning is performed based on the target context code to determine the code result.
2. The method according to claim 1, characterized in that, The determination of the comprehensive weight score for each candidate code unit in the candidate code set includes: For each candidate code unit in the candidate code set, a weighted fusion of at least two dimensions is performed to determine the comprehensive weight score of the candidate code unit; wherein, the dimensions include at least two of the following: The call relationship dimension, the score corresponding to which is determined is based on the in-degree and out-degree of the candidate code unit; The activity dimension is modified, and the score corresponding to the modified activity dimension is determined based on the submission frequency and time decay factor of the candidate code unit; The structural distance dimension, the score corresponding to which the structural distance dimension is determined based on the path distance between the current editing position and the candidate code unit in the engineering structure diagram model; The module importance dimension, the corresponding score for which is determined based on the core module identifier or business priority; and The context relevance dimension, the score corresponding to which is determined is based on the degree of semantic matching between the currently edited content and the candidate code set.
3. The method according to claim 2, characterized in that, The method further includes: Based on the engineering structure diagram model and the historical engineering structure diagram model, the upstream node of the changed node and the changed target code unit are determined. Based on the activity scores of the upstream nodes, the topology injection energy of the target code unit is determined; and Based on the injected energy from the topology, update the score corresponding to the modification activity dimension of the target code unit.
4. The method according to claim 1, characterized in that, The second determining module is further configured as follows: Based on the comprehensive weight score of the multiple candidate code units, the multiple candidate code units are sorted in descending order, and at least one first code unit that meets the preset conditions is selected. as well as The at least one first code unit is preprocessed to obtain at least one second code unit, and the target context code is updated.
5. The method according to claim 4, characterized in that, The preprocessing includes at least one of the following operations: Extract the interface definition from the at least one first code unit and hide the implementation logic; Merge similar code segments in at least one first code unit; as well as Generate a structural summary of the at least one first code unit based on the abstract syntax tree.
6. A code generation system, characterized in that, include: The model building module is configured to build the engineering structure diagram model of the target project; The first determining module is configured to obtain the current editing position based on the code generation request, and determine a candidate code set based on the current editing position and the engineering structure diagram model, wherein the candidate code set includes multiple candidate code units; The second determining module is configured to determine the comprehensive weight score of each candidate code unit in the candidate code set, and determine the target context code from the candidate code set based on the comprehensive weight score; as well as The inference module is configured to perform inference based on the target context code to determine the code result.
7. The system according to claim 5, characterized in that, The second determining module is further configured as follows: For each candidate code unit in the candidate code set, a weighted fusion of at least two dimensions is performed to determine the comprehensive weight score of the candidate code unit; wherein, the dimensions include at least two of the following: The call relationship dimension, the score corresponding to which is determined is based on the in-degree and out-degree of the candidate code unit; The activity dimension is modified, and the score corresponding to the modified activity dimension is determined based on the submission frequency and time decay factor of the candidate code unit; The structural distance dimension, the score corresponding to which the structural distance dimension is determined based on the path distance between the current editing position and the candidate code unit in the engineering structure diagram model; The module importance dimension, the corresponding score for which is determined based on the core module identifier or business priority; and The context relevance dimension, the score corresponding to which is determined is based on the degree of semantic matching between the currently edited content and the candidate code set.
8. The system according to claim 7, characterized in that, The second determining module is further configured as follows: Based on the engineering structure diagram model and the historical engineering structure diagram model, the upstream node of the changed node and the changed target code unit are determined. Based on the activity score of the upstream node, the topology injection energy of the target code unit is determined; as well as Based on the injected energy from the topology, update the score corresponding to the modification activity dimension of the target code unit.
9. The system according to claim 6, characterized in that, The second determining module is further configured as follows: Based on the comprehensive weight score of the multiple candidate code units, the multiple candidate code units are sorted in descending order, and at least one first code unit that meets the preset conditions is selected. as well as The at least one first code unit is preprocessed to obtain at least one second code unit, and the target context code is updated.
10. The system according to claim 9, characterized in that, The preprocessing includes at least one of the following operations: Extract the interface definition from the at least one first code unit and hide the implementation logic; Merge similar code segments in at least one first code unit; as well as Generate a structural summary of the at least one first code unit based on the abstract syntax tree.