Intelligent analysis method, system, equipment and program product for automatic code review
By using a large language model for code semantic understanding and cross-platform comparison, the problem of code review tools being unable to understand code semantics and cross-terminal logical consistency is solved, achieving efficient and accurate code review and risk detection, and reducing labor costs.
Patent Information
- Application Number
- CN202511247632.2
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-09-02
- Publication Date
- 2025-12-19
AI Technical Summary
Existing code review tools cannot understand code semantics, making it difficult to ensure cross-terminal code logic consistency. Manual review is inefficient and struggles to identify potential performance bottlenecks and security vulnerabilities.
It leverages large language models for deep semantic understanding and cross-platform automated code comparison. By acquiring code difference data, it preprocesses the data to generate semantic code units, dynamically constructs structured prompt words, identifies logically equivalent and non-equivalent changes, and generates visual reports.
It improves the efficiency, accuracy, and risk control capabilities of code review, automates the detection of cross-terminal API compatibility and potential security vulnerabilities, reduces labor costs, and achieves standardized review.
Smart Images

Figure CN121166514A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of computer software engineering and development tools technology, and in particular to an intelligent analysis method, system, device and program product for automated code review. Background Technology
[0002] With the increasing complexity and faster iteration speed of software development, code review plays a crucial role in the software development lifecycle as a means of ensuring software quality. Traditional code review methods rely on manual work, which is inefficient and prone to errors. Existing code comparison tools are mainly based on textual difference detection and cannot understand the semantic information of the code, resulting in a large number of false positives for logically equivalent code changes such as variable name modifications and function refactorings, thus increasing the burden on reviewers.
[0003] In multi-platform collaborative development scenarios such as iOS and Android, the differences between programming languages like Swift / Objective-C, Kotlin / Java, and platform application programming interface APIs make it difficult to ensure cross-platform code logic consistency manually, increasing the risk of introducing compatibility issues. Furthermore, in the face of continuous integration code merging requests, purely manual review is insufficient to uncover potential performance bottlenecks and security vulnerabilities.
[0004] In recent years, artificial intelligence technology has been applied in the field of software development, such as code auto-completion and code generation. However, in the code review process, especially in terms of deep semantic understanding and automated cross-platform comparison analysis of code changes, the technology is still immature. Therefore, there is an urgent need for a technical solution that can understand code semantics and automatically perform cross-platform logical consistency verification and risk assessment to improve the efficiency and quality of code review.
[0005] It should be noted that the information disclosed in the background section above is only used to enhance the understanding of the background of the present invention, and therefore may include information that does not constitute prior art known to those skilled in the art. Summary of the Invention
[0006] In view of this, the present invention provides an intelligent analysis method, system, device and program product for automated code review, which aims to solve the problems of traditional code review tools being unable to understand code semantics, difficulty in ensuring cross-terminal code logic consistency and insufficient efficiency and depth of manual review in the prior art. By using a large language model to perform deep semantic understanding of code and cross-platform automated comparison, the present invention improves code review efficiency, enhances code review accuracy and strengthens risk prevention and control capabilities.
[0007] This invention provides an intelligent analysis method for automated code review, comprising:
[0008] Obtain code difference data resulting from target code changes;
[0009] The code difference data is preprocessed to generate semantic code units. The preprocessing includes filtering non-code files and semantic segmentation of code difference fragments.
[0010] Based on preset review rules, structured prompt words for input into the large language model are dynamically constructed. The structured prompt words include review rules, old and new versions of code corresponding to semantic code units, and code context information.
[0011] The large language model is invoked to process structured prompts to identify logically equivalent and non-equivalent changes in code modifications, and risk points in the code are marked based on review rules.
[0012] Based on the recognition and annotation results of the large language model, a visual report is generated that includes differential classification statistics and risk point distribution.
[0013] In some optional embodiments, obtaining code difference data includes:
[0014] By calling the application programming interface of the version control system, the difference file corresponding to the target commit or merge request can be extracted.
[0015] In some optional embodiments, it also includes:
[0016] Based on the preset code repository mapping relationship, multiple code repositories deployed on different terminals are automatically associated to obtain cross-platform code difference data generated to implement the same business function.
[0017] In some optional embodiments, semantic segmentation of the code difference segments includes:
[0018] By using an abstract syntax tree parser for the programming language, code differences are segmented into semantic code units bounded by class or function definitions.
[0019] In some optional embodiments, the preprocessing further includes:
[0020] Static dependency analysis is performed on each semantic code unit to identify the external functions it calls or the external classes it references.
[0021] In some optional embodiments, the preprocessing further includes:
[0022] The interface definition of external functions or classes is attached as a cross-file dependency tag to the corresponding semantic code unit as part of the code context information.
[0023] In some alternative embodiments, structured prompts are constructed dynamically, including:
[0024] Read the pre-defined review rules from the rule base stored in a machine-readable format.
[0025] In some alternative embodiments, dynamically constructing structured prompts further includes:
[0026] The technical review indicators read from the rule base are transformed into a set of natural language instructions to constrain the analysis behavior of the large language model, and the set of natural language instructions is placed into structured prompt words.
[0027] In some optional embodiments, the structured prompts also include semantic guidelines for distinguishing between logically equivalent refactoring and functionally non-equivalent changes, as well as instructions requiring the large language model to follow a preset structured format for its output.
[0028] In some alternative embodiments, risk points in the code are marked, including:
[0029] At least one of the following should be noted: API compatibility risk, security risk, or performance risk.
[0030] In some optional embodiments, when the code difference data contains multiple independent semantic code units, a large language model is invoked for processing, including:
[0031] The large language model is invoked in parallel for multiple independent semantic code units to perform analysis.
[0032] In some optional embodiments, when the code difference data contains multiple interrelated semantic code units, a large language model is invoked for processing, including:
[0033] The first semantic code unit is analyzed to generate a function change summary, and when analyzing subsequent associated semantic code units, the function change summary is injected as additional contextual information into the corresponding structured prompt words.
[0034] In some optional embodiments, the method is applied to cross-language platform code logic consistency verification and further includes:
[0035] Specific instructions are added to the structured prompts to instruct the large language model to ignore the syntactic differences between the first and second programming languages and focus on comparing the consistency of its core algorithm logic.
[0036] In some optional embodiments, generating a visualization report includes:
[0037] Generate a risk heatmap, based on file or terminal dimensions, to characterize the distribution density of risk points.
[0038] In some optional embodiments, generating a visualization report further includes:
[0039] For the identified key risk points, we provide code snippets with highlights and correction suggestions generated by a large language model.
[0040] This invention provides an intelligent analysis system for automated code review, comprising:
[0041] The data acquisition module is used to acquire code difference data resulting from changes to the target code;
[0042] An intelligent preprocessing engine is used to preprocess code difference data to generate semantic code units. The preprocessing engine is configured to filter non-code files and perform semantic segmentation on code difference fragments.
[0043] The dynamic prompt word constructor is used to dynamically construct structured prompt words for input into the large language model according to preset review rules. The structured prompt words include review rules, old and new versions of code corresponding to semantic code units, and code context information.
[0044] The AI large model analysis layer is used to call a large language model to process structured prompt words in order to identify logically equivalent and non-equivalent changes in code changes, and to mark risk points in the code based on review rules.
[0045] A visualization report generator that generates visualization reports containing differential classification statistics and risk point distribution based on the recognition and annotation results of a large language model.
[0046] In some optional embodiments, the intelligent preprocessing engine includes:
[0047] An abstract syntax tree parser is used to segment code differences into semantic code units bounded by class or function definitions; and
[0048] The static dependency analysis unit is used to analyze each semantic code unit to identify the external functions it calls or the external classes it references, and to attach the interface definition of the external functions or classes as cross-file dependency tags to the corresponding semantic code unit.
[0049] In some optional embodiments, the dynamic prompt word constructor is further configured to:
[0050] Read the rule base stored in a machine-resolvable format; and
[0051] The technical review indicators read from the rule base are transformed into a set of natural language instructions to constrain the analysis behavior of the large language model, and then placed into structured prompt words.
[0052] In some optional embodiments, the AI large model analysis layer is further configured to handle situations where the code difference data contains multiple interrelated semantic code units:
[0053] The first semantic code unit is analyzed to generate a feature change summary, and the dynamic prompt word constructor is instructed to inject the feature change summary as additional contextual information when constructing subsequent structured prompt words.
[0054] This invention provides a computing device, including a processor and a memory, wherein the memory stores a computer program, and the computer program, when executed by the processor, implements the method described above.
[0055] This invention provides a computer program product, including computer program instructions, which, when executed by a processor, are used to implement the method described above.
[0056] It should be understood that the above general description and the following detailed description are exemplary and explanatory only, and are not intended to limit the invention.
[0057] The intelligent analysis method, system, device, and program product for automated code review of the present invention have the following beneficial effects:
[0058] This invention uses semantic understanding of code changes to accurately identify logically equivalent refactorings, effectively eliminating review noise. Employing a parallel analysis strategy significantly shortens code review time. It can automatically detect cross-terminal API compatibility and potential security vulnerabilities, reducing online defect rates. By unifying review standards through a configurable rule base, it reduces reliance on senior engineers, saving labor costs. Compared to traditional technologies, this invention improves code review efficiency, increases accuracy, enhances risk control capabilities, and achieves standardized review processes, resulting in a dual improvement in efficiency and quality. Attached Figure Description
[0059] Other features, objects, and advantages of the invention will become more apparent from the following detailed description of non-limiting embodiments with reference to the accompanying drawings.
[0060] Figure 1 This is a flowchart of an intelligent analysis method for automated code review according to an embodiment of the present invention;
[0061] Figure 2 This is a schematic diagram of the structure of an intelligent analysis system for automated code review according to an embodiment of the present invention. Detailed Implementation
[0062] Exemplary embodiments will now be described more fully with reference to the accompanying drawings. However, these exemplary embodiments can be implemented in many forms and should not be construed as limited to the examples set forth herein; rather, they are provided so that the invention will be more comprehensive and complete, and will fully convey the concept of the exemplary embodiments to those skilled in the art. The described features, structures, or characteristics may be combined in any suitable manner in one or more embodiments.
[0063] Furthermore, the accompanying drawings are merely illustrative of the invention and are not necessarily drawn to scale. The same reference numerals in the drawings denote the same or similar parts, and therefore repeated descriptions of them will be omitted. Some block diagrams shown in the drawings are functional entities and do not necessarily correspond to physically or logically independent entities. These functional entities can be implemented in software, in one or more hardware modules or integrated circuits, or in different network and / or processor devices and / or microcontroller devices.
[0064] The flowchart shown in the attached diagram is merely an illustrative example and does not necessarily include all steps. For example, some steps may be broken down, while others may be combined or partially combined. Therefore, the actual execution order may change depending on the specific circumstances.
[0065] The code review method involved in this invention automates code changes by relying on precise analysis and risk identification of code discrepancies. The underlying technology utilizes Abstract Syntax Trees (ASTs) to transform code into a computer-understandable structured representation, and employs Natural Language Processing (NLP) techniques to understand the semantics of the code. ASTs enable the analysis of the code's logical structure, while NLP techniques, especially large language models, endow the system with the ability to understand the code's intent. By encoding code review rules into natural language instructions and leveraging the reasoning capabilities of large language models, automated analysis of code changes can be performed to identify potential defects and risks. This method, which integrates structured code analysis and natural language understanding, enables a more comprehensive and in-depth understanding of the meaning of code changes, improves the efficiency and accuracy of code reviews, and reduces software defect rates.
[0066] like Figure 1 As shown, this embodiment of the invention provides an intelligent analysis method for automated code review. This method achieves automated review of code changes through a series of steps and generates a visual report containing risk analysis.
[0067] Step S100: Obtain code diff data resulting from the target code changes. In one embodiment, this step is implemented by calling a GitLab API. For example, the system receives a GitLab webhook notification indicating that a Merge Request has been created or updated. The system then uses the project ID and Merge Request ID from the notification to call the GitLab API (e.g., GET / projects / {id} / merge_requests / {mr_iid} / changes) to obtain the code diff data corresponding to the Merge Request. This code diff data is typically in Diff format text format, containing the name of the modified file, the modified line number, and the specific code changes. Alternatively, the system can also obtain code diff data by listening to events from other version control systems, such as GitHub or Bitbucket.
[0068] Step S200: Preprocess the code difference data to generate semantic code units. Preprocessing includes filtering non-code files and semantically segmenting the code difference fragments. In one implementation, the system first iterates through the acquired code difference data, filtering out non-code files based on their file extensions, such as .png, .jpg, and .xml. Then, for the remaining code files, the system uses an Abstract Syntax Tree (AST) parser to semantically segment them. For Java code, JavaParser can be used; for Python code, the ast module can be used. The AST parser parses the code into an abstract syntax tree. The system determines the specific location of the code change (e.g., a modification to a function) by comparing the differences between the two ASTs before and after the change. Then, the code is segmented into multiple semantic code units, based on functions, classes, or methods. Each semantic code unit contains both the original and modified code fragments. As an alternative, code difference fragments can also be segmented using regular expressions or a token-based diff algorithm.
[0069] Step S300: Based on preset review rules, dynamically construct structured prompts for input into the large language model. The structured prompts include review rules, the old and new versions of the code corresponding to the semantic code unit, and code context information. In one example, the system reads preset review rules from a YAML file. These rules may include naming conventions, security vulnerability checks, API compatibility checks, etc. Each rule contains an ID, a description, and a corresponding natural language instruction. For example, a rule might be "Check if the code uses an insecure encryption algorithm." Subsequently, the system combines these rules, the old and new versions of the semantic code unit, and code context information (e.g., code comments, function signatures, etc.) into a structured prompt. The prompts can be in JSON or Markdown format. The prompts are designed to guide the large language model in code review and return structured data containing the review results. As an alternative, the rule base can also be stored in a database, such as MySQL or PostgreSQL, and queried using SQL statements.
[0070] Step S400: The system invokes a large language model to process the structured prompts to identify logically equivalent and non-equivalent changes in the code modifications, and marks risk points in the code based on review rules. In one embodiment, the system invokes OpenAI's GPT-4 model. The system takes the structured prompts generated in step S300 as input and sends them to the GPT-4 model via API. The GPT-4 model analyzes the code modifications based on the instructions in the prompts, identifying logically equivalent refactorings (e.g., variable renaming) and functionally non-equivalent changes (e.g., algorithm modifications). Simultaneously, the GPT-4 model also marks potential risk points in the code (e.g., using outdated APIs) according to review rules. The GPT-4 model returns the analysis results in JSON format. This JSON data contains the change type (refactoring or functional change), a change summary, and a list of risk points, each containing a rule ID, description, and code snippet. Alternatively, the system can use other large language models, such as Google's PaLM or the open-source LLaMA model, or use large language models through local deployment.
[0071] Step S500: Based on the recognition and annotation results of the large language model, generate a visual report containing statistical differences and risk point distribution. In one implementation, the system parses the JSON data received in step S400, extracting change types, change summaries, and risk point information. Then, the system uses this data to generate an HTML-formatted visual report. This report includes statistical charts of change types (refactoring / addition / deletion), a risk heatmap distributed by file or terminal, and highlighted code snippets, detailed risk explanations, and AI-generated remediation suggestions for each high-risk point. The report can be viewed in a browser. Alternatively, the report can also be generated in Markdown or PDF format. The visual report can also be displayed directly through a web interface integrated into a version control system, such as through GitLab's Merge Request comment function.
[0072] Through the above steps, this embodiment realizes an automated code review process. The data acquisition module acquires code change information, the intelligent preprocessing engine transforms the code into structured information, the dynamic prompt word constructor generates LLM-understandable instructions based on rules, the LLM analysis layer performs code analysis and identifies risks, and finally, the visualization report generator presents the analysis results in an easy-to-understand format. These various technical features work together to solve the technical problems of existing code review technologies, such as difficulty in understanding code semantics, inability to effectively identify cross-terminal code logic consistency, and low efficiency of manual review. Specifically, the intelligent preprocessing engine provides LLM with structured code input rich in contextual information, the dynamic prompt word constructor transforms review rules into LLM-executable instructions, and LLM's powerful semantic understanding capabilities can accurately identify logically equivalent refactorings and potential risk points, thereby significantly improving the efficiency and accuracy of code review.
[0073] The intelligent analysis method provided in this embodiment can reduce the code review process, which traditionally requires hours or even days of manual work, to within minutes, significantly improving software development efficiency. Simultaneously, this method can accurately identify logically equivalent refactorings, eliminate review noise, and automatically detect potential security, performance, and compatibility risks, thereby improving code quality. Furthermore, this method unifies code review standards through a configurable rule base, reducing reliance on senior engineers and saving labor costs.
[0074] In one specific implementation, based on the above embodiments, obtaining code difference data specifically includes the following steps: First, the system listens for Merge Request-related events in the version control system, such as GitLab. Specifically, this can be done by registering a Webhook to listen for events such as "Merge Request creation" and "Merge Request update". Then, when the target event is detected, the data acquisition module obtains the code difference data by calling the GitLab API. Specifically, the following HTTP request can be constructed:
[0075] GET / projects / {project_id} / merge_requests / {merge_request_iid} / changes
[0076] Here, `project_id` represents the project ID, and `merge_request_iid` represents the internal ID of the Merge Request. The data acquisition module uses an API key with appropriate permissions for authentication to ensure access to the code repository. Next, the version control system responds to the API request, returning data containing detailed code change information, typically a text file in Diff format. The data acquisition module parses this response data into an internal data structure, including, for example, the filename of each changed file, the change type (added, deleted, modified), and specific code difference fragments. The API key can be configured through GitLab's Settings->CI / CD->Secret variables. Alternatively, the data acquisition module can also obtain code difference data by calling Git commands, such as `git diff`. For example, executing the command `git diff commit_id1commit_id2 --path / to / file` will retrieve the code differences between two commits. Finally, considering the stability and efficiency of network transmission, the data acquisition module can use a streaming approach to process API responses, avoiding loading large amounts of data into memory at once.
[0077] By following the steps above, code difference data can be automatically retrieved from the version control system, providing a data foundation for subsequent code review and analysis. This process avoids the tedious steps of manually downloading and converting data, improving the efficiency and accuracy of code review.
[0078] In one specific implementation, based on the above embodiments, the acquisition of cross-platform code difference data is also included. First, the system maintains a code repository mapping database, which records the correspondence between code repositories of the same software function on different terminals (e.g., iOS, Android, Web). This database is stored in key-value pairs, where the key is a unique identifier representing a specific function, and the value is a list, where each element contains the code repository URL, branch name, and terminal type.
[0079] Specifically, when the data acquisition module receives a code change analysis request for a specific terminal (e.g., iOS), it first parses the project identifier in the request and queries the code repository mapping database to see if there are code repositories for other terminals associated with it. If so, the data acquisition module initiates API calls to these associated code repositories in parallel to extract code difference data on the corresponding branches. When extracting API difference data, a time window parameter can be selectively added; for example, only changes that occurred within a similar time frame to the code changes in the initial request can be extracted to ensure the relevance of the analysis. Optionally, the length of this time window is configurable, for example, set to 24 hours before and after the time of the code changes in the initial request.
[0080] Then, the data acquisition module encapsulates all acquired code difference data, including code difference data corresponding to the original request and associated cross-platform code difference data, into a unified data input for the analysis task. This data input includes metadata such as the code repository URL, branch name, and terminal type corresponding to each code difference data, so that subsequent modules can distinguish and process code from different terminals.
[0081] Furthermore, the code repository mapping database supports dynamic updates. The system provides a management interface that allows administrators to manually add, modify, or delete mappings between code repositories. The system also supports automatic learning to extract cross-platform association information from code commit messages and automatically update the code repository mapping database. For example, if multiple code commit messages contain the same bug fix number, and these commits belong to code repositories on different platforms, the system can automatically infer a relationship between these repositories and add the corresponding mapping to the code repository mapping database.
[0082] This embodiment can automatically acquire code difference data for the same function on different terminals, thereby providing a data foundation for subsequent cross-platform code consistency analysis.
[0083] In one specific implementation, based on the above embodiments, when semantically segmenting code difference fragments, firstly, for code files in different programming languages, a corresponding Abstract Syntax Tree (AST) parser is selected. For example, for Java, the JavaParser library is used; for Python, the ast module is selected; and for JavaScript, parsers such as Esprima or Acorn can be used. Then, using the selected AST parser, the code difference fragments are parsed into ASTs respectively. Specifically, for each code fragment, the parser decomposes the code into a series of hierarchical nodes, each node representing a syntactic structure in the code, such as expressions, statements, declarations, etc. Next, the generated AST is traversed to identify nodes bounded by class definitions or function definitions. For example, in Java, nodes of type ClassDeclaration and MethodDeclaration are searched; in Python, nodes of type ClassDef and FunctionDef are searched. For the identified class definition and function definition nodes, their corresponding code fragments are extracted and encapsulated into semantic code units. Specifically, the start and end positions of the node in the source code are extracted, and the corresponding code segments are extracted from the original code file based on these two positions. Alternatively, as a simplified alternative to the AST parser, a code parsing method based on predefined syntax patterns can be used. This method includes the following steps: First, a set of text patterns for identifying logical unit boundaries is predefined based on the syntax features of the target programming language. These text patterns can be implemented as regular expressions designed to match keywords such as function or class definition keywords (e.g., 'function', 'def', 'class', etc. in different languages), parameter list delimiters (e.g., parentheses '()'), and code body start and end delimiters (e.g., curly braces '{}' or the 'end' keyword). Then, the text patterns are used to scan and match code difference fragments to extract the code segments corresponding to the patterns, which are then used as semantic code units. While this method is less precise than AST parsing when dealing with complex or nested syntax structures, it can serve as a more lightweight implementation in certain scenarios. Finally, isolated code snippets that cannot be parsed by AST or matched by regular expressions can be treated as independent semantic code units or merged into adjacent semantic code units.
[0084] By utilizing an abstract syntax tree parser or regular expressions to semantically segment code differences, this embodiment can more accurately identify logical units in the code, providing more structured input for subsequent large language model analysis, thereby improving the accuracy and efficiency of code review.
[0085] In one specific implementation, based on the above embodiments, for each semantic code unit segmented by the abstract syntax tree parser, before the dynamic prompt word constructor generates prompt words, the system first performs static dependency analysis. Specifically, it traverses the abstract syntax subtree corresponding to the semantic code unit to identify the dependencies on external code contained therein. These dependencies include, but are not limited to: calls to other functions or methods, instantiation of other classes, inheritance of parent classes, implementation of interfaces, and import statements of external modules. Static dependency analysis can be implemented in various ways, such as using symbol tables, control flow graphs, or data flow graphs. In one example, the system utilizes the SymbolSolver function provided by the JavaParser library to parse symbolic references in Java code to determine the specific type and location of external dependencies. If a call to an external function is detected, the system records information such as the function name, parameter types, and return type of the called function. If an instantiation of an external class is detected, the system records the class name and constructor information of the instantiated class. The system also maintains a caching mechanism to store already analyzed dependencies to avoid duplicate analysis and improve efficiency. In addition, as an alternative to static dependency analysis, text matching based on regular expressions can be used. Although the accuracy is lower, it can provide a lightweight solution for some simple dependency identification, such as finding specific import statements.
[0086] By performing static dependency analysis, this embodiment can provide richer contextual information for subsequent prompt word construction, improving the accuracy and depth of large language model analysis of code changes.
[0087] In one specific implementation, based on the above embodiments, the preprocessing flow of the semantic code unit further includes attaching the interface definition of the external function or class as a cross-file dependency tag to the corresponding semantic code unit as part of the code context information. First, after identifying the external functions or classes that the semantic code unit depends on through static dependency analysis, the system queries a pre-established bulleted index database for the interface definitions of these external dependencies. For Java, the interface definition can include a complete function signature, such as return type, function name, parameter types, and parameter names; for C++, the interface definition can include declarations of the class's public member functions. Then, the system creates a text string containing the interface definition of the external dependency. For example, for the Java method "public int calculate(int a, int b)", the interface definition string can be represented as " / / Signature of called externalmethod:\npublic int calculate(int a, int b);". Next, this text string is stored as an attribute of a JSON object named "context" along with other attributes of the semantic code unit (such as "old_code" and "new_code"). If the interface definition of an external dependency cannot be found in the bulleted index database, the system will attempt to analyze the file containing that dependency on an ad-hoc basis, for example, by reading the file content and extracting the interface definition using the appropriate abstract syntax tree parser. This bulleted index database can be implemented in various ways, such as an in-memory hash table, a disk-based key-value store (e.g., LevelDB), or a relational database (e.g., MySQL). The bulleted index database can be updated periodically to reflect the latest changes to the codebase. Alternatively, the system can choose to query the interface definition only when needed, without maintaining a persistent index database. For some dynamically typed languages (e.g., Python or JavaScript), the interface definition may not contain complete type information due to the lack of static type information. In this case, the system can extract available type hints or other relevant information, such as the docstring of a function or method. The extracted interface definition information is then added as text to the context information of the semantic code unit.
[0088] By adding the interface definitions of external functions or classes as cross-file dependency tags to semantic code units, large language models can obtain more complete contextual information when analyzing code changes, thereby improving the accuracy and reliability of the analysis.
[0089] In one specific implementation, based on the above embodiments, the rule base for dynamically constructing structured prompt words is implemented as a YAML file. This YAML file is stored on the system's local hard drive or network file system and can be edited and updated by a user with administrator privileges.
[0090] First, this YAML file is loaded during system initialization or when a rule update instruction is received. This file is parsed into an internal data structure, such as a dictionary in Python or a HashMap in Java, for fast retrieval and access.
[0091] Specifically, the YAML file contains a list of rules, each rule containing at least the following fields: rule_id (a unique identifier for the rule, string type), description (a natural language description of the rule, string type), language (the programming language to which the rule applies, string type, e.g., "Java", "Python", "Swift", "Kotlin", etc.), threshold (the risk level, an enumeration type, e.g., "CRITICAL", "MAJOR", "MINOR"), and prompt_template (a template used to generate prompt words, string type). prompt_template may contain placeholders, such as ${code}, ${context}, and ${rule_description}, which will be replaced by the actual code snippets, context information, and rule descriptions during the prompt word construction process.
[0092] Then, when dynamically constructing suggestion words, the dynamic suggestion word builder first filters out a subset of applicable rules based on the programming language of the currently analyzed code snippet. The filtering operation is implemented through string matching; for example, if the programming language of the code snippet is "Kotlin", then only rules whose language field contains "Kotlin" or "All" are selected.
[0093] Next, for each selected rule, the dynamic prompt word constructor combines the rule's `prompt_template` field with the code snippet from the semantic code unit output by the preprocessing engine and the context information obtained from static dependency analysis to generate the final prompt word. The combination process includes string substitution; for example, replacing `${code}` in `prompt_template` with the code snippet, `${context}` with the context information, and `${rule_description}` with the rule's natural language description.
[0094] The rule base can also be implemented as a relational database, such as MySQL or PostgreSQL. In this alternative, rule information is stored in database tables, and the dynamic prompt word builder retrieves applicable rules from the database using SQL queries. To improve query efficiency, indexes can be created in the database tables, such as an index on the language field. Alternatively, the rule base can be implemented using a key-value database such as Redis, storing rule IDs and rule information as key-value pairs.
[0095] This embodiment stores review rules in a machine-readable rule base, enabling centralized management and dynamic updates of review rules. This allows code review standards to be flexibly adjusted as project requirements change, avoiding the drawbacks of hard-coding review logic into the system.
[0096] In one specific implementation, based on the above embodiments, the process of dynamically constructing structured prompts further includes: First, reading technical review indicators stored in YAML, JSON, or XML formats from a rule base. The rule base is stored in a relational database such as MySQL, a NoSQL database such as MongoDB, or a distributed key-value storage system such as Etcd. Specifically, the rule base contains multiple rule entries, each entry containing at least a rule ID, a natural language description, an applicable programming language, and a conditional expression for detecting specific code risks. Then, each read technical review indicator is converted into one or more natural language instructions. During the instruction conversion process, a template-based generation method or a rule-based conversion engine can be used. Next, the generated natural language instruction set is placed into the structured prompts. The instruction set can be organized in the form of lists, paragraphs, or code blocks. The natural language instruction set is used to guide the large language model to perform specific analysis tasks, such as checking for cross-thread concurrent access to shared variables or verifying whether the input data has undergone sufficient legality checks.
[0097] For example, a rule can be defined in the rule base to detect unhandled Activity leak risks in Android applications:
[0098] yaml
[0099] rule_id:ANDROID_ACTIVITY_LEAK
[0100] description: "Detects potential Activity leaks in Android applications."
[0101] language: "Java"
[0102] condition:"Check if the Activity context is being held by a staticreference or a long-running background thread without proper cleanup."
[0103] The dynamic prompt word constructor translates it into the following natural language instructions:
[0104] text
[0105] [Rule:ANDROID_ACTIVITY_LEAK]Carefully examine the provided Java code for any potential Activity leaks. Specifically, check if the Activity context is being held by a static reference, an inner class instance, or a long-running background thread without proper cleanup in the Activity's onDestroy() method. Report any instances where the Activity context may outlive itsintended lifecycle, leading to a memory leak.
[0106] This embodiment transforms technical review indicators into a natural language instruction set, enabling more flexible configuration of code review rules, expanding the analytical capabilities of large language models, and improving the accuracy and efficiency of automated code review.
[0107] In one specific implementation, based on the above embodiments, the dynamic prompt word constructor generates structured prompt words that include semantic guidelines and formatting instructions. First, the constructor distinguishes between "logically equivalent refactoring" and "functionally non-equivalent changes," providing clear distinction criteria for large language models. For example, for Java code, semantic guidelines may include:
[0108] json
[0109] {
[0110] "refactoring_criteria":
[0111] "Variable renaming without changing data flow",
[0112] "Function extraction or inlining that preserves functionality",
[0113] "Code block reordering that does not alter program logic",
[0114] "Changing comments or whitespace"
[0115] ,
[0116] "functional_change_criteria":
[0117] "Adding new features or functionalities",
[0118] "Modifying existing functionalities",
[0119] "Fixing bugs or errors",
[0120] "Changing the program's behavior or output"
[0122] }
[0123] Then, the constructor converts the above criteria into a natural language description and embeds it in the prompt: "Carefully analyze the code change. Determine if the changes fall under 'logically equivalent refactoring' (as defined in the refactoring criteria) or 'functional change' (as defined in the functional change criteria). Clearly state your reasoning."
[0124] Specifically, the constructor specifies the output format of the large language model. For example, outputting the analysis results in JSON format:
[0125] json
[0126] {
[0127] "change_type":"refactoring"|"functional",
[0128] "reasoning":"Detailed explanation of why the change is classified as such",
[0129] "risks":[
[0130] {
[0131] "rule_id":"API_LEVEL_CHECK",
[0132] "description":"API level compatibility issue",
[0133] "code_snippet":"Relevant code section"
[0134] } ]
[0136] }
[0137] The constructor embeds the above JSON schema as text within the prompt: "Provide your analysis in JSON format, strictly adhering to the following schema: {...}. The change_type field must be either 'refactoring' or 'functional'. The reasoning field must contain a detailed explanation. The risks field must be an array of riskobjects (if any), following the specified structure." Alternatively, the output format instructions can also use other machine-readable formats such as XML or YAML.
[0138] Next, the constructor combines the aforementioned semantic guidelines and formatting instructions with technical review metrics read from the rule base to form a complete structured cue word, which is then input into the large language model. The large language model follows the instructions in the cue word to categorize code changes and outputs the analysis results in a predefined structured format.
[0139] By incorporating semantic guidelines and formatting instructions into the prompts, this implementation can more accurately guide large language models in analyzing the types of code changes and ensure that the analysis results are output in a machine-readable format, thereby facilitating subsequent automated processing and report generation.
[0140] In one specific implementation, based on the above embodiments, the rule base contains rules for defining various types of risks, and the process of the large language model marking risk points is as follows: First, for API compatibility risks, the rule base contains a blacklist of API calls for different operating system versions and hardware platforms, as well as the corresponding minimum compatible version number. When analyzing code, if the large language model identifies a call to an API in the blacklist, it will further check the version number of the target platform. If it is lower than the minimum compatible version, it will be marked as an API compatibility risk. Alternative solutions include using a whitelist approach, that is, only allowing calls to APIs of specific versions and below. Specifically, for the Android platform, the android:minSdkVersion attribute can be checked, and for the iOS platform, the MinimumOSVersion field in the Info.plist file can be checked. Then, for security risks, the rule base contains common security vulnerability patterns, such as SQL injection, cross-site scripting (XSS) attacks, and buffer overflows. The large language model will identify whether there are operations in the code that may lead to security vulnerabilities, such as concatenating SQL statements or directly outputting user input, and mark them according to the severity of the vulnerability. Static code analysis tools (such as Fortify and Checkmarx) can be used to supplement security vulnerability patterns. Next, for performance risks, the rule base includes code patterns that may cause performance bottlenecks, such as database queries within loops, loading and decoding large images, and inappropriate thread usage. The large language model assesses the potential performance impact based on the code's execution path and data scale, and labels it as a performance risk. The labeling of performance risks can also be combined with the results of dynamic performance analysis tools (such as AndroidProfiler and Instruments) to improve accuracy.
[0141] Furthermore, for identified API compatibility risks, the labeling process can provide different levels of risk warnings based on the specific circumstances of the API. For example, if an API has an easily implementable alternative, it can be labeled as a "MINOR" risk; if an API alternative requires a major refactoring, it can be labeled as a "MAJOR" risk; and if the absence of an API would cause the functionality to completely fail, it can be labeled as a "CRITICAL" risk.
[0142] This embodiment can automatically mark various types of risk points in the code, effectively improving the depth and breadth of code review.
[0143] In one specific implementation, based on the above embodiments, a parallel analysis technical solution is provided for code changes comprising multiple independent semantic code units. First, after the data acquisition module acquires code difference data, the intelligent preprocessing engine identifies N (N is an integer greater than 1) independent semantic code units. For example, modifications to file A and file B do not involve any cross-file dependencies. Specifically, when performing static dependency analysis, if the intelligent preprocessing engine determines that there is no dependency between any two semantic code units (e.g., no shared external function calls or class references), it marks them as independent. Then, a dynamic prompt word constructor generates structured prompt words for each independent semantic code unit. Next, the AI large model analysis layer maintains a thread pool or process pool, the size of which can be dynamically adjusted according to system resources, such as the number of CPUs or available memory. The AI large model analysis layer allocates N analysis tasks to this thread pool or process pool for parallel execution. Specifically, the AI large model analysis layer can use Python's `concurrent.futures` module to implement concurrent calls, or Java's `ExecutorService` interface. Each thread or process is responsible for invoking the large language model (e.g., via an HTTP request) to analyze a semantic code unit. In another implementation, the AI large model analysis layer can communicate with the large language model service using asynchronous non-blocking I / O, such as using Python's asyncio library or Java's NIO library. Finally, the rule-based result parser receives the analysis results from N threads or processes and merges them into a complete analysis report.
[0144] By adopting the parallel analysis strategy described above, the analysis time for large-scale code changes can be significantly shortened. In particular, when the code changes involve multiple unrelated modules, the computing power of multi-core processors can be fully utilized, thereby improving the efficiency of code review.
[0145] In one specific implementation, based on the above embodiments, the process of calling the large language model is refined for cases where code difference data contains multiple interrelated semantic code units. First, the system identifies multiple semantic code units with dependencies. These dependencies can be determined by analyzing the call relationships between code units, such as function A calling function B, or class C inheriting from class D. After determining the dependencies, the system processes the semantic code units located upstream in the dependency chain according to the dependency order. Specifically, assuming there are three semantic code units, corresponding to functions A, B, and C respectively, and function A calls function B, and function B calls function C, then the processing order is function C, function B, and function A.
[0146] Next, for the first semantic code unit processed (function C in this example), the system constructs structured prompts and calls the large language model for analysis, following the steps in the above embodiments. After the large language model analysis is completed, the rule-based result parser extracts the LLM output and extracts a summary of the functional changes to the code unit. This summary is a highly generalized description of the functional modification of the code unit, and can be in the form of natural language text or structured key-value pairs. For example, if the function of C is changed from calculating the sum of two integers to calculating the product of two integers, the summary could be "The function of C has been changed from addition to multiplication" or {"operation":"multiplication"}. This summary is stored in system memory or written to a temporary file for use in subsequent steps.
[0147] The system then processes subsequent code units that depend on the aforementioned code unit (function B in this example). When constructing the structured prompt for function B, the system injects a previously generated feature change summary as additional contextual information into the prompt. Specifically, the feature change summary can be added to the "Code Context Information" section of the prompt or to the "Task Description" section. For example, if the original prompt was "Please analyze the risks of the following code," the modified prompt might be "Please analyze the risks of the following code; note that the function C's functionality has been changed from addition to multiplication."
[0148] The system calls upon a large language model to analyze the modified prompt. Because the prompt contains a summary of the functional changes to function C, the large language model can consider these changes when analyzing function B, thus making a more accurate judgment. For example, if the modification of function B depends on the calculation result of function C, the large language model can identify this dependency and determine whether the modification of function B is correct.
[0149] Finally, the system processes the remaining code units (function A in this example), repeating the above steps until all interrelated semantic code units have been processed. A summary of the functional changes of the code units it depends on is injected into the structured prompt for each code unit, ensuring that the large language model can fully understand the logical relationships of the entire code change process.
[0150] This embodiment effectively addresses the context window limitation problem of large language models through this chain-based analysis method, improving the accuracy and efficiency of code review, especially when dealing with complex code changes with dependencies.
[0151] In one specific implementation, based on the above embodiments, for code review of cross-platform applications (e.g., applications with both iOS and Android versions), the dynamic prompt word constructor, when generating structured prompt words, first determines whether the code changes to be analyzed fall within the scope of cross-platform logical consistency verification. If so, it extracts a set of rules specifically for cross-platform code comparison from the rule base.
[0152] Specifically, these rule sets contain specific instructions to guide large language models to ignore syntactic differences between programming languages. For example, for Swift code snippets on iOS and Kotlin code snippets on Android, the rule set might contain instructions such as: "Ignore syntactic differences between Swift and Kotlin, such as semicolons, type declarations, and function definitions. Focus on comparing the business logic of the two code snippets, including but not limited to: user input validation, data processing flow, API call order, and error handling mechanisms."
[0153] The dynamic prompt builder then embeds these specific instructions into structured prompts generated for Swift and Kotlin code snippets, respectively. For example, the two final prompts might contain the following snippets:
[0154] Swift prompt word snippet: "...You are a cross-platform code reviewer.Focus on the core business logic of the following Swift code,ignoring Swift-specific syntax.The goal is to ensure consistency with the corresponding Kotlin codeprovided separately..."
[0155] Kotlin prompt word snippet: "...You are a cross-platform code reviewer.Focus on the core business logic of the following Kotlin code,ignoring Kotlin-specific syntax.The goal is to ensure consistency with the corresponding Swift codeprovided separately..."
[0156] Next, the AI large-scale model analysis layer submits structured prompts containing the aforementioned specific instructions to the large language model. Upon receiving these prompts, the large language model, guided by the instructions, ignores the syntactic differences between Swift and Kotlin, and instead focuses on comparing whether the two code snippets are consistent in their functional implementation logic. For example, the large language model might check whether both platforms use the same encryption process for user passwords, or whether both platforms employ the same retry strategy when handling network request timeouts.
[0157] Finally, the rule-based result parser parses the analysis results returned by the large language model, quantifies the risk level of inconsistencies in the code logic of the two platforms, and highlights these potential cross-platform defects in the visualization report.
[0158] Through the above steps, this embodiment enables the large language model to overcome the interference caused by cross-language differences, accurately identify deviations in business logic in multi-platform code, thereby improving the efficiency and accuracy of cross-platform code review.
[0159] In one specific implementation, based on the above embodiments, the process of generating a visualization report specifically includes: First, determining the number of risk points for each file in the code repository; then, categorizing the number of risk points into the corresponding terminal dimension according to the terminal type to which the file belongs (e.g., iOS, Android, Web); next, calculating the risk density for each file or terminal. The risk density is calculated by dividing the number of risk points by the number of lines of code in the file, or the total number of lines of code in all files under that terminal. Color coding is used for risk density mapping; for example, low risk density is displayed as green, medium risk density as yellow, and high risk density as red. Finally, using HTML5 Canvas, SVG, or other graphics libraries, the data is presented in the form of a heatmap. The horizontal axis represents the file path or terminal type, and the vertical axis can represent the time series of code submissions or other relevant dimensions. The color of each cell in the heatmap is filled according to the corresponding risk density. The heatmap can be interactive, such as displaying more detailed risk information when the mouse hovers over it, or clicking on a cell to jump to the relevant code change location. Alternatively, risk density can also be represented by the brightness or size of the cells. In another implementation, the color coding of the heatmap can be weighted according to the risk level. For example, CRITICAL-level risk points are given higher weights, thus making high-risk areas more prominent in the heatmap.
[0160] This embodiment generates risk heatmaps by file or terminal dimension, which can intuitively display the risk distribution in the code repository, help developers quickly locate potential problem areas, and improve code review efficiency.
[0161] In one specific implementation, based on the above embodiments, when generating a visual report, the system first locates risk points identified by the Large Language Model (LLM) whose risk level exceeds a preset threshold. The risk level is determined according to the definition in the rule base. Specifically, this threshold can be set in the system configuration, for example, set to MAJOR. Then, for each risk point, the report generator extracts the corresponding code snippet. This code snippet includes the line of code involving the risk, as well as several surrounding lines of code to provide contextual information. The extracted code snippet is automatically syntax-highlighted to highlight the risk code. The syntax highlighting scheme can be adapted to different programming languages; for example, for Java code, words are used in blue, strings in green, and comments in gray. Furthermore, the system calls the Large Language Model, requesting it to generate a brief correction suggestion for the risk point. For example, for an API compatibility issue, the LLM might generate the following suggestion: "It is recommended to use a version with API Level >= 21 to avoid compatibility issues." This correction suggestion is displayed in the report in text form along with the highlighted code snippet. The highlighting in the report can be implemented in various ways, such as using HTML. <pre>and <code>Tags are used and combined with CSS styles for rendering; or Markdown syntax is used and parsed by a Markdown rendering engine. The implementation of generating corrective suggestions using a large language model includes sending a hint containing a risky code snippet to the large language model and instructing it to generate corrective suggestions for that risk.
[0162] By providing highlighted code snippets and suggested fixes generated by a large language model, this implementation helps developers quickly locate and understand risks in their code and provides actionable remediation solutions, thereby improving the efficiency and quality of code reviews.
[0163] like Figure 2 As shown, this embodiment of the invention provides an intelligent analysis system for automated code review. Through modular design, the system realizes intelligent analysis and risk assessment of code changes, providing software development teams with an efficient and accurate code review tool.
[0164] The system includes a data acquisition module M100, configured to communicate with the API of version control systems (such as GitLab and GitHub) to obtain code diff data resulting from target code changes. In one implementation, the M100 can retrieve Diff formatted text data from API endpoints provided by the version control system (e.g., GitLab's GET / projects / {id} / merge_requests / {merge_request_iid} / changes) via HTTP requests. The M100 can support multiple version control systems, adapting to different API interfaces to obtain code change information. Version control systems can be centralized, such as SVN, or distributed, such as Git. The acquired code diff data can be in a unified diff format or a format specific to other version control systems.
[0165] The system also includes an intelligent preprocessing engine M200, used to preprocess the code difference data obtained by the data acquisition module M100 to generate semantic code units. This intelligent preprocessing engine M200 is configured to filter non-code files and perform semantic segmentation on code difference fragments. In one embodiment, the preprocessing engine first checks the file extensions, for example, ignoring image files such as .jpg and .png, and configuration files such as .xml and .json (unless these configuration files are explicitly specified to be analyzed). Then, the intelligent preprocessing engine M200 uses an Abstract Syntax Tree (AST) parser (e.g., the JavaParser library for Java; the ast module for Python) to segment the code difference fragments into semantic code units bounded by class definitions, function definitions, or method definitions. For example, for Java code, the `class` keyword and `{}` can be recognized to determine class boundaries, and method signatures and `{}` can be recognized to determine method boundaries. The intelligent preprocessing engine M200 can also be configured to recognize other types of code structures, such as interfaces and enumerations.
[0166] The system also includes a dynamic prompt word builder M300, which dynamically constructs structured prompt words for input into a large language model based on preset review rules. These structured prompt words include review rules, old and new versions of the code corresponding to the semantic code unit, and code context information. In one example, the dynamic prompt word builder M300 reads review rules from a rule base stored in YAML format. For example, a rule might define usage restrictions on a specific API or a check for potential security vulnerabilities. The dynamic prompt word builder M300 then translates these review rules into natural language instructions, such as, "Please check the code for calls to deprecated APIs." The builder combines these instructions with the old and new versions of the code and context information obtained from static analysis (e.g., version information of external libraries the code unit depends on) to form a structured prompt word, for example, using JSON format. The prompt word builder can generate different prompt words based on different programming languages and code styles.
[0167] The system also includes an AI large-scale model analysis layer, M400, which calls a large language model to process the structured prompts generated by the dynamic prompt word builder M300. This process identifies logically equivalent and non-equivalent changes in code modifications and marks risk points in the code based on review rules. The AI large-scale model analysis layer M400 can send structured prompts to a large language model service (e.g., OpenAI's GPT-4, Google's PaLM 2) via API calls. The large language model analyzes the prompts and generates text containing the analysis results. The AI large-scale model analysis layer M400 can process multiple prompts concurrently to improve analysis efficiency. The large language model can identify various types of risk points, such as null pointer exceptions, SQL injection, and cross-site scripting attacks.
[0168] The system also includes the M500 visualization report generator, which generates visualization reports containing differential classification statistics and risk point distribution based on the identification and annotation results obtained from the AI large model analysis layer M400. In one implementation, the M500 visualization report generator parses the analysis results of the large language model into structured data (e.g., JSON) and uses this data to generate charts and tables that display statistical information on the types of code changes (e.g., refactoring, feature changes, bug fixes) and the distribution of risk points in the code. The report can include risk level, risk description, and remediation recommendations. The visualization report can be presented in formats such as HTML and Markdown. The M500 visualization report generator can generate various types of charts, such as pie charts, bar charts, and heatmaps.
[0169] The data acquisition module M100, intelligent preprocessing engine M200, dynamic prompt word constructor M300, AI large-scale model analysis layer M400, and visualization report generator M500 work together to complete code review tasks. The data acquisition module M100 collects raw data; the intelligent preprocessing engine M200 converts the raw data into structured data that the large language model can understand; the dynamic prompt word constructor M300 generates targeted analysis instructions based on preset rules; the AI large-scale model analysis layer M400 executes the analysis tasks and identifies risk points; and finally, the visualization report generator M500 presents the analysis results to the user in an easy-to-understand manner. This collaborative approach solves the problem that traditional code review tools cannot understand code semantics and are unable to discover deep-seated risks, achieving automation and intelligence in code review.
[0170] Through the above technical solutions, the intelligent analysis system for automated code review provided in this embodiment can improve the efficiency and accuracy of code review, reduce risks in the software development process, and help the development team better understand and maintain the code.
[0171] In one specific implementation, based on the above embodiments, the intelligent preprocessing engine M200 includes an abstract syntax tree parser and a static dependency analysis unit. The abstract syntax tree parser is configured to receive code difference data from the data acquisition module M100 and select the corresponding parser based on the programming language type of the code file; for example, selecting JavaParser for Java, KotlinParser for Kotlin, and SwiftSyntax for Swift. The abstract syntax tree parser first constructs abstract syntax trees for the code versions before and after the change, then determines the changed code segments by comparing the node differences between the two abstract syntax trees, and divides these code segments into semantic code units bounded by class definitions, function definitions, or method definitions.
[0172] The static dependency analysis unit is configured to receive semantic code units from the abstract syntax tree parser and perform static analysis on them to identify external dependencies. The static dependency analysis unit includes:
[0173] Symbol table construction module: Used to construct the symbol table of the current semantic code unit, recording symbol information such as variables, functions, and classes defined in it.
[0174] Dependency identification module: Used to scan the symbol table and identify references to external symbols. For example, it identifies function calls, class instantiations, inheritance relationships, interface implementations, and import statements from external modules. The dependency identification module can be implemented using methods such as regular expression matching, symbol table lookup, or abstract interpretation. For function calls, it identifies the function name, parameter types, and return type of the called function. For class instantiation, it identifies the class name and constructor parameter types of the instantiated class. For inheritance relationships and interface implementations, it identifies the parent class name and interface name. For import statements from external modules, it identifies the module name.
[0175] Interface definition retrieval module: This module retrieves the corresponding interface definitions based on external dependencies identified by the dependency identification module. It can search for interface definitions in a pre-built project-level symbol index database or obtain them by analyzing related files in real-time. The symbol index database can be implemented using a relational database, key-value store, or graph database. For interface definitions that cannot be retrieved from the symbol index database, the module will analyze the source files containing the dependent code units to extract the required interface definition information.
[0176] The context injection module is used to append the interface definitions obtained by the interface definition retrieval module as cross-file dependency markers to the corresponding semantic code units. The context injection module can be implemented by adding new attributes or fields to the semantic code unit object, or by modifying the metadata of the semantic code unit object.
[0177] This embodiment uses an abstract syntax tree parser to accurately segment code fragments and identifies and injects external dependencies through a static dependency analysis unit, providing more accurate and complete contextual information for subsequent analysis of a large language model, thereby improving the accuracy and efficiency of code review.
[0178] In one specific implementation, based on the above embodiments, the dynamic prompt word builder M300 is configured to read rules from a rule base. This rule base is stored in YAML format and in non-volatile memory, such as a solid-state drive (SSD) or flash memory. The rule base contains multiple rule entries, each including at least a rule ID, rule description, applicable programming language, risk level, and a template fragment for generating prompt words. The rule ID consists of letters, numbers, and underscores and is globally unique. The rule description is natural language text used to explain the purpose of the rule. The applicable programming language specifies which programming language the rule applies to for code review. The risk levels include four levels: CRITICAL, MAJOR, MINOR, and INFO. The template fragment for generating prompt words is a string containing placeholders used to dynamically insert code snippets and contextual information.
[0179] The M300 dynamic prompt word builder includes a YAML parsing module that uses a YAML parsing library (such as PyYAML or SnakeYAML) to read the rule base file and parse the rule entries into in-memory data structures. The M300 also includes a template engine that uses template languages (such as Jinja2 or FreeMarker) to combine template fragments of rule entries with code fragments and contextual information to generate complete natural language instructions.
[0180] When generating prompts, the dynamic prompt builder M300 first selects applicable rule entries from the rule base based on the programming language involved in the current code change. Then, for each applicable rule entry, the dynamic prompt builder M300 uses a template engine to combine the template fragment of the rule entry with the corresponding semantic code unit and its context information to generate a natural language instruction. Finally, the dynamic prompt builder M300 combines all the generated natural language instructions into a complete structured prompt and inputs it into the large language model analysis layer.
[0181] As an alternative, the rule base can also be stored in JSON, XML, or other structured data formats. The YAML parsing module can be replaced with a corresponding JSON or XML parsing module. The template engine can also be replaced with other template engines or implemented using string concatenation.
[0182] This embodiment achieves centralized management and dynamic configuration of code review rules by reading rules from a machine-parseable rule base and converting these rules into a set of natural language instructions, thereby improving the flexibility and maintainability of code review.
[0183] In one specific implementation, based on the above embodiments, the AI large model analysis layer M400 is configured to include a change summary generator. When the code difference data contains multiple semantic code units that are interconnected through call chains or inheritance relationships, the analysis process is as follows:
[0184] Determining the Analysis Order: The AI large-scale model analysis layer M400 first determines the analysis order of semantic code units based on dependencies. For example, if a code change in unit A depends on a code change in unit B, then unit B is analyzed first, followed by unit A. Dependency determination is based on the static dependency analysis results of the intelligent preprocessing engine M200. As an alternative, dependencies can also be determined by analyzing code commit history or explicit dependency declarations provided by the developer.
[0185] Analyzing the first unit and generating a summary: The AI large model analysis layer M400 submits the first semantic code unit (e.g., unit B) and its corresponding structured cue words to the large language model for analysis. After analysis, the change summary generator receives the output of the large language model, extracts information, and generates a concise summary of the feature change. This summary can include the change type (e.g., bug fix, new feature, performance optimization), an overview of the change, and its potential impact. The summary generator can employ word extraction, text summarization algorithms, or a pre-trained summary generation model.
[0186] Context Injection and Subsequent Analysis: The AI large-scale model analysis layer M400 instructs the dynamic prompt word builder M300 to inject a summary of functional changes as additional contextual information into the structured prompt words of subsequently associated semantic code units (e.g., unit A). Specifically, this summary can be added to the task description part of the prompt word or as a separate "background information" part. The AI large-scale model analysis layer M400 then submits the modified prompt words to the large language model for analysis.
[0187] Iterative processing: If more related semantic code units exist, repeat the above steps until all units have been analyzed. The analysis summary of each unit may serve as context information for subsequent unit analyses. The summary information is stored in an in-memory database or cache system, such as Redis or Memcached, for fast access.
[0188] Results Summary: After the analysis is completed, the AI large model analysis layer M400 passes the analysis results of all semantic code units, including risk point annotation, change type identification and summary information, to the rule-based result parser for processing, and finally the visualization report generator M500 generates a report.
[0189] Through the above structure and process, this embodiment enables large language models to better understand the dependencies and overall impact between interrelated code changes when analyzing them, thereby improving the accuracy and comprehensiveness of the analysis.
[0190] This invention provides a computing device including a processor and a memory. The memory stores a computer program, which, when executed by the processor, implements the intelligent analysis method for automated code review as described in any of the above embodiments.
[0191] The processor can be any type of processor, such as, but not limited to, a central processing unit (CPU), a graphics processing unit (GPU), a digital signal processor (DSP), a microcontroller (MCU), or an application-specific integrated circuit (ASIC). In one embodiment, the processor is a multi-core processor capable of executing multiple threads or processes in parallel. The processor communicates with memory via an internal bus or a high-speed interconnect network.
[0192] The memory can be any type of computer-readable storage medium, such as, but not limited to, random access memory (RAM), read-only memory (ROM), flash memory, hard disk drive (HDD), solid-state drive (SSD), or optical disk drive. In one embodiment, the memory includes volatile memory (e.g., RAM) and non-volatile memory (e.g., SSD). Computer programs are stored in the memory in the form of executable code, source code, bytecode, or any other form suitable for processor execution. The memory also stores various data required for program execution, such as rule bases, code difference data, and LLM analysis results.
[0193] The computer program includes instructions for an intelligent analysis method for automated code review in any of the above embodiments. Specifically, the computer program includes instructions for: acquiring code difference data resulting from target code changes; preprocessing the code difference data to generate semantic code units, the preprocessing including filtering non-code files and semantically segmenting code difference fragments; dynamically constructing structured prompts for input to a large language model according to preset review rules, the structured prompts including review rules, old and new versions of code corresponding to semantic code units, and code context information; calling the large language model to process the structured prompts to identify logically equivalent and non-equivalent changes in the code changes, and marking risk points in the code based on the review rules; and generating a visual report containing difference classification statistics and risk point distribution based on the identification and marking results of the large language model.
[0194] In one embodiment, the computing device further includes a network interface that allows the computing device to communicate with other devices, such as version control systems and LLM services. The network interface can be wired (e.g., Ethernet) or wireless (e.g., Wi-Fi).
[0195] The processor, memory, and network interface are interconnected via a system bus or other interconnection mechanisms to allow them to work together. The processor executes computer program instructions stored in memory, thereby controlling the operation of the computing device and implementing intelligent analysis methods for automated code review. Specifically, the data acquisition module M100 acquires code difference data from the version control system and stores it in memory; the intelligent preprocessing engine M200 reads the code difference data from memory, performs preprocessing operations, and stores the generated semantic code units back in memory; the dynamic prompt word constructor M300 reads the semantic code units and review rules from the rule base from memory, constructs structured prompt words, and stores the structured prompt words in memory; the AI large model analysis layer M400 reads the structured prompt words from memory, calls the LLM service for analysis through the network interface, and stores the analysis results in memory; the rule-based result parser reads the LLM analysis results from memory, parses and quantifies the risks, and stores the quantified results in memory; the visualization report generator M500 reads the quantified risk data from memory, generates a visualization report, and pushes the report to the developers through the network interface. The above modules interact with each other by sharing data in the shared memory, collaboratively completing the code review process. This structured collaborative process enables computing devices to automate code review tasks, solving technical problems in traditional code review methods such as insufficient semantic understanding, difficulty in ensuring cross-terminal consistency, and low efficiency of manual review.
[0196] Through the aforementioned structure, this computing device can effectively implement intelligent analysis methods for automated code review. By executing computer programs stored in memory and coordinating hardware resources such as processors, memory, and network interfaces, the device achieves a series of functions including code discrepancy data acquisition, preprocessing, prompt word construction, large language model analysis, result parsing and quantification, and visualization report generation, thus solving the long-standing efficiency and accuracy issues in the code review process.
[0197] This invention provides a computer program product comprising computer program instructions. When executed by a processor, these instructions implement the intelligent analysis method for automated code review described in any of the above embodiments. The specific implementation of this computer program product is as follows:
[0198] The computer program instructions are configured to perform the following steps:
[0199] Retrieve code difference data resulting from target code changes. In one embodiment, this step involves calling the version control system's application programming interface (API), such as GitLab's API, to extract the difference file corresponding to the target commit or merge request. This API could be GET / projects / {id} / merge_requests / {mr_iid} / changes, where {id} is the project ID and {mr_iid} is the internal ID of the merge request. Alternatively, the data retrieval process can be automatically triggered by listening to version control system webhook events.
[0200] The code difference data is preprocessed to generate semantic code units. The preprocessing process includes:
[0201] File type filtering: Program instructions are configured to identify and exclude non-code files, such as image files (.jpg, .png) or configuration files (.xml, .json). File type filtering can be achieved by checking a list of file extensions.
[0202] Semantic segmentation: For code segments with discrepancies, program instructions use an Abstract Syntax Tree (AST) parser (e.g., JavaParser for Java code; the ast module for Python code) to divide the code into semantic code units bounded by class definitions, function definitions, or method definitions. The AST parser analyzes the code structure and extracts independently understandable logical blocks. As an alternative, program instructions can also achieve similar code segmentation based on regular expression matching of code structure.
[0203] Based on preset review rules, structured prompt words are dynamically constructed for input into a large language model. This step includes:
[0204] Read preset review rules from the rule base: The rule base can be stored in a database (such as MySQL, PostgreSQL) or a configuration file (such as YAML, JSON).
[0205] The technical review indicators are translated into natural language instructions: The program instructions utilize natural language generation technology to convert the technical indicators in the rule base into human-readable instructions. For example, the rule "Avoid using outdated APIs" is translated into "Please check your code for calls to deprecated APIs." Structured prompts can be in JSON or XML format for easier subsequent parsing.
[0206] Structured hints include review rules, the old and new versions of code corresponding to semantic code units, and code context information. Code context information includes, for example, code comments, function signatures, or other relevant code snippets.
[0207] The program invokes a large language model to process structured prompts. The program instructions are configured to communicate with the large language model via HTTP or gRPC. The large language model can be a remote API service (e.g., OpenAI GPT series, Google PaLM series) or a locally deployed large language model (e.g., LLaMA, ChatGLM). The choice of large language model can be based on factors such as the model's code comprehension capabilities, API call costs, and data security.
[0208] Based on the recognition and annotation results of the large language model, a visual report is generated that includes differential classification statistics and risk point distribution. The program parses the results returned by the large language model (usually in JSON format) and transforms them into an easy-to-understand visual format. The visual report can be presented in HTML, Markdown, or PDF format and includes charts, highlighted code snippets, and risk level annotations. Differential classification statistics can be displayed using bar charts or pie charts, and risk point distribution information can be displayed using heatmaps or scatter plots.
[0209] In one embodiment, the program instructions can also be configured to analyze the first semantic code unit to generate a feature change summary when the code difference data contains multiple interrelated semantic code units, and to inject the feature change summary as additional contextual information into the corresponding structured prompt words when analyzing subsequent related semantic code units.
[0210] In one implementation, the computer program instructions can also be used for code logic consistency verification across language platforms. In this case, the program instructions are configured to add specific instructions to the structured prompts, requiring the large language model to ignore syntactic differences between different programming languages and focus on comparing the consistency of their algorithmic logic.
[0211] The aforementioned technical features work together in a coordinated manner. First, by acquiring and preprocessing code difference data, unstructured code information is transformed into structured semantic code units, laying the foundation for subsequent analysis. Then, dynamically constructed structured prompts effectively transmit review rules, code change details, and contextual information to the large language model, guiding it to perform accurate analysis. Based on the instructions in the prompts, the large language model identifies logical equivalence, non-equivalence, and potential risks in the code changes, returning the results in a structured format. Finally, through the generation of a visual report, the analysis results are presented to developers in an intuitive way, helping them quickly understand the impact of code changes and promptly identify potential problems. Through the synergistic effect of these steps, this solution solves the problems of semantic understanding difficulties, low efficiency, and difficulty in risk detection inherent in traditional code review methods.
[0212] The computer program product provided in this embodiment controls the processor to execute each step of automated code review through program instructions. It can automate the traditional time-consuming and labor-intensive code review work that requires manual completion, greatly improve the efficiency and accuracy of code review, and effectively reduce potential risks in the software development process.
[0213] The above description, in conjunction with specific preferred embodiments, provides a further detailed explanation of the present invention. It should not be construed that the specific implementation of the present invention is limited to these descriptions. For those skilled in the art, various simple deductions or substitutions can be made without departing from the concept of the present invention, and all such modifications and substitutions should be considered within the scope of protection of the present invention.< / code> < / pre>
Claims
1. An intelligent analysis method for automated code review, characterized in that, include: Obtain code difference data resulting from target code changes; The code difference data is preprocessed to generate semantic code units. The preprocessing includes filtering non-code files and semantically segmenting the code difference fragments. Based on preset review rules, structured prompt words for input into a large language model are dynamically constructed. The structured prompt words include the review rules, the old and new versions of the code corresponding to the semantic code unit, and code context information. The large language model is invoked to process the structured prompt words to identify logically equivalent and non-equivalent changes in the code changes, and risk points in the code are marked based on the review rules; Based on the recognition and annotation results of the large language model, a visual report containing differential classification statistics and risk point distribution is generated.
2. The method according to claim 1, characterized in that, Obtaining the code difference data includes: By calling the application programming interface of the version control system, the difference file corresponding to the target commit or merge request can be extracted.
3. The method according to claim 2, characterized in that, Also includes: Based on the preset code repository mapping relationship, multiple code repositories deployed on different terminals are automatically associated to obtain cross-platform code difference data generated to implement the same business function.
4. The method according to claim 1, characterized in that, Semantic segmentation of the code difference fragments includes: Using an abstract syntax tree parser for the programming language of the code, the code difference fragments are segmented into semantic code units bounded by class definitions or function definitions.
5. The method according to claim 4, characterized in that, The preprocessing also includes: Static dependency analysis is performed on each of the semantic code units to identify the external functions it calls or the external classes it references.
6. The method according to claim 5, characterized in that, The preprocessing also includes: The interface definition of the external function or class is appended as a cross-file dependency tag to the corresponding semantic code unit as part of the code context information.
7. The method according to claim 1, characterized in that, Dynamically constructing the structured prompt words includes: The preset review rules are read from the rule base stored in a machine-readable format.
8. An intelligent analysis system for automated code review, characterized in that, include: The data acquisition module is used to acquire code difference data resulting from changes to the target code; An intelligent preprocessing engine is used to preprocess the code difference data to generate semantic code units. The preprocessing engine is configured to filter non-code files and perform semantic segmentation on code difference fragments. A dynamic prompt word constructor is used to dynamically construct structured prompt words for input into a large language model according to preset review rules. The structured prompt words include the review rules, the old and new versions of the code corresponding to the semantic code unit, and code context information. The AI large model analysis layer is used to call a large language model to process the structured prompt words, so as to identify the logically equivalent and non-equivalent changes in the code changes, and mark the risk points in the code based on the review rules. A visualization report generator is used to generate a visualization report containing differential classification statistics and risk point distribution based on the recognition and annotation results of the large language model.
9. A computing device, characterized in that, It includes a processor and a memory, wherein the memory stores a computer program that, when executed by the processor, implements the method as described in any one of claims 1 to 7.
10. A computer program product, characterized in that, It includes computer program instructions, which, when executed by a processor, are used to implement the method as described in any one of claims 1 to 7.
Citation Information
Cited By
Semantized analysis method and system for version difference of three-dimensional assembly
CN121543597A
Private data compliance auxiliary evaluation method and system based on large language model
CN122065342A
Robot skill primitive library automatic generation method and system based on large language model
CN122311404A
