Code annotation method and device for large model generation function and computer equipment
By constructing a decorative abstract syntax tree and an intelligent decision-making mechanism, and combining it with a large model or local template to generate standardized function comments, the problem of low efficiency and high cost of code commenting in existing technologies is solved. This achieves an efficient and lightweight code commenting method, improving code quality and team collaboration efficiency.
Patent Information
- Application Number
- CN202511754787.5
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-11-26
- Publication Date
- 2026-03-17
AI Technical Summary
Existing code annotation methods for large model generation functions are inefficient, costly, difficult to batch process, and have limited annotation generation effects, failing to meet the needs of improving code quality.
By traversing the code project, performing lexical, syntactic and semantic analysis to construct a decorative abstract syntax tree, identifying the set of functions that need to be annotated, selecting the annotation generation mode according to preset conditions, generating standardized function annotations, and combining large models or local templates to achieve batch annotation supplementation and repair.
It has achieved several orders of magnitude improvement in code commenting efficiency, significantly improved the accuracy and consistency of comments, reduced the cost of code understanding and maintenance, and improved code quality and team collaboration efficiency.
Smart Images

Figure CN121680929A_ABST
Abstract
Description
Technical Field
[0001] This application relates to the field of large model technology, and in particular to a method, apparatus, computer device, computer-readable storage medium, and computer program product for code annotation of large model generation functions. Background Technology
[0002] In software development, code comments are an important tool for improving program readability, maintainability, and team collaboration efficiency. Comments not only help clarify code logic and design intent but also serve as the basis for automatically generating technical documentation. In recent years, code comment coverage has become one of the key indicators for measuring code quality and has received widespread attention from various code quality management platforms.
[0003] Currently, automated code comment generation mainly relies on large code models, such as Comate, TongyiLingma, and ChatGPT. These tools can generate corresponding comments based on function code snippets, but their application still has significant limitations: First, their batch processing capabilities are weak, making it difficult to efficiently comment out all functions in an entire project at once; second, the comment generation effect is limited by the length and context of the input code, often only able to generate simple descriptions based on function names; furthermore, the generation speed is affected by factors such as computing power and network speed, and response latency impacts the development experience; finally, whether calling public cloud APIs or deploying on a private platform, the cost is high, limiting its large-scale application.
[0004] Therefore, there is an urgent need for a code annotation method, apparatus, computer device, computer-readable storage medium, and computer program product for large model generation functions, which can perform more efficient, lightweight, and scalable automated code annotation. Summary of the Invention
[0005] Therefore, it is necessary to provide a method, apparatus, computer device, computer-readable storage medium, and computer program product for generating large model functions that can perform more efficient, lightweight, and scalable automated code annotation, addressing the aforementioned technical problems.
[0006] Firstly, this application provides a method for code annotation of large model generation functions, including:
[0007] Obtain the root directory path of the target code project, and traverse all source code files in the target code project based on the root directory path;
[0008] Each source code file obtained through the traversal is filtered and judged to select a set of source code files to be processed from all source code files. The filtering and judgment methods include at least excluding test files and automatically generating code files.
[0009] For each source code file in the set of source code files to be processed, lexical analysis, syntax analysis, and semantic analysis are performed to construct the decoration abstract syntax tree corresponding to each source code file;
[0010] Based on the aforementioned decoration abstract syntax tree, all function definitions in the corresponding source code file are parsed, and the set of target functions to be annotated is identified from all function definitions.
[0011] Based on the preset annotation generation trigger conditions, an annotation generation mode is selected for each objective function in the objective function set to generate the corresponding normalized function annotation;
[0012] The generated standardized function comments are written into the source code location of the corresponding target function to complete the batch supplementation and repair of function comments in the target code project.
[0013] In one embodiment, identifying the set of target functions to be annotated from all function definitions includes:
[0014] For each function in all the function definitions, determine whether the function is an exported function;
[0015] If the current function is an exported function, check whether the current function has any associated comments;
[0016] If the current function is not associated with any comments, add the current function to the target function set;
[0017] If the current function already has associated comments, perform a standardization check on the comments.
[0018] When the result of the normative verification shows that the comment content does not conform to the preset comment specifications, the current function is added to the target function set.
[0019] In one embodiment, the standardization verification of the annotation content includes:
[0020] Determine whether the comment content contains a function name identifier that conforms to the preset format requirements;
[0021] If the comment content does not contain the function name identifier, or if the contained function name identifier does not match the actual name of the current function, the comment content is determined to be inconsistent with the preset comment specifications.
[0022] In one embodiment, selecting an annotation generation mode for each objective function in the set of objective functions to generate a corresponding normalized function annotation includes:
[0023] If the annotation content does not conform to the preset annotation specifications but contains explanatory text, the explanatory text shall be retained;
[0024] Based on the selected annotation generation mode, generate a normalized function name identifier based on the actual name of the current function;
[0025] The standardized function name identifier is combined with the retained explanatory text to form the standardized function annotation.
[0026] In one embodiment, selecting an annotation generation mode for each objective function in the set of objective functions according to a preset annotation generation trigger condition includes:
[0027] Check whether a large model service interface is configured in the operating environment, and assess whether the current situation meets the preset cost control strategy and response time requirements;
[0028] If the large model service interface is not configured in the operating environment, or if it does not meet the cost control strategy and response time requirements, the local template annotation generation mode shall be uniformly selected for all objective functions in the objective function set.
[0029] If a large model service interface is configured in the operating environment and the cost control strategy and response time requirements are met, the large model annotation generation mode is uniformly selected for all objective functions in the objective function set.
[0030] In one embodiment, selecting an annotation generation mode for each objective function in the set of objective functions to generate a corresponding normalized function annotation includes:
[0031] When the annotation generation mode is the large model annotation generation mode, the function signature, internal logical structure and associated contextual semantic information of the target function are extracted based on the decorative abstract syntax tree.
[0032] The function signature, internal logic structure, and contextual semantic information are encapsulated and organized according to a preset prompt word engineering template to generate structured large model input prompt words;
[0033] Send the input prompts for the large model to the large model service interface and receive the returned initial annotation text;
[0034] The initial annotation text is then standardized and formatted to generate the final standardized function annotation.
[0035] Secondly, this application also provides a code annotation device for large model generation functions, including:
[0036] The acquisition module is used to obtain the root directory path of the target code project and traverse all source code files in the target code project based on the root directory path;
[0037] The filtering module is used to filter and judge each source code file obtained through traversal, so as to filter out the set of source code files to be processed from all source code files. The filtering and judgment methods include at least excluding test files and automatically generating code files.
[0038] The analysis module is used to perform lexical analysis, syntax analysis and semantic analysis on each source code file in the set of source code files to be processed, so as to construct the decoration abstract syntax tree corresponding to each source code file;
[0039] The identification module is used to parse all function definitions in the corresponding source code file based on the decoration abstract syntax tree, and identify the set of target functions to be annotated from all function definitions;
[0040] The selection module is used to select an annotation generation mode for each target function in the target function set according to preset annotation generation trigger conditions, so as to generate corresponding normalized function annotations.
[0041] The annotation module is used to write the generated standardized function annotations into the source code location of the corresponding target function, thereby completing the batch supplementation and repair of function annotations in the target code project.
[0042] Thirdly, this application also provides a computer device, including a memory and a processor, wherein the memory stores a computer program, and the processor executes the computer program to perform the following steps:
[0043] Obtain the root directory path of the target code project, and traverse all source code files in the target code project based on the root directory path;
[0044] Each source code file obtained through the traversal is filtered and judged to select a set of source code files to be processed from all source code files. The filtering and judgment methods include at least excluding test files and automatically generating code files.
[0045] For each source code file in the set of source code files to be processed, lexical analysis, syntax analysis, and semantic analysis are performed to construct the decoration abstract syntax tree corresponding to each source code file;
[0046] Based on the aforementioned decoration abstract syntax tree, all function definitions in the corresponding source code file are parsed, and the set of target functions to be annotated is identified from all function definitions.
[0047] Based on the preset annotation generation trigger conditions, an annotation generation mode is selected for each objective function in the objective function set to generate the corresponding normalized function annotation;
[0048] The generated standardized function comments are written into the source code location of the corresponding target function to complete the batch supplementation and repair of function comments in the target code project.
[0049] Fourthly, this application also provides a computer-readable storage medium having a computer program stored thereon, which, when executed by a processor, performs the following steps:
[0050] Obtain the root directory path of the target code project, and traverse all source code files in the target code project based on the root directory path;
[0051] Each source code file obtained through the traversal is filtered and judged to select a set of source code files to be processed from all source code files. The filtering and judgment methods include at least excluding test files and automatically generating code files.
[0052] For each source code file in the set of source code files to be processed, lexical analysis, syntax analysis, and semantic analysis are performed to construct the decoration abstract syntax tree corresponding to each source code file;
[0053] Based on the aforementioned decoration abstract syntax tree, all function definitions in the corresponding source code file are parsed, and the set of target functions to be annotated is identified from all function definitions.
[0054] Based on the preset annotation generation trigger conditions, an annotation generation mode is selected for each objective function in the objective function set to generate the corresponding normalized function annotation;
[0055] The generated standardized function comments are written into the source code location of the corresponding target function to complete the batch supplementation and repair of function comments in the target code project.
[0056] Fifthly, this application also provides a computer program product, including a computer program that, when executed by a processor, performs the following steps:
[0057] Obtain the root directory path of the target code project, and traverse all source code files in the target code project based on the root directory path;
[0058] Each source code file obtained through the traversal is filtered and judged to select a set of source code files to be processed from all source code files. The filtering and judgment methods include at least excluding test files and automatically generating code files.
[0059] For each source code file in the set of source code files to be processed, lexical analysis, syntax analysis, and semantic analysis are performed to construct the decoration abstract syntax tree corresponding to each source code file;
[0060] Based on the aforementioned decoration abstract syntax tree, all function definitions in the corresponding source code file are parsed, and the set of target functions to be annotated is identified from all function definitions.
[0061] Based on the preset annotation generation trigger conditions, an annotation generation mode is selected for each objective function in the objective function set to generate the corresponding normalized function annotation;
[0062] The generated standardized function comments are written into the source code location of the corresponding target function to complete the batch supplementation and repair of function comments in the target code project.
[0063] The aforementioned methods, devices, computer equipment, computer-readable storage media, and computer program products for generating code comments for large-scale model functions firstly overcome the limitations of traditional manual operations by traversing all source code files and performing batch processing, improving comment completion efficiency by several orders of magnitude and achieving a leap from days of manual work to seconds of automated processing. Secondly, based on deep parsing of the decorator abstract syntax tree, it can accurately extract the function definition structure and deep contextual semantic information, ensuring that the generated comments not only describe the function but also accurately reflect the implementation logic and usage scenarios, significantly improving the accuracy and practicality of the comments. Thirdly, by establishing an intelligent decision-making mechanism through preset comment generation trigger conditions, it dynamically selects the optimal generation path based on the availability, cost control, and response requirements of the large-scale model service, achieving the best balance between quality and cost. Fourthly, through a unified standardization processing mechanism, it can both generate standard comments for functions without comments and intelligently repair existing non-standard comments, ensuring consistent comment style and standardized format throughout the entire code project, directly improving code readability and maintainability. Ultimately, by significantly increasing code comment coverage, the cost of code understanding and maintenance was effectively reduced, team collaboration efficiency was accelerated, and the overall governance level and quality of software engineering were improved. Attached Figure Description
[0064] To more clearly illustrate the technical solutions in the embodiments of this application or related technologies, the drawings used in the description of the embodiments of this application or related technologies will be briefly introduced below. Obviously, the drawings described below are only some embodiments of this application. For those skilled in the art, other related drawings can be obtained based on these drawings without creative effort.
[0065] Figure 1 This is a flowchart illustrating the code annotation method for a large model generation function in one embodiment;
[0066] Figure 2 This is a schematic diagram of the code annotation method for the large model generation function of the conventional technique in the most detailed embodiment;
[0067] Figure 3 This is a schematic diagram of the code annotation method for the large model generation function of this application in the most detailed embodiment;
[0068] Figure 4 This is a schematic diagram illustrating the overall process of generating function comments in seconds in this code project, as shown in the most detailed embodiment.
[0069] Figure 5 This is a flowchart illustrating the process of filtering, supplementing, and correcting the standardization of function comments in the most detailed embodiment.
[0070] Figure 6 A structural block diagram of the code annotation device for a large model generation function in one embodiment;
[0071] Figure 7 This is an internal structural diagram of a computer device in one embodiment. Detailed Implementation
[0072] To make the objectives, technical solutions, and advantages of this application clearer, the following detailed description is provided in conjunction with the accompanying drawings and embodiments. It should be understood that the specific embodiments described herein are merely illustrative and not intended to limit the scope of this application.
[0073] It should be noted that the terms "first," "second," etc., used in this application can be used to describe various elements, but these elements are not limited by these terms. These terms are only used to distinguish the first element from the second element. The terms "comprising" and "having," and any variations thereof, used in this application, are intended to cover non-exclusive inclusion. The term "multiple" used in this application refers to two or more. The term "and / or" used in this application refers to one of the embodiments, or any combination of multiple embodiments.
[0074] In one exemplary embodiment, such as Figure 1 As shown, a code annotation method for a large model generation function is provided. Taking the application of this method to a server as an example, the method includes the following steps S102 to S112. Wherein:
[0075] Step S102: Obtain the root directory path of the target code project, and traverse all source code files in the target code project based on the root directory path.
[0076] Specifically, the first step is to obtain the root directory path of the target code project. This path serves as the logical starting point for the entire codebase and can be specified by the user via command-line arguments, automatically read by the system through a configuration file, or automatically identified by the project configuration file in an integrated development environment. After obtaining the root directory path, the system initiates a recursive traversal of the entire project structure based on this path. This traversal process uses algorithms such as depth-first search or breadth-first search to systematically access the root directory and all its subdirectories, identifying and collecting all source code files for a specific programming language. For example, for a Golang project, files with the ".go" extension will be selected. This automated traversal mechanism, starting from a single entry point, overcomes the traditional operational mode of manually locating and selecting files one by one, achieving a fundamental shift from manual, piecemeal processing to automatic, batch processing. This provides the necessary prerequisites for efficient and unified processing of large-scale code projects, thereby significantly improving the efficiency and consistency of the entire comment completion process.
[0077] Step S104: Filter and judge each source code file obtained by traversal to select the set of source code files to be processed from all source code files. The filtering and judgment methods include at least excluding test files and automatically generating code files.
[0078] Specifically, an intelligent filtering mechanism excludes source code files that do not need or should not generate comments, ensuring that subsequent computing resources are focused on business logic code that truly requires comments. Specifically, this filtering judgment implements multiple filtering logics based on file feature recognition technology: First, the system automatically identifies and excludes test files by analyzing file paths, filename characteristics, and file content; for example, for Golang projects, the system filters test files ending with "-test.go," as these files contain unit tests or performance test code, and their functions typically do not require API documentation comments. Second, the system identifies and excludes automatically generated code files by detecting copyright notices, generator tool identifiers, or specific code generation patterns in the file header; these files are usually automatically generated by protocol buffer compilers, serialization tools, or API frameworks, and their code structure is fixed and already contains basic comments; adding comments is neither necessary nor likely to disrupt their synchronization with the original code. This filtering mechanism is implemented through a configurable rule engine, supporting customized filtering rules according to project needs, such as matching specific filename patterns or directory paths using regular expressions. By using preprocessing, the scope of subsequent syntax analysis and annotation generation is effectively narrowed, avoiding approximately 30%-50% of non-business code processing overhead. This not only significantly improves the overall processing speed but also fundamentally ensures that the generated function annotations are all relevant to the core business logic.
[0079] Step S106: For each source code file in the set of source code files to be processed, perform lexical analysis, syntax analysis and semantic analysis to construct the decoration abstract syntax tree corresponding to each source code file.
[0080] Specifically, the source code is transformed from its raw text form into a structured data model rich in semantic information, providing a deep analytical foundation for subsequent accurate function identification and high-quality annotation generation. The implementation involves a three-tiered analysis process: First, lexical analysis is performed, where a lexical analyzer converts the character sequence of the source code into a sequence of tags with specific categories, identifying basic syntactic units such as keywords, identifiers, operators, and literals. For example, when processing Golang code, it can accurately identify key tags such as "func", "package", and "import". Next, syntax analysis is performed, where the parser constructs an abstract syntax tree (AST) structure based on the programming language's syntax rules. This structure accurately reflects the syntactic hierarchy of the code, where each node represents a syntactic structure, such as function declarations, parameter lists, and control flow statements. Finally, semantic analysis is performed, through traversing the AST and constructing a symbol table, performing type checking, scope analysis, and reference resolution to form a decorated AST. This decoration process adds rich semantic information to the original AST nodes, including but not limited to the specific types of variables, function call relationships, identifier binding information, and expression evaluation methods.
[0081] Step S108: Based on the decoration abstract syntax tree, parse all function definitions in the corresponding source code file and identify the set of target functions to be annotated from all function definitions.
[0082] Specifically, by traversing the decorator abstract syntax tree, all function declaration nodes are located, and complete definition information for each function is extracted, including function name, parameter list, return type, receiver information, and function body structure. This parsing process fully utilizes the type binding and symbolic reference relationships already established in the decorator abstract syntax tree, accurately distinguishing function definitions from other similar structures. Based on obtaining all function definitions, the system executes multi-level identification logic to determine the target set of functions that need additional annotations: First, the system identifies exported functions according to the visibility rules of programming languages, i.e., public functions with a capital first letter in Golang. These functions constitute part of the API and are the primary targets for annotation generation. Second, for each exported function, the system checks the status of its associated documentation comments, including cases where comments are completely missing, contain only single-line comments, or contain comments that do not conform to the standard format. More importantly, by analyzing the relationship between comment nodes and function declaration nodes in the decorator abstract syntax tree, the system can identify functions that, although containing comment text, do not meet the preset specification requirements, such as comments lacking a standard function name start identifier or not matching the actual function name.
[0083] Step S110: Based on the preset annotation generation trigger conditions, select an annotation generation mode for each objective function in the objective function set to generate the corresponding normalized function annotation.
[0084] Specifically, the system first evaluates the preset annotation generation trigger conditions, which constitute a multi-dimensional decision matrix. These conditions include detecting the availability and current response latency of the large model service interface in the runtime environment, assessing whether the computational cost of batch processing tasks exceeds a preset threshold, considering the balance between generation speed requirements and expected quality standards, and analyzing the complexity and contextual dependencies of the objective function itself. Based on the comprehensive evaluation of these conditions, the system uniformly selects the most suitable annotation generation mode for the entire set of objective functions. That is, when high-quality annotations are required and large model resources are sufficient, the large model annotation generation mode is selected to obtain semantically rich and accurately descriptive annotation content; while in scenarios with limited resources or where extreme efficiency is pursued, the local template annotation generation mode is enabled to quickly generate standard annotations that conform to the specifications through predefined annotation templates.
[0085] Step S112: Write the generated standardized function comments into the source code location of the corresponding target function to complete the batch supplementation and repair of function comments in the target code project.
[0086] Specifically, firstly, the system locates the exact insertion point of each target function in the source code based on recorded function location information, including filename, line number, and character offset. This process requires precise positioning by combining the location information stored in the decorator abstract syntax tree with the text structure of the source code. Secondly, during the writing process, the system needs to maintain the original format and style consistency of the source code, including correctly handling indentation, line breaks, and the retention or removal of existing comments. For example, when fixing non-standard comments, the system will retain the valid explanatory text in the original comments, only replacing or supplementing the non-standard parts, rather than simply overwriting the entire comment block. For batch processing scenarios, the system adopts a transactional writing mechanism, creating a backup before writing to ensure that it can roll back to the original state in case of errors, ensuring code integrity. At the same time, the system supports an incremental update strategy, modifying only the function locations that need to be supplemented or repaired with comments, avoiding unnecessary impact on other parts of the file.
[0087] The above-mentioned method for generating code comments for large-scale model functions firstly overcomes the limitations of traditional manual operations by traversing all source code files and performing batch processing, improving comment completion efficiency by several orders of magnitude and achieving a leap from days of manual work to seconds of automation. Secondly, based on deep parsing of the decorator abstract syntax tree, it can accurately extract the function definition structure and deep contextual semantic information, ensuring that the generated comments not only describe the function but also accurately reflect the implementation logic and usage scenarios, significantly improving the accuracy and practicality of the comments. Thirdly, an intelligent decision-making mechanism is established through preset comment generation trigger conditions, dynamically selecting the optimal generation path based on the availability, cost control, and response requirements of the large-scale model service, achieving the best balance between quality and cost. Fourthly, through a unified standardization processing mechanism, it can generate standardized comments for functions without comments and intelligently repair existing non-standard comments, ensuring consistent comment style and standardized format throughout the entire code project, directly improving code readability and maintainability. Finally, by significantly improving code comment coverage, it effectively reduces code understanding and maintenance costs, accelerates team collaboration efficiency, and improves the overall governance level and quality of software engineering.
[0088] In one embodiment, the set of target functions to be annotated is identified from all function definitions, including:
[0089] For each function in all function definitions, determine whether the function is an exported function;
[0090] If the current function is an exported function, check whether the current function has any associated comments;
[0091] If the current function is not associated with any comments, add the current function to the target function set;
[0092] If the current function already has associated comments, perform a standardization check on the comments.
[0093] When the result of the normative verification shows that the comment content does not conform to the preset comment specifications, the current function is added to the target function set.
[0094] Specifically, based on the semantic information provided by the decorator abstract syntax tree, the system first determines whether each function is an exported function. Exported functions constitute the public API of a package and are its contract for interacting with external code; therefore, they are the primary target for documentation. Non-exported functions, as internal implementation details, can have their comment requirements appropriately reduced. For identified exported functions, the system further checks their current comment association status. By analyzing the positional relationship and syntactic association between comment nodes and function declaration nodes in the abstract syntax tree, the system accurately determines whether a function has associated comment content. If a function is completely missing comments, it is directly included in the target set for supplementation; this is the most basic and necessary processing scenario. For functions that already have associated comments, the system initiates a deeper standardization verification process. This step reflects intelligent features that go beyond simple "existence or absence judgment." Standardization verification is not simply checking whether comments exist or not, but rather verifying the format, structure, and completeness of the comment content based on preset comment specifications. For example, in Golang, comments for exported functions must begin with the function name. When the verification finds that the comment content does not meet the standard requirements, such as the comment being only a short description on a single line without a standard function name prefix, or the comment content being significantly inconsistent with the actual function, the system will include the function in the target set for standardization correction.
[0095] In this embodiment, this hierarchical identification mechanism ensures that the final target function set includes both all derived functions that need additional annotations and those functions that have annotations but are of substandard quality. This provides accurate input for subsequent batch annotation generation and repair, ensuring the achievement of both the coverage and standardization goals of code annotations from the source.
[0096] In one embodiment, the annotation content is subjected to normative verification, including:
[0097] Determine whether the comment content contains a function name identifier that meets the preset format requirements;
[0098] If the comment does not contain a function name identifier, or if the function name identifier does not match the actual name of the current function, the comment is deemed not to conform to the preset comment specifications.
[0099] Specifically, the system first extracts the actual name identifier of the current function from the decoration abstract syntax tree. Then, it performs structured parsing on the associated comment content, checking whether it contains a function name identifier that conforms to the preset format requirements. This preset format requirement is usually based on the official documentation specifications or project conventions of the specific programming language. For example, in Golang, comments for exported functions should start with the function name, in the form of " / / FunctionName Description". The system uses text matching and pattern recognition algorithms to detect whether such an identifier structure exists at the beginning of the comment content. When two typical cases occur, the system will determine that the comment content does not conform to the preset comment specifications: one is that the comment content does not contain a function name identifier at all, such as only containing the descriptive text " / / Handle user requests" without the preceding function name "LoginHandler"; the other is that the function name identifier contained in the comment content does not match the actual name of the current function, for example, the actual function name is "ValidateEmail", but the comment starts with " / / ValidateUserEmail Validate email address". This inconsistency will cause errors in the automatically generated API documentation.
[0100] In this embodiment, this refined standardization verification mechanism can effectively identify comments that appear complete but do not actually conform to engineering standards, ensuring that all comments in the final codebase are not only readable by humans, but also accurately parsed and presented by automated documentation tools such as godoc, thereby improving the professionalism of the entire code project and the compatibility of the toolchain.
[0101] In one embodiment, a comment generation mode is selected for each objective function in the set of objective functions to generate corresponding normalized function comments, including:
[0102] If the annotation content does not conform to the preset annotation specifications but contains explanatory text, retain the explanatory text;
[0103] Based on the selected annotation generation mode, generate a normalized function name identifier based on the actual name of the current function;
[0104] The standardized function name identifier is combined with the retained explanatory text to form a standardized function comment.
[0105] Specifically, when the system detects that a function's comment, while not conforming to preset formatting specifications, contains meaningful explanatory text—for example, the comment might lack the required function name prefix but contain important descriptions of the function's internal logic, parameter meanings, or boundary conditions—the system will initiate this intelligent repair process. First, the system uses natural language processing or rule-based text analysis to identify and extract semantically valuable explanatory text from the original comment. This text typically contains key descriptions of function behavior, algorithm implementation, or business logic, representing valuable knowledge assets accumulated by developers during the initial coding process. Next, based on the rules corresponding to the currently selected comment generation mode and the actual function name obtained from the decorator abstract syntax tree, the system automatically generates a standardized function name identifier that conforms to preset formatting requirements. For example, in the Golang specification, this usually means generating a standard prefix starting with the function name. Finally, the system uses an intelligent text combination algorithm to seamlessly combine the newly generated standardized function name identifier with the retained explanatory text extracted from the original comment, forming a final comment that conforms to engineering specifications while preserving the original knowledge content.
[0106] In this embodiment, this processing mechanism not only standardizes the annotation format, but more importantly, by preserving and integrating the original explanatory content, the generated standardized function annotations maintain consistency in format and inherit historically accumulated code knowledge, significantly improving the accuracy and practicality of annotation updates and avoiding common problems of information loss and semantic gaps in automated processing.
[0107] In one embodiment, based on preset annotation generation trigger conditions, an annotation generation mode is selected for each objective function in the objective function set, including:
[0108] Check whether a large model service interface is configured in the operating environment, and assess whether the current situation meets the preset cost control strategy and response time requirements;
[0109] If the large model service interface is not configured in the operating environment, or if it does not meet the cost control strategy and response time requirements, select the local template annotation generation mode for all objective functions in the objective function set.
[0110] When the runtime environment has a large model service interface configured and meets the cost control strategy and response time requirements, the large model annotation generation mode is uniformly selected for all objective functions in the objective function set.
[0111] Specifically, the system first performs a deep inspection of the operating environment. This includes verifying the network connectivity, authentication status, and service health of the large model service interface to ensure its availability. Simultaneously, the system needs to assess in real-time whether the current task meets the preset cost control strategy and response time requirements. The cost control strategy involves calculating the token consumption of a single API call, estimating the total cost of batch processing, and comparing it with a preset budget threshold. The response time requirement involves estimating the overall processing time of the large model mode based on the number of functions to be processed and code complexity, and determining whether it meets the time constraints set by the user or the system. When the environment inspection indicates that an available large model service interface is not configured, the cost assessment exceeds the control threshold, or the expected response time cannot meet the requirements, the system will uniformly select the local template annotation generation mode for the entire set of target functions. This mode, through predefined annotation templates and function signature filling mechanisms, can quickly generate annotations that conform to basic specifications without network dependencies and with low computational overhead, ensuring the system's basic availability and processing efficiency in resource-constrained environments. Conversely, when the runtime environment has available large model service interfaces and the cost assessment and response time prediction meet the preset requirements, the system will uniformly select the large model annotation generation mode to make full use of the large model's deep understanding of code semantics to generate high-quality annotations that are rich in content and accurate in context.
[0112] In this embodiment, by adopting a unified mode selection strategy, that is, using a single generation mode for the entire set of objective functions instead of making decisions for each function, the overhead of mode switching is effectively reduced, the consistency and predictability of the processing flow are guaranteed, and the optimal balance between efficiency and quality, cost and effect is achieved while ensuring system robustness.
[0113] In one embodiment, a comment generation mode is selected for each objective function in the set of objective functions to generate corresponding normalized function comments, including:
[0114] When the annotation generation mode is the large model annotation generation mode, the function signature, internal logical structure and associated contextual semantic information of the target function are extracted based on the decoration abstract syntax tree.
[0115] The function signature, internal logic structure, and contextual semantic information are encapsulated and organized according to the preset prompt word engineering template to generate structured large model input prompt words;
[0116] Send the input prompts for the large model to the large model service interface and receive the returned initial annotation text;
[0117] The initial comment text is corrected and formatted to generate the final standardized function comments.
[0118] Specifically, the system first comprehensively extracts multi-dimensional features of the target function based on the decorator abstract syntax tree, a structured representation rich in semantic information. This includes accurately extracting interface information such as the function name, parameter list, and return type from the function signature; deeply analyzing the internal implementation details such as the control flow structure, key algorithm steps, and exception handling logic within the function body; and utilizing the symbolic associations established during the decoration process to extract the function's call relationships, type dependencies, and business scenario semantics within a larger code context. These deeply analyzed code features are then systematically encapsulated according to a pre-defined prompt word engineering template. This template is specially designed to organize discrete code elements into structured prompt words that conform to the understanding habits of large models, such as using a segmented structure of "function definition - core logic - context association - comment requirements" to ensure the completeness of input information and the accuracy of model parsing. After sending the constructed prompt words to the large model service interface, the system receives the returned initial comment text. Although this text contains rich semantic content, it may have deficiencies in terms of formatting specifications, terminology consistency, or style uniformity. Therefore, the system will perform strict standardization and formatting corrections on it, including but not limited to: ensuring that comments begin with a standard function name identifier, adjusting the structure of comment paragraphs to conform to project conventions, standardizing the use of professional terminology, and removing any potentially redundant descriptions.
[0119] In this embodiment, the original text output by the large model is transformed into standardized function annotations that truly conform to engineering standards. This ensures that the generated results possess both the semantic richness brought by the large model and the standardization required for industrial applications, thereby achieving an effective integration of artificial intelligence capabilities and software engineering practices.
[0120] The most detailed embodiment of this application is as follows:
[0121] 1. Existing solutions based on large model-generated function annotations:
[0122] The current overall approach for generating function comments using large code models is as follows: Figure 2 As shown:
[0123] The solution is described below:
[0124] (1) Developers install the code big model plugin in commonly used code development tools (vscode, IntelliJ IDEA, etc.).
[0125] (2) During the development process, it was found that some existing functions were missing comments. Function comments were generated by accessing the code big model through the plugin.
[0126] (3) The large model plugin will process the passed-in function through a certain prompt project and then pass it into the code large model to generate function comments.
[0127] (4) After the annotation is generated, the annotation is returned to the large model plugin to display the generated result.
[0128] (5) Developers paste the generated comments at the beginning of the function code. Of course, during the development process, the auto-completion tool of the large model plugin can also be used to automatically generate comments at the beginning of the function.
[0129] 2. Technical solution for generating function comments in seconds in Golang code projects:
[0130] This application's embodiment provides an overall scheme for generating function comments in Golang code projects, as follows: Figure 3 As shown:
[0131] (1) Use a function code comment auto-completion tool to analyze the Golang code project and filter out the functions that need code completion. The filtered content includes: test files, automatically generated files, and functions that conform to the comment specifications.
[0132] (2) Classify the filtered functions and adopt different function supplementation methods.
[0133] (3) Depending on whether a large model is accessible, decide whether to access the large model to generate function comments. If there is no large model, generate code comments directly according to the locally configured template format.
[0134] (4) In the case of a large model, the tool will process the functions that need to be annotated and completed through the prompt project, and then send them to the configured large model to generate annotations.
[0135] (5) After the comments are generated, write the comments back to the code file.
[0136] The overall process is as follows Figure 4 As shown:
[0137] (1) Build a Golang function annotation automatic generation tool that supports passing in the file path of the code project.
[0138] (2) The tool will automatically recursively traverse all files in the Golang code project.
[0139] (3) First, determine whether the file needs to be processed. If the file does not need to be processed, proceed to the next file. Files that do not need to be processed include: automatically generated files, test files, etc.
[0140] (4) For files that need to be processed, use lexical analysis and syntax analysis tools to generate an abstract syntax tree (AST).
[0141] (5) Then, semantic analysis is performed on the abstract syntax tree (AST) to generate a decorated abstract syntax tree (DecoratedAST).
[0142] (6) Analyze whether the function code blocks in the file need to be commented out based on the Decorated Abstract Syntax Tree (DecoratedAST).
[0143] (7) If the function code block has no comments or the comments do not conform to the specifications, the function needs to be commented to complete the comments.
[0144] (8) Depending on whether there is a large model available, choose to generate comments by using a locally configured comment template or by accessing a large model to generate code comments.
[0145] The process for filtering functions that require additional comments is as follows: Figure 5 As shown:
[0146] The process is explained as follows:
[0147] (1) Filter files that do not require comments. For example, test files and automatically generated code files. To determine how to determine which files need to be filtered, please refer to the implementation process below.
[0148] (2) Analyze all function code blocks in the file and determine whether the function is an exported function. In Golang code style, exported functions need to be commented.
[0149] (3) For the exported function, determine whether it already has comments. If not, use the large model or local template to supplement the function comments.
[0150] (4) If the function already has comments, check if the comments conform to the specifications. If they do, skip the function.
[0151] (5) If a function already has comments that do not conform to the specification, then the missing specification is checked. In the Golang code specification, the format of a function comment is: " / / function name function explanation".
[0152] (6) Determine if the function's existing comments only contain the function name prefix. If only the function name is present, supplement the function comments using the large model or local template.
[0153] (7) If there is no function name or the function name does not conform to the standard format, remove the non-standard function name first. Then add the function name to the existing comment according to the standard format.
[0154] It should be understood that although the steps in the flowcharts of the embodiments described above are shown sequentially according to the arrows, these steps are not necessarily executed in the order indicated by the arrows. Unless explicitly stated herein, there is no strict order restriction on the execution of these steps, and they can be executed in other orders. Moreover, at least some steps in the flowcharts of the embodiments described above may include multiple steps or multiple stages. These steps or stages are not necessarily completed at the same time, but can be executed at different times. The execution order of these steps or stages is not necessarily sequential, but can be performed alternately or in turn with other steps or at least some of the steps or stages of other steps.
[0155] Based on the same inventive concept, this application also provides a code annotation apparatus for implementing the code annotation method for large model generation functions as described above. The solution provided by this apparatus is similar to the implementation described in the above method; therefore, the specific limitations of one or more code annotation apparatus embodiments for large model generation functions provided below can be found in the limitations of the code annotation method for large model generation functions described above, and will not be repeated here.
[0156] In one exemplary embodiment, such as Figure 6 As shown, a code annotation device for a large model generation function is provided, including:
[0157] The acquisition module 602 is used to obtain the root directory path of the target code project and traverse all source code files in the target code project based on the root directory path;
[0158] The filtering module 604 is used to filter and judge each source code file obtained by traversal in order to filter out the set of source code files to be processed from all source code files. The filtering and judgment methods include at least excluding test files and automatically generating code files.
[0159] Analysis module 606 is used to perform lexical analysis, syntax analysis and semantic analysis on each source code file in the set of source code files to be processed, so as to construct the decoration abstract syntax tree corresponding to each source code file;
[0160] The identification module 608 is used to parse all function definitions in the corresponding source code file based on the decoration abstract syntax tree, and identify the set of target functions to be annotated from all function definitions;
[0161] The selection module 610 is used to select an annotation generation mode for each objective function in the objective function set according to the preset annotation generation trigger conditions, so as to generate the corresponding normalized function annotation.
[0162] The annotation module 612 is used to write the generated standardized function annotations into the source code location of the corresponding target function, thereby completing the batch supplementation and repair of function annotations in the target code project.
[0163] In an exemplary embodiment, the identification module 608 is specifically used to determine whether each function in all function definitions is an exported function; if the current function is an exported function, it detects whether the current function is associated with comments; if the current function is not associated with comments, it adds the current function to the target function set; if the current function is associated with comments, it performs a standardization check on the comments; when the standardization check result shows that the comments do not conform to the preset comment standard, it adds the current function to the target function set.
[0164] In an exemplary embodiment, the identification module 608 is specifically used to determine whether the comment content contains a function name identifier that conforms to the preset format requirements; if the comment content does not contain a function name identifier, or the function name identifier contained therein does not match the actual name of the current function, it is determined that the comment content does not conform to the preset comment specifications.
[0165] In an exemplary embodiment, the selection module 610 is specifically used to retain the explanatory text when the annotation content does not conform to the preset annotation specification but contains explanatory text; generate a standardized function name identifier based on the actual name of the current function according to the selected annotation generation mode; and combine the standardized function name identifier with the retained explanatory text to form a standardized function annotation.
[0166] In an exemplary embodiment, the selection module 610 is specifically used to detect whether a large model service interface is configured in the runtime environment, and to assess whether the current situation meets the preset cost control strategy and response time requirements; if a large model service interface is not configured in the runtime environment, or if the cost control strategy and response time requirements are not met, the local template annotation generation mode is uniformly selected for all objective functions in the objective function set; if a large model service interface is configured in the runtime environment and the cost control strategy and response time requirements are met, the large model annotation generation mode is uniformly selected for all objective functions in the objective function set.
[0167] In an exemplary embodiment, the selection module 610 is configured to, when the annotation generation mode is the large model annotation generation mode, extract the function signature, internal logical structure, and associated contextual semantic information of the target function based on the decoration abstract syntax tree; encapsulate and organize the function signature, internal logical structure, and contextual semantic information according to a preset prompt word engineering template to generate structured large model input prompt words; send the large model input prompt words to the large model service interface and receive the returned initial annotation text; perform standardization and format standardization processing on the initial annotation text to generate the final standardized function annotation.
[0168] Each module in the code annotation device for the aforementioned large model generation function can be implemented entirely or partially through software, hardware, or a combination thereof. These modules can be embedded in or independent of the processor in a computer device, or stored in the memory of a computer device in software form, so that the processor can call and execute the operations corresponding to each module.
[0169] In one exemplary embodiment, a computer device is provided, which may be a server, and its internal structure diagram may be as follows: Figure 7 As shown, this computer device includes a processor, memory, input / output (I / O) interfaces, and a communication interface. The processor, memory, and I / O interfaces are connected via a system bus, and the communication interface is also connected to the system bus via the I / O interfaces. The processor provides computational and control capabilities. The memory includes non-volatile storage media and internal memory. The non-volatile storage media stores the operating system, computer programs, and a database. The internal memory provides the environment for the operating system and computer programs stored in the non-volatile storage media. The database stores source code files. The I / O interfaces are used for exchanging information between the processor and external devices. The communication interface is used for communication with external terminals via a network connection. When executed by the processor, the computer program implements a code annotation method for a large model generation function.
[0170] Those skilled in the art will understand that Figure 7 The structure shown is merely a block diagram of a portion of the structure related to the present application and does not constitute a limitation on the computer device to which the present application is applied. Specific computer devices may include more or fewer components than those shown in the figure, or combine certain components, or have different component arrangements.
[0171] In one exemplary embodiment, a computer device is provided, including a memory and a processor, wherein the memory stores a computer program, and the processor executes the computer program to implement the steps of the method described above.
[0172] In one embodiment, a computer-readable storage medium is provided having a computer program stored thereon, which, when executed by a processor, implements the steps of the above-described method.
[0173] In one embodiment, a computer program product is provided, including a computer program that, when executed by a processor, implements the steps of the method described above.
[0174] It should be noted that the user information (including but not limited to user device information, user personal information, etc.) and data (including but not limited to data used for analysis, data stored, data displayed, etc.) involved in this application are all information and data authorized by the user or fully authorized by all parties, and the collection, use and processing of the relevant data must comply with relevant regulations.
[0175] Those skilled in the art will understand that all or part of the processes in the methods of the above embodiments can be implemented by a computer program instructing related hardware. The computer program can be stored in a non-volatile computer-readable storage medium, and when executed, it can include the processes of the embodiments of the above methods. Any references to memory, databases, or other media used in the embodiments provided in this application can include at least one of non-volatile memory and volatile memory. Non-volatile memory can include read-only memory (ROM), magnetic tape, floppy disk, flash memory, optical memory, high-density embedded non-volatile memory, resistive random access memory (ReRAM), magnetic random access memory (MRAM), ferroelectric random access memory (FRAM), phase change memory (PCM), graphene memory, etc. Volatile memory can include random access memory (RAM) or external cache memory, etc. By way of illustration and not limitation, RAM can take many forms, such as Static Random Access Memory (SRAM) or Dynamic Random Access Memory (DRAM). The databases involved in the embodiments provided in this application may include at least one type of relational database and non-relational database. Non-relational databases may include, but are not limited to, blockchain-based distributed databases. The processors involved in the embodiments provided in this application may be general-purpose processors, central processing units, graphics processing units, digital signal processors, programmable logic devices, quantum computing-based data processing logic devices, artificial intelligence (AI) processors, etc., and are not limited to these.
[0176] The technical features of the above embodiments can be combined in any way. For the sake of brevity, not all possible combinations of the technical features in the above embodiments are described. However, as long as there is no contradiction in the combination of these technical features, they should be considered to be within the scope of this application.
[0177] The embodiments described above are merely illustrative of several implementation methods of this application, and while the descriptions are specific and detailed, they should not be construed as limiting the scope of this patent application. It should be noted that those skilled in the art can make various modifications and improvements without departing from the concept of this application, and these all fall within the protection scope of this application. Therefore, the protection scope of this application should be determined by the appended claims.
Claims
1. A method for generating code annotations of a function of a large model, the method comprising: The method comprises: obtaining a root directory path of a target code project, and traversing all source code files in the target code project based on the root directory path; filtering and judging each source code file obtained through traversal to screen out a set of source code files to be processed from all source code files, wherein the filtering and judging mode at least includes excluding test files and automatically generated code files; for each source code file in the set of source code files to be processed, performing lexical analysis, syntax analysis and semantic analysis to construct a decorated abstract syntax tree corresponding to each source code file; based on the decorated abstract syntax tree, parsing all function definitions in the corresponding source code file, and identifying a set of target functions to be supplemented with annotations from all function definitions; according to a preset annotation generation trigger condition, selecting an annotation generation mode for each target function in the set of target functions to generate a corresponding normalized function annotation; writing the generated normalized function annotation into the source code position of the corresponding target function, completing batch supplement and repair of function annotations of the target code project.
2. The method of claim 1, wherein, The set of target functions to be supplemented with annotations from all function definitions comprises: for each function in the set of target functions, determining whether the function is an exported function; in the case that the current function is an exported function, detecting whether the current function is associated with annotation content; in the case that the current function is not associated with annotation content, adding the current function to the set of target functions; in the case that the current function is associated with annotation content, performing a normative check on the annotation content; when the result of the normative check indicates that the annotation content does not conform to the preset annotation specification, adding the current function to the set of target functions.
3. The method of claim 2, wherein, The normative check on the annotation content comprises: determining whether the annotation content contains a function name identifier that conforms to a preset format requirement; in the case that the annotation content does not contain the function name identifier, or the contained function name identifier does not match the actual name of the current function, determining that the annotation content does not conform to the preset annotation specification.
4. The method of claim 3, wherein, The selection of an annotation generation mode for each target function in the set of target functions to generate a corresponding normalized function annotation comprises: in the case that the annotation content does not conform to the preset annotation specification but contains explanatory text, retaining the explanatory text; generating a normalized function name identifier based on the actual name of the current function according to the selected annotation generation mode; combining the normalized function name identifier and the retained explanatory text to form the normalized function annotation.
5. The method of claim 1, wherein, The selection of an annotation generation mode for each target function in the set of target functions according to a preset annotation generation trigger condition comprises: detecting whether a large model service interface is configured in the running environment, and evaluating whether the current condition conforms to a preset cost control strategy and response time requirement; in the case that the large model service interface is not configured in the running environment, or the cost control strategy and response time requirement are not met, uniformly selecting a local template annotation generation mode for all target functions in the set of target functions. In the running environment, the large model service interface is configured, and the cost control strategy and the response time requirement are met. The large model annotation generation mode is uniformly selected for all target functions in the target function set.
6. The method of claim 5, wherein, The annotation generation mode is selected for each target function in the target function set to generate corresponding normalized function annotations, including: In the case of the large model annotation generation mode, the function signature, internal logic structure, and associated context semantic information of the target function are extracted based on the decorated abstract syntax tree; The function signature, internal logic structure, and context semantic information are encapsulated and organized according to the preset prompt word engineering template to generate structured large model input prompts; The large model input prompts are sent to the large model service interface, and the returned initial annotation text is received; The initial annotation text is corrected and standardized to generate the final normalized function annotation. 7.A device for generating code annotations of a function of a large model, the device comprising: The device comprises: An acquisition module is configured to acquire a root directory path of a target code project and traverse all source code files in the target code project based on the root directory path; A screening module is configured to filter and judge each source code file obtained by traversal to screen a set of source code files to be processed from all source code files, wherein the filtering and judging manner at least includes excluding test files and automatically generated code files; An analysis module is configured to perform lexical analysis, syntax analysis, and semantic analysis on each source code file in the set of source code files to be processed to construct a decorated abstract syntax tree corresponding to each source code file; An identification module is configured to parse all function definitions in the corresponding source code file based on the decorated abstract syntax tree and identify a set of target functions to be supplemented from all function definitions; A selection module is configured to select an annotation generation mode for each target function in the set of target functions according to a preset annotation generation trigger condition to generate corresponding normalized function annotations; An annotation module is configured to write the generated normalized function annotations into the source code positions of the corresponding target functions to complete batch supplement and repair of function annotations of the target code project.
8. A computer device comprising a memory and a processor, the memory storing a computer program, characterized in that, The processor executes the computer program to implement the steps of the method of any one of claims 1 to 6.
9. A computer readable storage medium having stored thereon a computer program, characterized in that, The computer program is executed by the processor to implement the steps of the method of any one of claims 1 to 6.
10. A computer program product comprising a computer program, characterized in that, The computer program is executed by the processor to implement the steps of the method of any one of claims 1 to 6.