Method for improving code writing efficiency
By building a user behavior feature model and Transformer technology, combining big data analysis and code context, candidate code snippets that conform to semantic logic and style constraints are generated, solving the problem of insufficient personalization and recommendation accuracy in the existing technology, and efficient automatic code generation and intelligent recommendation are achieved.
Patent Information
- Application Number
- CN202510481578.1
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-04-17
- Publication Date
- 2025-08-01
- Estimated Expiration
- Not applicable · inactive patent
AI Technical Summary
The existing code completion technology lacks a deep understanding of the individual behavior of developers, cannot dynamically adapt to individual coding styles, insufficient recommendation accuracy and context relevance, and insufficient scoring mechanism, which makes the recommendation results difficult to satisfy practicality.
By building a user behavior feature model, combining big data analysis and Transformer's code sequence prediction technology, it captures the semantic intentions and operation habits in the programming process, combines the code abstract syntax structure and engineering context to generate candidate code snippets that conform to semantic logic and style constraints, and sort and recommend them through a multi-factor scoring mechanism.
It realizes automatic code generation and intelligent recommendations with strong personalized and high prediction accuracy, and has the ability to continuously learn and update, which significantly improves the efficiency of code writing and productivity and quality in the development process.
Smart Images

Figure CN120406916A_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the technical field of integrated development environments, and particularly to a method for improving code writing efficiency. Background Art
[0002] In the current software development process, programmers complete a large number of code writing tasks in an integrated development environment (IDE), and this process is often accompanied by problems such as repetitive operations, high-frequency editing behaviors, structural pattern writing, and context switching. To solve these problems, code completion and intelligent recommendation tools have emerged, including static template recommendation, context-based completion functions, keyword association, history record memory, etc. These functions have become important components of modern IDEs such as VisualStudioCode, IntelliJ IDEA, Eclipse, etc. Especially in some open-source editors, users can expand the code intelligence function by installing plugins, such as using intelligent assistance systems like Copilot, TabNine, Kite, etc., to provide candidate code snippets, syntax hints, and variable name recommendations during the code input stage.
[0003] However, most existing code completion technologies mainly rely on local context information matching and static rule configuration. Although these methods can improve input efficiency in specific situations, they lack a deep understanding of developers' individual behaviors. For example, traditional completion tools often do not consider the user's input behavior trajectory, code style habits, historical editing sequence, and cannot recognize the coding pattern changes of users in different projects and different tasks. This "general but not personalized" strategy limits the adaptability of the completion system in actual projects and also reduces the accuracy and context relevance of the completion content.
[0004] Driven by the field of artificial intelligence, code generation methods based on neural networks have also emerged in recent years. For example, language models based on Transformer (such as GPT, CodeBERT, etc.) are used for code continuation, function generation, and code translation tasks. These methods can predict and generate code snippets in unsupervised or weakly supervised scenarios by training the model with large-scale data. However, such methods also have several prominent problems: First, the model is mainly trained based on natural language analogy and it is difficult to fully incorporate abstract syntax tree (AST) constraints and engineering structure context; second, deploying these models in the actual IDE environment faces challenges such as high computational resource consumption, slow response speed, and unstable accuracy; third, these models ignore the modeling of user behavior data and lack a behavior-driven mechanism, and cannot dynamically adapt to individual coding styles.
[0005] Meanwhile, in existing programming behavior research, some academic efforts have attempted to use user operation data (such as cursor movement, keyboard input, command usage frequency) for behavior pattern mining, and have preliminarily explored behavior-driven coding assistance mechanisms. However, these studies are mostly limited to data statistics and simple clustering analysis, and have not yet constructed a complete user behavior feature model, nor have they formed an end-to-end closed loop with code context, structural semantics, and code prediction. Therefore, the introduction of behavior information is still in its primitive stage and has not yet achieved a true deep integration with code generation logic.
[0006] In addition, there are also certain limitations in the candidate segment screening mechanism of existing code recommendation systems. Common scoring methods mostly use simple TF-IDF features, edit distance matching, or probability output based on language models, and do not fully consider multi-factor fusion and dynamic scoring strategies. For example, candidate code may be syntactically correct but incompatible with the context structure, or have a low confidence level in the behavior model but be wrongly recommended due to a high score. This "scoring skew" problem makes the recommendation results unsatisfactory in terms of practicality.
[0007] In terms of the display and feedback mechanism of candidate recommendations, most current intelligent code completion tools adopt a passive response mechanism, that is, they only provide a candidate list when the user triggers a completion instruction or enters a specific character. This method fails to demonstrate the "active intelligence" ability of the system. At the same time, user feedback often only stays at the level of "whether to select", lacking more refined behavior records and utilization of post-insertion modification behavior, ignoring behavior, etc., making it difficult to effectively train and adaptively update the system. This severely restricts the closed-loop evolution of the behavior model and the completion logic, leaving the system in a static state for a long time and unable to continuously improve performance according to the usage process.
[0008] In a big data environment, there are rich differences and correlations in behaviors and structures among different users, different projects, and different languages. However, most existing methods are unable to extract general behavior features across users and projects, nor have they introduced statistical laws and pattern extraction mechanisms in behavior modeling. Therefore, there are still obvious shortcomings in terms of recommendation accuracy, transferability, and model generalization ability.
[0009] Therefore, how to provide a method for improving code writing efficiency is an urgent problem that needs to be solved by those skilled in the art. Summary of the Invention
[0010] An object of the present invention is to propose a method for improving code writing efficiency. The present invention makes full use of user behavior feature modeling, big data analysis, syntax structure parsing, and Transformer-based code sequence prediction technology, and details how to construct a context-aware behavior feature model, combine code abstract syntax structure and engineering context, and realize automatic code generation and intelligent recommendation that conform to semantic logic, style constraints, and type consistency, with the advantages of strong personalization, high prediction accuracy, and sustainable self-learning and updating.
[0011] A method for improving code writing efficiency according to an embodiment of the present invention includes the following steps:
[0012] S1. Obtain the instruction sequence during the programming process of the user and perform preprocessing;
[0013] S2. Construct a behavior feature model through the preprocessed instruction sequence, and combine big data analysis technology to capture the semantic intention and operation habits of the user during the programming process, and form a semantic graph sequence;
[0014] S3. Obtain the user's programming code, and perform structured parsing in combination with the function call relationship, variable declaration structure, class and method definition information in the project, and extract the code context features;
[0015] S4. Based on the semantic graph sequence and code context features, adopt a Transformer-based sequence prediction algorithm to predict the continuous code sequence at the current position under the condition of maintaining the abstract syntax tree structure constraint, and output multiple candidate code fragments that meet the semantic constraints;
[0016] S5. Perform matching scoring on the candidate code fragments, use the context structure matching degree, semantic similarity score, and behavior feature model confidence score as the scoring basis respectively, and sort the scoring results;
[0017] S6. Present the candidate code fragment with the highest score to the user through an insertable interactive interface, and the user selectively inserts it to the current editing position, and record the response behavior of the user to the candidate recommended code fragment;
[0018] S7. Save the candidate code fragments and user feedback data, update the parameter values of the behavior feature model in real time, and adjust the sorting rules and code generation logic.
[0019] Optionally, the instruction sequence includes cursor movement, shortcut key use, code completion confirmation, and code fragment insertion, and the preprocessing includes timestamp alignment and noise removal.
[0020] Optionally, when generating the candidate code snippets, they need to meet the syntax rules, indentation format requirements, and naming conventions of the target programming language. The syntax rules include the integrity of statement structure, the legality of scope, and the consistency of data types. The indentation format requirements are constrained according to the predefined code style file in the project. The naming conventions are generated based on the statistical patterns of function names, variable names, and class names in the project history.
[0021] Optionally, the response behavior includes three modes: insertion, editing modification, and ignoring.
[0022] Optionally, S2 specifically includes:
[0023] S21. Represent the preprocessed instruction sequence set as a vector matrix where n is the number of instructions, d is the embedding vector dimension of each instruction, and let M = [m1, m2,..., m n T , where m i is the feature vector of the i-th instruction;
[0024] S22. Based on the vector matrix, use a distributed dimensionality reduction method optimized by feature clustering entropy to generate an intermediate feature matrix where r is the embedding vector dimension of each instruction, and r < d;
[0025] S23. Input the intermediate feature matrix into a sparse gated tensor network to generate a behavior tensor where c is the number of tensor channels, and the construction process introduces multi-scale attention weight calculation:
[0026]
[0027] where, T ijk represents the attention weighted value of the j-th dimension of the i-th instruction in the tensor under the k-th channel, α jk is the attention weight of the j-th dimension under the k-th channel, α lk is the attention weight of the l-th dimension under the k-th channel, u ij is the element at the i-th row and j-th column in the intermediate feature matrix, u il is the element at the i-th row and l-th column in the intermediate feature matrix;
[0028] S24. Perform one-dimensional convolution on the behavior tensor along the time axis to calculate the semantic graph sequence The convolution kernel size is set to k, the stride is 1, and the convolution function is defined as:
[0029]
[0030] where, G ik is the semantic graph feature value of the i-th instruction under the k-th channel, ω s is the weight of the s-th convolutional kernel, and k is the length of the convolutional kernel;
[0031] S25. Perform global feature aggregation on the semantic graph sequence, and combine the historical behavior matrix across users in the big data environment to perform similarity matching and construct a behavior feature model
[0032]
[0033] where B k is the global fusion representation of the behavior feature model under the k-th channel, γ is a regulatory factor that controls the fusion weight of local and global information, N is the number of users in the big data sample, and D jk is the historical behavior feature value of the j-th user under the k-th channel.
[0034] Optionally, the intermediate feature matrix The dimensionality reduction function is defined as:
[0035]
[0036] where argmin is the independent variable value when the function takes the minimum value, is the transpose of m i , W j is the feature weight vector of the j-th clustering direction, u ij is the element in the i-th row and j-th column of the intermediate feature matrix, r is the dimensionality of the feature after dimensionality reduction, λ is the weight of the information entropy regularization term, H(U) is the information entropy of the intermediate feature matrix, log2 is the logarithmic function, n is the number of instructions, d and r are the embedding vector dimensions of each instruction respectively, and r < d.
[0037] Optionally, the specific steps of S3 include:
[0038] S31. Obtain the source code file that the user is currently writing, and construct the syntax tree structure of the code. The syntax tree structure is generated according to the grammar rules of the target programming language and contains a node set where n i represents the i-th syntax unit node, and m is the number of syntax unit nodes;
[0039] S32. Based on the syntax tree structure, extract the function call graph where is the function node set, representing all function entities in the project, is the directed edge set, representing the call relationship between functions;
[0040] S33. Construct a variable reference graph where is a set of variable nodes, representing all variables in the source code, represents the reference relationship between variables and syntax nodes;
[0041] S34. Construct a class - method structure mapping table where c i is the name of the i - th class, represents the set of methods under class c i , recording its inheritance chain, overriding relationship, and parameter structure;
[0042] S35. Combine the behavior feature model B = {B1, B2,..., B c}, and calculate the context behavior weight of each syntax node :
[0043]
[0044] where, s i is the weighted score of the context behavior features of syntax node n i , B k is the global fusion representation of the behavior feature model in the k - th channel, c is the number of tensor channels, w ik is the feature response value of syntax node n i in the k - th channel.
[0045] Optionally, the S4 specifically includes:
[0046] S41. Fuse the semantic graph sequence G = {g1, g2,..., g q} with the code context feature set to construct a context embedding matrix where, F is the function call graph, V is the variable reference graph, C is the class - method structure mapping table, is the set of nodes, l is the combination number of the fused semantic segments and syntax nodes, d is the feature dimension, and the i - th row vector is the fused representation of the i - th context unit;
[0047] S42. Construct a behavior - driven Transformer model, with the input being the embedding matrix X, and combining the position encoding matrix and the structure mask matrix and the output being the candidate code representation tensor Y = [y1, y2,..., y t T , where, is the predicted code token vector sequence, is the embedded representation of the i-th predicted token, and t is the length of the target code sequence;
[0048] S43. Map the output tensor Y to a code token sequence T = {t1, t2,..., t t}, where each code token t i satisfies the same constraint conditions;
[0049] S44. Restore the token sequence T to a set of candidate code snippets Z = {z1, z2,..., z m}, where m is the number of code snippets, and each code snippet z i is a continuous, compilable, and semantically complete code structure that satisfies all the above constraints for subsequent scoring and sorting.
[0050] Optionally, the same constraint conditions include:
[0051] Grammatical structure integrity: The token sequence T can be restored to a legal abstract syntax tree A T , that is, T ∈ ValidAST(L), where L represents the currently used programming language;
[0052] Scope legality: If t i represents an identifier, the scope where t i is located must be resolvable in the set of context nodes ;
[0053] Data type consistency: If t i is in the right value position of an assignment statement, the data type of t i must be consistent with the data type of the left value;
[0054] Indentation format matching: The number of leading spaces at the start of each code line needs to satisfy the function I(t i ) = f(Depth(n j )), where I(t i ) is the indentation amount of the code line where the i-th token is located, n j is the syntax tree node it belongs to, Depth(n j ) is the level of the node in the syntax tree, and f(·) is a mapping function;
[0055] Naming convention consistency: If t i represents one of a variable name, a function name, and a class name, the morphological structure of t i needs to satisfy the set of statistical naming rules P in the project history, that is, Form(t i ) ∈ P, where Form(·) is the set of morphological structures.
[0056] Optionally, the specific content of S5 includes:
[0057] S51. Calculate the context structure matching degree score based on the candidate code snippet z i ∈Z:
[0058]
[0059] where Z is the set of candidate code snippets, is the structure matching degree score of the candidate code snippet z i , is the set of current source code syntax nodes, d is the embedding vector dimension of each instruction, φ jk is the structure eigenvalue of the j-th syntax node in the k-th dimension, ψ ik is the structure encoding value of the candidate snippet z i in the k-th dimension;
[0060] S52. Calculate the semantic similarity score between each candidate snippet z i and the semantic graph sequence G:
[0061]
[0062] where, is the semantic similarity score of the candidate snippet z i , ο is the length of the semantic graph sequence, c is the number of tensor channels, g jk is the eigenvalue of the j-th moment in the k-th channel in the semantic graph, t i is the number of tokens in the candidate code snippet z i , η ilk represents the embedding value of the l-th token in the k-th channel, w lk is the weighted response of the behavior feature model at the l-th token and the k-th channel, and σ(·) is the standard Sigmoid function;
[0063] S53. Perform a confidence score on the response intensity of the candidate snippet z i in the behavior feature model:
[0064]
[0065] where, is the confidence score of the behavior feature model of the candidate snippet z i , θ ijk is the behavior response value of the j-th token in the candidate snippet in the k-th channel, B k is the global fusion representation of the behavior feature model in the k-th channel, t i is the number of tokens in the candidate code snippet z i , c is the number of tensor channels, and ∈ is a positive constant used to avoid division by zero errors;
[0066] S54. Weightedly fuse the above three score values to obtain the final sorting score of the candidate fragments:
[0067]
[0068] Among them, R i is the final sorting score of the candidate fragment z i , λ1, λ2, λ3 ∈ [0, 1] are weighting coefficients, satisfying λ1 + λ2 + λ3 = 1, which are the structure matching degree score, semantic similarity score, and behavior confidence score respectively, represents the positive transformation of semantic similarity and is used to unify the direction;
[0069] S55. Sort the candidate code fragment set Z = {z1, z2,..., z m} in descending order according to the size of the final sorting score, output the sorted candidate list, and present it to the user through an insertable interactive interface.
[0070] The beneficial effects of the present invention are as follows:
[0071] First of all, by introducing multi-dimensional instruction behavior data of users during the programming process, the present invention constructs a behavior feature model, realizing in-depth modeling and high-precision expression of developers' personalized coding habits. Compared with the existing code completion technology that only relies on static context, the present invention can capture users' semantic intentions, operation paths, and behavior patterns, improving the context relevance and user matching degree in the code generation and recommendation process, and significantly enhancing the system's adaptability to different users and different project environments.
[0072] Secondly, the present invention combines structured context information such as abstract syntax tree constraints, function call graphs, and variable scope graphs during the code generation process, and generates multiple candidate code fragments that meet semantic logic and syntax rules through a sequence prediction algorithm based on Transformer. Compared with existing methods, the present invention not only improves the correctness and integrity of the generated code, but also ensures the readability and consistency of the generated code in engineering practice through mechanisms such as indentation style constraints and naming habit learning. At the same time, the scoring and sorting mechanism introduces multi-factor evaluation indicators such as structure matching degree, semantic similarity, and behavior model confidence, realizing a more comprehensive and accurate candidate sorting strategy.
[0073] Finally, through the real-time recording and feedback analysis of user response behaviors, the present invention constructs an adaptive update mechanism, enabling the behavioral feature model to continuously optimize and dynamically adjust the recommendation logic. This closed-loop learning ability enables the system to continuously improve its intelligence level during long-term use, forming an intelligent evolution effect of "the more it is used, the more it understands the user", thereby significantly improving the code writing efficiency, reducing repetitive labor, and enhancing the overall productivity and quality level in the software development process. BRIEF DESCRIPTION OF THE DRAWINGS
[0074] The drawings are used to provide a further understanding of the present invention and constitute a part of the specification. Together with the embodiments of the present invention, they are used to explain the present invention and do not constitute a limitation to the present invention. In the drawings:
[0075] Figure 1 is a flowchart of a method for improving code writing efficiency proposed by the present invention;
[0076] Figure 2 is a flowchart of the code prediction process of a method for improving code writing efficiency proposed by the present invention;
[0077] Figure 3 is a schematic diagram of the Transformer structure and constraint control of a method for improving code writing efficiency proposed by the present invention. DETAILED DESCRIPTION OF THE EMBODIMENTS
[0078] Now, the present invention will be further described in detail with reference to the drawings. These drawings are all simplified schematic diagrams, only illustrating the basic structure of the present invention in a schematic manner, so they only show the components related to the present invention.
[0079] Referring to Figures 1 - 3 , a method for improving code writing efficiency includes the following steps:
[0080] S1. Obtain the instruction sequence of the user during the programming process and perform preprocessing;
[0081] S2. Construct a behavioral feature model through the preprocessed instruction sequence, and combine big data analysis technology to capture the semantic intention and operation habits of the user during the programming process, forming a semantic graph sequence;
[0082] S3. Obtain the user's programming code, and perform structured parsing in combination with the function call relationship, variable declaration structure, class and method definition information in the project to extract the code context features;
[0083] S4. Based on the semantic graph sequence and code context features, adopt a sequence prediction algorithm based on Transformer. Under the condition of maintaining the abstract syntax tree structure constraint, predict the continuous code sequence at the current position, and output multiple candidate code snippets that meet the semantic constraints;
[0084] S5. Perform matching scoring on the candidate code snippets. Use the context structure matching degree, semantic similarity score, and behavior feature model confidence score as the scoring basis respectively, and sort the scoring results;
[0085] S6. Present the candidate code snippet with the highest score to the user through an insertable interaction interface. The user selectively inserts it to the current editing position, and record the user's response behavior to the candidate recommended code snippet;
[0086] S7. Save the candidate code snippets and user feedback data, update the parameter values of the behavior feature model in real time, and adjust the sorting rules and code generation logic.
[0087] The present invention constructs a code generation process centered on the user behavior feature model, integrates the operation behavior of the user in the programming process, the code context structure, and the project semantic information, and establishes an end-to-end code prediction and recommendation mechanism. Through multi-stage information extraction, structure analysis, semantic modeling, generation prediction, and scoring feedback, the intelligence, self-adaptability, and personalization in the code completion process are realized, effectively improving the code writing efficiency, reducing the repetitive labor, and enhancing the automation and precision control capabilities in the development process.
[0088] In this embodiment, the instruction sequence includes cursor movement, shortcut key use, code completion confirmation, and code snippet insertion, and the preprocessing includes timestamp alignment and noise elimination.
[0089] The present invention obtains the programming instruction behavior of the user in a fine-grained manner, such as cursor movement, shortcut key use, code completion confirmation, and code snippet insertion, and combines timestamp alignment and noise elimination processing to ensure the timeliness, stability, and computability of the behavior data, providing a basis for the high-quality training of the subsequent behavior feature model. This precise sampling mechanism for behavior modeling enhances the depth of the model's understanding of the user's intention and improves the personalized expressiveness of code generation.
[0090] In this embodiment, when generating the candidate code snippets, they need to meet the syntax rules, indentation format requirements, and naming conventions of the target programming language. The syntax rules include the integrity of the statement structure, the legality of the scope, and the consistency of the data type. The indentation format requirements are constrained according to the predefined code style file in the project, and the naming conventions are generated based on the statistical patterns of function names, variable names, and class names in the project history.
[0091] The present invention ensures the comprehensive adaptation of the generated content in terms of language legality, style consistency, and project naming conventions by setting constraint conditions such as syntax rules, indentation formats, and naming conventions for candidate code snippets. This mechanism improves the engineering practicability and maintainability of the recommended code, reduces code rollback and secondary modification caused by issues such as inconsistent code styles and naming conflicts, thereby improving development efficiency and code quality.
[0092] In this embodiment, the response behaviors include three modes: insertion, editing and modification, and ignoring.
[0093] The present invention classifies and records the response behaviors of users in detail, including three types of feedback: insertion, editing and modification, and ignoring, realizing the true evaluation of the recommendation effect and the behavior-driven dynamic adjustment. This closed-loop feedback mechanism enables the behavior feature model to be continuously optimized, continuously improves the accuracy and relevance of code recommendation, and has the intelligent features of long-term adaptation and personalized evolution.
[0094] In this embodiment, S2 specifically includes:
[0095] S21. Represent the preprocessed instruction sequence set as a vector matrix where n is the number of instructions, d is the embedding vector dimension of each instruction, and let M = [m1, m2,..., m n T , where m i is the feature vector of the i-th instruction;
[0096] S22. Based on the vector matrix, use a distributed dimensionality reduction method optimized by feature clustering entropy to generate an intermediate feature matrix where r is the embedding vector dimension of each instruction, and r < d;
[0097] S23. Input the intermediate feature matrix into a sparse gated tensor network to generate a behavior tensor where c is the number of tensor channels, and the construction process introduces multi-scale attention weight calculation:
[0098]
[0099] where, T ijk represents the attention weighted value of the j-th dimension of the i-th instruction in the tensor under the k-th channel, α jk is the attention weight of the j-th dimension under the k-th channel, α lk is the attention weight of the l-th dimension under the k-th channel, u ij is the element in the i-th row and j-th column of the intermediate feature matrix, u il is the element in the i-th row and l-th column of the intermediate feature matrix;
[0100] S24. Perform one-dimensional convolution on the behavior tensor along the time axis to calculate the semantic graph sequence Set the convolution kernel size to k, the stride to 1, and define the convolution function as follows:
[0101]
[0102] where G ik is the semantic graph feature value of the i-th instruction in the k-th channel, ω s is the weight of the s-th convolution kernel, and k is the length of the convolution kernel;
[0103] S25. Perform global feature aggregation on the semantic graph sequence, and combine the historical behavior matrix of cross-users in the big data environment to perform similarity matching and construct a behavior feature model
[0104]
[0105] where B k is the global fusion representation of the behavior feature model in the k-th channel, γ is a regulatory factor for controlling the fusion weight of local and global information, N is the number of users in the big data sample, and D jk is the historical behavior feature value of the j-th user in the k-th channel.
[0106] In the present invention, the preprocessed instruction sequence is converted into a high-dimensional embedding matrix, and the deep behavior pattern is extracted by using a sparse gated tensor network. Further, the semantic graph is calculated through a multi-scale attention mechanism and one-dimensional convolution, and the behavior feature model is constructed by combining the user behavior history in the big data. This process improves the model's representation ability for the behavior sequence, enhances the high-dimensional modeling ability for the user intention, enables the model to not only adapt to individual differences but also have a certain behavior migration ability.
[0107] In this embodiment, the dimensionality reduction function of the intermediate feature matrix is defined as follows:
[0108]
[0109] where argmin is the independent variable value when the function takes the minimum value, is the transpose of m i W j is the feature weight vector of the j-th clustering direction, u ij is the element in the i-th row and j-th column of the intermediate feature matrix, r is the dimension of the feature after dimensionality reduction, λ is the weight of the information entropy regularization term, H(U) is the information entropy of the intermediate feature matrix, log2 is the logarithmic function, n is the number of instructions, d and r are the embedding vector dimensions of each instruction respectively, and r < d.
[0110] The present invention optimizes the dimensionality reduction method by introducing feature clustering entropy, compresses the computational resource overhead while retaining the instruction feature expression ability, and improves the efficiency and model stability of behavior feature extraction. The introduction of information entropy regularization avoids high-dimensional feature redundancy, improves the model's focusing ability on key information, and thus enhances the discriminability and generalization performance of subsequent model training.
[0111] In this embodiment, step S3 specifically includes:
[0112] S31. Obtain the source code file currently being written by the user, and construct a syntax tree structure of the code. The syntax tree structure is generated according to the grammar rules of the target programming language and contains a set of nodes where n i represents the i-th syntax unit node, and m is the number of syntax unit nodes;
[0113] S32. Based on the syntax tree structure, extract the function call graph where is the set of function nodes, representing all function entities in the project, is the set of directed edges, representing the call relationship between functions;
[0114] S33. Construct a variable reference graph where is the set of variable nodes, representing all variables in the source code, represents the reference relationship between variables and syntax nodes;
[0115] S34. Construct a mapping table of class and method structures where c i is the name of the i-th class, represents the set of methods under class c i and records its inheritance chain, overriding relationship, and parameter structure;
[0116] S35. Combine the behavior feature model B = {B1, B2,..., B c}, and calculate the context behavior weight of each syntax node :
[0117]
[0118] where, s i is the context behavior feature weighted score of the syntax node n i , B k is the global fusion representation of the behavior feature model in the k-th channel, c is the number of tensor channels, and w ik is the feature response value of the syntax node n i in the k-th channel.
[0119] Through the construction of a code structure diagram (function call graph, variable reference graph, class method structure table) and the combination with the output of the behavior model, the present invention realizes the accurate mapping and weight scoring of user behavior characteristics at the syntax node granularity, and improves the adaptation degree of the syntax context to the behavior characteristics. This structural behavior fusion mechanism enhances the model's understanding of complex engineering structures and effectively improves the semantic consistency and logical coherence during code prediction.
[0120] In this embodiment, the S4 specifically includes:
[0121] S41. Fuse the semantic graph sequence G = {g1, g2,..., g q} with the code context feature set to construct a context embedding matrix where F is the function call graph, V is the variable reference graph, C is the class and method structure mapping table, is the node set, l is the combination number of the fused semantic segments and syntax nodes, d is the feature dimension, and the i-th row vector is the fused representation of the i-th context unit;
[0122] S42. Construct a behavior-driven Transformer model, with the input being the embedding matrix X, and combined with the position encoding matrix and the structure mask matrix The output is the candidate code representation tensor Y = [y1, y2,..., y t T , where, is the predicted code token vector sequence, is the embedding representation of the i-th predicted token, and t is the length of the target code sequence;
[0123] S43. Map the output tensor Y to the code token sequence T = {t1, t2,..., t t}, and each code token t i satisfies the same constraint conditions;
[0124] S44. Restore the token sequence T to the candidate code fragment set Z = {z1, z2,..., z m}, where m is the number of code fragments, and each code fragment z i is a continuous, compilable and semantically complete code structure that satisfies all the above constraints for subsequent scoring and sorting.
[0125] By integrating the semantic graph with the code structure features, the present invention establishes a Transformer input matrix, introduces positional encoding and structural masking, and realizes the prediction of legal code sequences under the constraint of the abstract syntax tree, improving the syntactic integrity and semantic correctness of candidate codes. The system embeds multiple constraints at the generation stage, effectively avoiding structural errors and style conflicts, and enhancing the plug-and-play performance of the recommended codes.
[0126] In this embodiment, the equivalent constraint conditions include:
[0127] Syntactic structure integrity: The token sequence T can be restored to a legal abstract syntax tree A T , that is, satisfying T ∈ ValidAST(L), where L represents the programming language currently in use;
[0128] Scope legality: If t i represents an identifier, the scope where t i is located must be resolvable in the set of context nodes ;
[0129] Data type consistency: If t i is in the right value position of an assignment statement, the data type of t i must be consistent with the data type of the left value;
[0130] Indentation format matching: The number of leading spaces at the start of each code line needs to satisfy the function I(t i ) = f(Depth(n j ))), where I(t i ) is the indentation amount of the i-th token's code line, n j is the syntax tree node it belongs to, Depth(n j ) is the level of the node in the syntax tree, and f(·) is a mapping function;
[0131] Naming convention consistency: If t i represents one of a variable name, a function name, and a class name, the morphological structure of t i needs to satisfy the set of statistical naming rules P in the project history, that is, Form(t i ) ∈ P, where Form(·) is the set of morphological structures.
[0132] By setting five constraints of unified syntactic structure integrity, scope legality, data type consistency, indentation style, and naming rules, the generated candidate code snippets not only conform to the compilation specifications but also are highly consistent in the project style and team specifications. This global constraint mechanism enhances the engineering adaptability of the code, reduces the deviation between the generated code and the actual requirements, and improves the maintainability and readability of the recommended content.
[0133] In this embodiment, S5 specifically includes:
[0134] S51. Based on the candidate code snippet z i ∈Z, calculate its context structure matching degree score:
[0135]
[0136] where Z is the set of candidate code snippets, is the structure matching degree score of the candidate code snippet z i , is the set of current source code syntax nodes, d is the embedding vector dimension of each instruction, φ is the structure eigenvalue of the j-th syntax node in the k-th dimension, ψ jk is the structure encoding value of the candidate snippet z ik in the k-th dimension; i in the k-th dimension;
[0137] S52. Calculate the semantic similarity score for each candidate snippet z i and the semantic graph sequence G:
[0138]
[0139] where, is the semantic similarity score of the candidate snippet z i , ο is the length of the semantic graph sequence, c is the number of tensor channels, g jk is the eigenvalue of the j-th moment in the k-th channel in the semantic graph, t i is the number of tokens in the candidate code snippet z i , η ilk represents the embedding value of the l-th token in the k-th channel, w lk is the weighted response of the behavior feature model at the l-th token and the k-th channel, and σ(·) is the standard Sigmoid function;
[0140] S53. Perform a confidence score on the response intensity of the candidate snippet z i in the behavior feature model:
[0141]
[0142] where, is the confidence score of the behavior feature model of the candidate snippet z i , θ ijk is the behavior response value of the j-th token in the candidate snippet in the k-th channel, B k is the global fusion representation of the behavior feature model in the k-th channel, t i is the candidate code snippet z iThe number of tokens in, c is the number of tensor channels, and ∈ is a positive constant used to avoid division by zero errors;
[0143] S54. Weightedly fuse the above three score values to obtain the final ranking score of the candidate segment:
[0144]
[0145] Among them, R i is the final ranking score of the candidate segment z i , λ1, λ2, λ3 ∈ [0, 1] are weighting coefficients, satisfying λ1 + λ2 + λ3 = 1, are the structural matching degree score, semantic similarity score, and behavior confidence score respectively, represents the positive transformation of semantic similarity and is used to unify the direction;
[0146] S55. Sort the candidate code segment set Z = {z1, z2,..., z m} in descending order according to the size of the final ranking score, output the sorted candidate list, and present it to the user through an insertable interactive interface.
[0147] The present invention proposes a scoring and ranking mechanism based on multi-factor fusion, which scores candidate code segments from three dimensions: context structure matching degree, semantic similarity, and behavior model confidence, and performs unified ranking through adjustable weight factors to ensure that the output results achieve an optimal balance in terms of accuracy, relevance, and personalization. At the same time, this scoring mechanism has strong scalability, can dynamically adjust the factor weights according to task or project requirements, and adapt to different types of development environments and user needs, thereby greatly enhancing the practical value and intelligence of the final recommendation results.
[0148] Example 1:
[0149] To verify the feasibility of the present invention in implementation, the present invention is applied to the development project of the "Enterprise-level Human Resource Management System" in the R & D center of a large Internet company A in Shenzhen. This project includes multiple modules, has a large amount of code, involves many team members, has a complex code style and frequent migration of historical projects, and there are obvious problems such as repetitive development, inconsistent styles, low coding efficiency, and inaccurate completion content. To solve the efficiency bottleneck in the development process, the technical person in charge of the company decides to introduce the method proposed by the present invention during the development process.
[0150] During the actual deployment process, the core module of the present invention is integrated into the in-house developed development platform based on IntelliJ IDEA and provided to 8 Java back-end engineers as an intelligent plug-in. After the system starts running, it automatically collects the operation behavior data of developers during the coding process, including input instructions such as cursor movement, code completion confirmation, and shortcut key usage. At the same time, the system aligns the timestamps and eliminates noise from the collected data in real time in the background, and constructs a user behavior feature model based on the behavior sequence. This model integrates the structural syntax graph and behavior sequence library in hundreds of historical Java projects of the company to form a personalized semantic graph supported by big data analysis.
[0151] In this project, the developer is mainly responsible for the development of the "employee training module" and the "salary settlement module", which involves a large number of inheritance calls of class structures, method overloading, and database access operations. In the traditional way, when writing similar DAO classes or Service interfaces, developers often need to manually repeat the input of method signatures, variable declarations, and formatted SQL statement fragments, which is not only time-consuming but also prone to naming style inconsistencies and type declaration errors.
[0152] After introducing the method of the present invention, when the developer starts coding for the first time, the system will predict the target semantics within the first 10 characters of their input in advance based on their historical behavior model combined with the current project context features, and provide 3-5 candidate code fragments that conform to the current syntax structure, code indentation rules, and naming style. These fragments include complete method definitions, annotated variable declarations, and data access interface codes, greatly reducing repetitive labor. For example, the system can automatically generate an @Select annotation SQL query method that conforms to the MyBatis style in this project and correctly matches the database field types with Java entity attributes. More importantly, these recommendations are dynamically generated by the behavior model according to the long-term usage habits of each developer, reflecting personalized learning ability.
[0153] During the two months of project iteration, the R & D team compared the development efficiency and code consistency before and after using the invention. Before using the present invention, the average number of lines of code manually input by each developer per day was 900 lines, the code modification rate was 27.5%, the naming style inconsistency rate was 11.8%, and it took about 3 hours to write an average function point (Service + DAO + Controller). After using the present invention, the number of lines of manually input code dropped to 620 lines, the hit rate of auto - completion reached 78.6%, the code modification rate dropped to 14.2%, the naming style consistency increased to 98.4%, and the development time for each function point was shortened to 1.9 hours. More importantly, developers reported that the intelligent recommendation had high accuracy and small amount of modification after insertion. The system could effectively identify the call relationship and structural constraints of the current context, and the proportion of candidate code snippets that "could be directly used without rewriting" reached 69.7%.
[0154] In addition, the system continuously fine - tuned the behavior feature model based on the developers' response behaviors (insert, modify, ignore) after the appearance of completion suggestions, automatically adjusted the sorting logic and recommendation strategy, so that the suggestion hit rate of the model was nearly 22 percentage points higher in the last week of the first month than in the first week after going online. The system updated the model once a day, combined with big data analysis across the entire project scope, enhancing its adaptability to new modules and new business logics.
[0155] To further demonstrate the actual effect of the system, the following table lists the comparison of key coding indicators of three main developers before and after using the present invention in the "Employee Training Module" and "Salary Settlement Module":
[0156] Table 1 Comparison of implementation effect data of the present invention in the enterprise human resource system
[0157]
[0158] Through the above implementation cases and data verification, the present invention has significant practical application value in a real enterprise - level software development environment, can effectively improve development efficiency, reduce repetitive operations, enhance code consistency, and has good self - adaptive evolution ability. This method is not only applicable to Java project development, but can also be extended to other programming language environments such as front - end, Python, Go, etc., with broad promotion prospects and practical value.
[0159] The above is only a preferred specific implementation manner of the present invention, but the protection scope of the present invention is not limited thereto. Any person skilled in the art within the technical scope disclosed by the present invention, according to the technical solution and inventive concept of the present invention, makes equivalent substitutions or changes, and should be covered by the protection scope of the present invention.
Claims
1. A method for improving code writing efficiency, characterized in that: It includes the following steps: S1. Obtain the instruction sequence during the programming process of the user and perform preprocessing; S2. Construct a behavior feature model through the preprocessed instruction sequence, and combine big data analysis technology to capture the semantic intention and operation habits of the user during the programming process, and form a semantic graph sequence; S3. Obtain the user's programming code, and perform structured parsing in combination with the function call relationship, variable declaration structure, class and method definition information in the project, and extract the code context features; S4. Based on the semantic graph sequence and code context features, adopt a sequence prediction algorithm based on Transformer. Under the condition of maintaining the abstract syntax tree structure constraint, predict the continuous code sequence at the current position, and output multiple candidate code fragments that meet the semantic constraints; S5. Perform matching scoring on the candidate code fragments, and use the context structure matching degree, semantic similarity score, and behavior feature model confidence score as the scoring basis respectively, and sort the scoring results; S6. Present the candidate code fragment with the highest score to the user through an insertable interactive interface. The user selectively inserts it to the current editing position, and records the response behavior of the user to the candidate recommended code fragment; S7. Save the candidate code fragments and user feedback data, update the parameter values of the behavior feature model in real time, and adjust the sorting rules and code generation logic.
2. A method for improving code writing efficiency according to claim 1, characterized in that, The instruction sequence includes cursor movement, shortcut key use, code completion confirmation, and code fragment insertion. The preprocessing includes timestamp alignment and noise removal.
3. A method for improving code writing efficiency according to claim 1, characterized in that When generating the candidate code fragments, they need to meet the syntax rules, indentation format requirements, and naming conventions of the target programming language. The syntax rules include statement structure integrity, scope legality, and data type consistency. The indentation format requirements are constrained according to the predefined code style file in the project. The naming conventions are generated based on the statistical patterns of function names, variable names, and class names in the project history.
4. The method for improving code writing efficiency according to claim 1, wherein: The response behavior includes three methods: insertion, editing modification, and ignoring.
5. A method for improving code writing efficiency according to claim 1, characterized in that, Specifically, S2 includes: S21. Represent the preprocessed instruction sequence set as a vector matrix where n is the number of instructions and d is the dimension of the embedding vector of each instruction. Let M = [m1, m2,..., m n T , where m i is the feature vector of the i-th instruction; S22. Based on the vector matrix, the intermediate feature matrix is generated by using a distributed dimensionality reduction method based on feature clustering entropy optimization Where r is the embedding vector dimension of each instruction, and r <d; S23. Input the intermediate feature matrix into the sparse gated tensor network to generate the behavior tensor Where c is the number of tensor channels, and the construction process introduces multi-scale attention weight calculation: Among them, T ijk represents the attention weighted value of the j-th dimension of the i-th instruction in the tensor under the k-th channel, and α jk is the attention weight of the j-th dimension under the k-th channel, and α lk is the attention weight of the l-th dimension under the k-th channel, and u ij is the element at the i-th row and j-th column in the intermediate feature matrix, and u il is the element at the i-th row and l-th column in the intermediate feature matrix; S24. Perform one-dimensional convolution on the behavior tensor along the time axis to calculate the semantic graph sequence Set the convolution kernel size to k, the stride to 1, and the convolution function is defined as: Among them, G ik is the semantic graph feature value of the i-th instruction under the k-th channel, ω s is the weight of the s-th convolution kernel, and k is the length of the convolution kernel; S25. Perform global feature aggregation on the semantic graph sequence, and combine the historical behavior matrix across users in the big data environment to perform similarity matching and construct a behavior feature model Among them, B k is the global fusion representation of the behavior feature model in the k-th channel, γ is the adjustment factor for controlling the fusion weight of local and global information, N is the number of users in the big data sample, and D jk is the historical behavior feature value of the j-th user in the k-th channel.
6. A method for improving code writing efficiency according to claim 5, characterized in that, The intermediate feature matrix The dimensionality reduction function is defined as: where argmin is the independent variable value when the function takes the minimum value, is m i transpose of, W j is the feature weight vector of the j-th clustering direction, u ij is the element in the i-th row and j-th column of the intermediate feature matrix, r is the dimension of the feature after dimensionality reduction, λ is the weight of the information entropy regularization term, H(U) is the information entropy of the intermediate feature matrix, log2 is the logarithmic function, n is the number of instructions, d and r are the embedding vector dimensions of each instruction respectively, and r < d.
7. A method for improving code writing efficiency according to claim 1, characterized in that, Specifically, S3 includes: S31, obtain the source code file currently being written by the user, and construct a syntax tree structure of the code. The syntax tree structure is generated according to the grammar rules of the target programming language and includes a node set where n i represents the i-th grammatical unit node, and m is the number of grammatical unit nodes; S32. Extract function call graph based on syntax tree structure in It is a collection of function nodes, representing all function entities in the project. It is a set of directed edges, indicating the calling relationship between functions; S33. Construct a variable reference graph wherein is a set of variable nodes, representing all variables in the source code, represents the reference relationship between variables and syntax nodes; S34. Construct a mapping table of class and method structures where c i is the name of the i-th class, represents the set of methods under class c i and records its inheritance chain, overriding relationship, and parameter structure; S35. Combine the behavior feature model B = {B1, B2,..., B c}, and calculate the weighted context behavior feature score for each syntax node . Where s i is the weighted context behavior feature score of the syntax node n i , B k is the global fusion representation of the behavior feature model in the k-th channel, c is the number of tensor channels, and w ik is the feature response value of the syntax node n i in the k-th channel.
8. A method for improving code writing efficiency according to claim 1, characterized in that Specifically, S4 includes: S41. Combine the semantic graph sequence G = {g1, g2,..., g q} with the code context feature set for feature fusion to construct the context embedding matrix where F is the function call graph, V is the variable reference graph, C is the class - method structure mapping table, is the node set, l is the combination number of the fused semantic segments and syntax nodes, d is the feature dimension, and the i - th row vector is the fused representation of the i - th context unit; S42. Construct a behavior-driven Transformer model with the input being the embedding matrix X, and combine it with the positional encoding matrix and the structural mask matrix The output is the candidate code representation tensor Y = [y1, y2,..., y t T , where is the predicted code token vector sequence, is the embedding representation of the i-th predicted token, and t is the length of the target code sequence; S43. Map the output tensor Y to a sequence of code tokens T = {t1, t2,..., t t}, where each code token t i satisfies the same constraint conditions; S44. Restore the marked sequence T to a set of candidate code snippets Z = {z1, z2,..., z m}, where m is the number of code snippets, and each code snippet z i is a semantically complete code structure that is continuous, compilable, and satisfies all the above constraints for subsequent scoring and ranking.
9. A method for improving code writing efficiency according to claim 1, characterized in that, The equivalent constraint conditions include: Syntactic structure integrity: The token sequence T can be restored to a legal abstract syntax tree A T , that is, it satisfies T ∈ ValidAST(L), where L represents the currently used programming language; Scope validity: If t i represents an identifier, then t i The scope must be resolvable within the context node set middle; Data type consistency: If t i is in the right value position of an assignment statement, then the data type of t i must be consistent with the data type of the left value; Indentation format matching: The starting space count of each code line should satisfy the function I(t i ) = f(Depth(n j ))), where I(t i ) is the indentation of the code line where the i-th token is located, n j is the syntax tree node it belongs to, Depth(n j ) is the level of the node in the syntax tree, and f(·) is a mapping function; Naming convention consistency: If t i represents one of variable names, function names, and class names, then the morphological structure of t i needs to satisfy the set of statistical naming rules P in the project history, that is, Form(t i ) ∈ P, where Form(·) is the set of morphological structures.
10. A method for improving code writing efficiency according to claim 1, characterized in that, Specifically, S5 includes: S51. Based on the candidate code snippet z i ∈ Z, calculate its context structure matching degree score: where Z is the set of candidate code snippets, is the structural matching score of the candidate code snippet z i , is the set of current source code syntax nodes, d is the embedding vector dimension of each instruction, and φ jk is the structural feature value of the j-th syntax node in the k-th dimension, and ψ ik is the structural encoding value of the candidate snippet z i on the k-th dimension; S52. For each candidate segment z i compute the semantic similarity score with the semantic graph sequence G: in, is the candidate segment z i The semantic similarity score of , ο is the length of the semantic graph sequence, c is the number of tensor channels, g jk is the feature value of the kth channel at the jth moment in the semantic graph, t i For candidate code fragment z i The number of markers in , η ilk represents the embedding value of the lth tag in the kth channel, w lk is the weighted response of the behavioral feature model under the lth mark and kth channel, σ(·) is the standard Sigmoid function; S53. Confidence scoring for the response intensity of candidate segment z i in the behavioral feature model: in, is the candidate segment z i The confidence score of the behavioral feature model, θ ijk is the behavioral response value of the jth marker in the candidate segment under the kth channel, B k is the global fusion representation of the behavioral feature model under the kth channel, t i For candidate code fragment z i The number of tags in , c is the number of tensor channels, and ∈ is a positive constant used to avoid division by zero errors; S54. Perform weighted fusion on the above three score values to obtain the final sorting score of the candidate fragment: Among them, R i is the candidate segment z i The final ranking score, λ1,λ2,λ3∈[0,1] are weighted coefficients, satisfying λ1+λ2+λ3=1, They are structure matching score, semantic similarity score, and behavior confidence score, The positive transformation representing semantic similarity is used to unify the direction; S55. Sort the candidate code snippet set \(Z = \{z_1, z_2, \ldots, z\) m \} in descending order according to the final sorting score, output the sorted candidate list, and present it to the user through an insertable interactive interface.
Citation Information
Cited By
Multi-scene target detection and behavior recognition method and system based on deep learning
CN121387259A
Multi-scene target detection and behavior recognition method and system based on deep learning
CN121387259B