An automatic constructor method and system for runtime assertions within source code repositories

CN122570283APending Publication Date: 2026-08-14NANJING UNIV
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202610682431.3
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-05-18
Publication Date
2026-08-14

AI Technical Summary

Technical Problem

[0007]发明目的:提出一种面向代码仓库的源码内运行时断言自动构造方法及系统,旨在解决现有源码侧断言生成方案中存在的检查对象选择不准确、插装位置不可靠、仓库级信息利用不足以及生成输出不规范的问题

Benefits of technology

[0020]与现有技术相比,本发明具有如下有益效果:一是利用候选断言锚点四元组明确断言生成对象,降低低价值变量干扰;二是利用tree-sitter等源码语法树工具校正插装位置,减少不可执行或越界引用;三是利用变量来源、方法实现、类结构和相关状态构建结构化上下文,提高生成依据的相关性;四是通过受限生成和输出清洗得到格式规范、便于写入源码的目标断言语句。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122570283A_ABST
    Figure CN122570283A_ABST
Patent Text Reader

Abstract

This invention provides a method and system for automatically constructing runtime assertions within source code for code repositories. The method includes: reading the source code method to be processed and its associated code repository; identifying suitable program elements for runtime verification from the source code; filtering program elements using candidate selection rules; calibrating approximate source code locations given by the model into instrumentable landing points using syntax tree parsing results; extracting relevant context from the repository source code around the program elements to form a source code evidence package; inputting the instrumented source code fragments, instrumented landing points, and source code evidence package into a large language model to generate candidate assertions; and performing compilation verification and execution trigger verification on the candidate assertions to obtain target assertions that can be written into the source code. This method can supplement runtime checks for critical execution paths in real code repositories without relying on complete manual test predictions, improving the constraint expression ability, compileability, and defect exposure ability during code evolution.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of automated software engineering, and in particular to a method and system for automatically constructing runtime assertions within source code for code repositories. Background Technology

[0002] In real-world software projects, program behavior is typically distributed across method parameters, local variables, return expressions, class fields, helper methods, and control structures. Unit tests can verify some external behaviors, but without explicit verification of internal method state changes, object relationships, and calling protocols in the source code execution path, regression issues that arise during code evolution may be difficult to expose in a timely manner.

[0003] Existing automated assertion generation technologies mostly revolve around test cases or local code snippets, typically relying on test inputs and outputs, execution paths, template rules, or local program structures to generate assertions. While these methods are effective in test completion scenarios, when dealing with repository-level source code, program constraints are often distributed across methods, classes, and files. It's difficult to determine the program objects to be checked based solely on local snippets, and it's also difficult to pinpoint the exact location where code can be written into the source code.

[0004] Directly generating assertions from source code fragments using large language models still suffers from unstable results. Without pre-screening program objects, large language models are prone to generating low-value assertions around loop counters, temporary variables, or log objects; without correcting insertion positions based on the syntax tree, the generated results may reference invisible variables or be placed in non-executable paths; and without constructing a structured context, large language models struggle to generate assertions with practical constraints based on variable sources, method implementations, class structures, and related states.

[0005] Specifically, there are significant differences between code repository-level scenarios and single test case scenarios. In a single test case, the object to be verified is usually naturally defined by the test input, the call statement, and the expected output; however, within the source code, the object to be verified needs to be actively identified from method implementation, local state, field access, control path, and call results. Without a candidate object selection mechanism, large language models are prone to mistaking syntactically obvious but semantically low-value objects as assertion objects.

[0006] Furthermore, in real-world projects, program semantics are often distributed across statements, methods, and even classes. For example, a return value may be formed by multiple helper methods, the state of an object may be determined by the constructor and field updates, and control conditions may affect multiple subsequent execution paths. If a large language model only receives a small amount of code near the instrumentation location, it may easily miss key evidence that determines the assertion content; if too much source code is directly input, it will introduce a lot of irrelevant information, reducing the stability of the generated results. Summary of the Invention

[0007] Purpose of the invention: To propose an automatic method and system for constructing runtime assertions within source code repositories, aiming to solve the problems of inaccurate selection of inspection objects, unreliable instrumentation positions, insufficient utilization of repository-level information, and non-standardized generation output in existing source code-side assertion generation schemes.

[0008] This invention proposes an automatic method for constructing runtime assertions within source code repositories, with the following steps:

[0009] Read the source code method to be processed and the related source code files in the code repository where the source code method to be processed is located; The source code method to be processed is input into a large language model, and semantic analysis is performed on the source code method based on a predefined selection principle to obtain a candidate assertion anchor list; each candidate assertion anchor in the candidate assertion anchor list includes name, type, category and source code location; The source code position of the candidate assertion anchor is corrected based on the source code syntax tree to obtain the corresponding precise instrumentation position and positioning information. Around the candidate assertion anchor, variable source information, method implementation information, class structure information, and related state information are extracted from the code repository, and a structured context is constructed. The source code snippet with instrumentation tags, the precise instrumentation location, the positioning information, and the structured context are input into the large language model to generate candidate assertion statements; The candidate assertion statements are cleaned and verified to obtain target assertion statements that can be written into the source code.

[0010] As a preferred embodiment, the predefined selection principles include a positive selection principle and a negative exclusion principle; The positive selection principle is used to select program objects that reflect input constraints, return result formation process, state changes, branch effects, or method call protocols; The reverse exclusion principle is used to exclude loop counter variables, log objects, temporary transition variables, variables that only forward parameters, and objects that are already directly guaranteed by the local control flow.

[0011] As a preferred embodiment, the categories of the candidate assertion anchors include input parameter class, return class, condition class, and ordinary execution class; wherein, the input parameter class corresponds to method parameters, the return class corresponds to variables or method calls in return statements, the condition class corresponds to variables that affect the control flow and continue to have an effect in subsequent execution, and the ordinary execution class corresponds to objects with independent verification significance other than the input parameter class, return class, and condition class.

[0012] As a preferred option, the source code syntax tree is generated by a tree-sitter parser.

[0013] As a preferred embodiment, obtaining the corresponding precise insertion position and positioning information specifically includes: When the candidate assertion anchor is an input parameter class, the candidate assertion anchor is confirmed in the parameter list of the method declaration, and the first executable position after the method declaration is determined as the precise instrumentation position. When the candidate assertion anchor is a return type, locate the return statement containing the candidate assertion anchor, and determine the position before the return statement as the precise instrumentation position; When the candidate assertion anchor is a conditional class, locate the minimum control structure that covers its source code location, and determine the reachable position after the minimum control structure ends as the precise instrumentation position. When the candidate assertion anchor is a normal execution class, locate the smallest complete statement that covers its source code location, and determine the reachable location after the smallest complete statement as the precise instrumentation location.

[0014] As a preferred embodiment, obtaining the corresponding precise insertion position and positioning information further includes: Based on statement boundaries, code block boundaries, return statements, exception-throwing statements, and scope, the reachability of the precise instrumentation location is checked, and the visibility of the candidate assertion anchors is checked.

[0015] As a preferred embodiment, the step of extracting variable source information, method implementation information, class structure information, and related state information from the code repository around the candidate assertion anchor, and constructing a structured context, specifically includes: Extract the definition statement, assignment statement, first use position, and subsequent propagation position of the candidate assertion anchor points to form the variable source information; Extract the method body, constructor body, call statement, and return expression associated with the candidate assertion anchor to form the method implementation information; Extract the class, associated type, field declaration, constructor signature, and accessible members of the candidate assertion anchor to form the class structure information; Extract static fields, shared states, usage positions before and after branches, and object state change information related to the candidate assertion anchors to form the relevant state information; The variable source information, the method implementation information, the class structure information, and the relevant state information are combined into the structured context.

[0016] As a preferred embodiment, the generation of candidate assertion statements specifically includes: An insertion mark is set at the precise insertion position; The large language model is constrained to only reference variables, fields, and methods visible at the precise instrumentation location; The large language model is constrained to generate only one Java assertion statement around a single candidate assertion anchor.

[0017] As a preferred embodiment, the generation of candidate assertion statements further includes: The constraints on the large language model prohibit the generation of null value checks, simple upper and lower bound checks, identity checks, type tautology checks, checks of repeated local control flow conditions, and method calls that include state modification behavior.

[0018] Furthermore, this invention proposes an automatic construction system for runtime assertions within source code repositories, which is used to execute the aforementioned methods. The system includes: The source code reading module is used to read the source code methods to be processed, as well as related source code files in the code repository. Anchor point identification module is used to generate a list of candidate assertion anchor points based on predefined selection principles; The position correction module is used to obtain accurate instrumentation position and positioning information based on the source code syntax tree; The context building module is used to extract variable source information, method implementation information, class structure information, and related state information, and to build a structured context; The assertion generation module is used to generate candidate assertion statements based on source code snippets with instrumentation tags, precise instrumentation locations, location information, and structured context. The output cleaning module is used to clean and verify the candidate assertion statements and obtain the target assertion statement.

[0019] Furthermore, the present invention also proposes a computer device comprising a processor and a memory storing computer program instructions; the processor, when executing the computer program instructions, implements the steps of the above-described method.

[0020] Compared with existing technologies, this invention has the following advantages: First, it uses candidate assertion anchor quadruples to clarify the assertion generation object and reduce interference from low-value variables; second, it uses source code syntax tree tools such as tree-sitter to correct the instrumentation position and reduce non-executable or out-of-bounds references; third, it uses variable sources, method implementations, class structures, and related states to construct a structured context and improve the relevance of the generation basis; and fourth, it obtains target assertion statements with standardized formats that are easy to write into the source code through restricted generation and output cleaning. Attached Figure Description

[0021] Figure 1 The overall flowchart of the runtime assertion automatic construction method provided in the source code for embodiments of the present invention is shown.

[0022] Figure 2 A flowchart for candidate assertion anchor point identification and position correction provided in an embodiment of the present invention.

[0023] Figure 3 This is a schematic diagram illustrating the construction of a structured context provided in an embodiment of the present invention.

[0024] Figure 4 This is a schematic diagram of the structure of the runtime assertion automatic construction system provided in the source code according to an embodiment of the present invention. Detailed Implementation

[0025] In the following description, numerous specific details are set forth in order to provide a more thorough understanding of the invention. However, it will be apparent to those skilled in the art that the invention can be practiced without one or more of these details. In other instances, certain technical features well-known in the art have not been described in order to avoid obscuring the invention.

[0026] This invention breaks down the construction of assertions within the source code into consecutive stages: candidate assertion anchor point identification, position correction, structured context construction, restricted assertion generation, and output cleaning. Data between each stage is connected by candidate assertion anchor point quadruples, precise instrumentation positions, and structured contexts, thus ensuring the generation process has clear input boundaries and verifiable intermediate results. The specific scheme is as follows: The system reads the source code files of the methods and code repositories to be processed; performs semantic analysis based on predefined selection principles using a large language model to obtain a list of candidate assertion anchors; corrects the position of the candidate assertion anchors using the source code syntax tree to obtain precise instrumentation positions and location information; extracts variable sources, method implementations, class structures, and related states around the candidate assertion anchors to form a structured context; inputs the source code fragments with instrumentation tags, precise instrumentation positions, and structured context into the large language model to generate candidate assertion statements; and cleans the output of the candidate assertion statements to obtain the target assertion statement.

[0027] To facilitate the explanation of the data relationships between the various processing stages of this invention, the key objects in the method are defined below in conjunction with formulas. Let the source code method to be processed be C, the predefined selection principle be R, the set of identifiable candidate program objects in source code method C be V(C), and the set of candidate assertion anchor points obtained after candidate selection be T. Then the candidate selection process is expressed as: T = SelectTargets(C, R), and T V(C)(1) In equation (1), SelectTargets represents the candidate object filtering operation performed based on predefined selection principles. This operation does not enumerate all variables in the source code indiscriminately, but combines the forward selection principle and the reverse exclusion principle to retain program objects that can reflect input constraints, return formation process, object state changes, branch effects, or calling protocols.

[0028] For any candidate assertion anchor ti in the set of candidate assertion anchors T, its structure can be represented as a quadruple: t i = <name i type i , category i , line i (2) In equation (2), name i Indicates the variable name or method name, type i Indicates the variable type or method call type, category i Indicates the input parameter class, return class, condition class, or ordinary execution class, line i This represents the approximate source code location given by the large language model. This quadruple matches the list of candidate assertion anchors in the abstract appendix and is used for subsequent location correction and structured context construction.

[0029] Furthermore, let the source code syntax tree be A, and the position correction function be FixLine, then the precise instrumentation position line of the candidate assertion anchor ti is... i Represented as: line i = FixLine(t i (3) In equation (3), FixLine is based on category i Choose different positioning strategies: for parameter-type anchors, locate the first executable position after the method declaration; for return-type anchors, locate the position before the corresponding return statement; for condition-type anchors, locate the reachable position after the end of the control structure; for ordinary execution-type anchors, locate the position after the smallest complete statement.

[0030] To ensure that the instrumentation result is executable and that symbolic references are valid, the precise instrumentation location must also satisfy the following constraints: Reachable(line i If (, A, C) = true, and Visible(t) i , line i ) = true(4) In equation (4), Reachable is used to determine the line iWhether it is located on the executable path, Visible uses this to determine whether the candidate assertion anchor and its related symbols are on the line. i Whether a location is visible. Only candidate assertion anchors that simultaneously satisfy both reachability and visibility will proceed to the structured context construction phase.

[0031] Let the code repository be Repo, and the structured context extraction function be Extract. Then, the context representation built around the candidate assertion anchor ti is as follows: Ctx(t i = Extract(Repo, t) i , line i (5) Wherein, Ctx(t) i This is not a simple concatenation of adjacent lines of code, but rather relevant source code evidence gathered and organized from the code repository around ti. Furthermore, this structured context can be represented as: Ctx(t i ) = <Obj(t i ), State(t i ), Exec(t i ), Scope(t i (6) In equation (6), Obj(t) i ) represents the object description information of the candidate assertion anchor, State(t) i ) represents information about changes in field, shared state, and object state. Exec(t) i ) represents the method implementation, constructor body, call statement, and return expression information. Scope(t) i ) indicates the class, method, statement boundary, and scope of accessible symbols where the instrumentation location is located.

[0032] Let the source code snippet with instrumentation tags be CodeMark, the generation constraint be P, the large language model be Gen, and the output cleaning function be Clean. Then the target assertion statement a i It can be represented as: a i = Clean( Gen(CodeMark, line i , Ctx(t i ), P) )(7) In equation (7), P represents the set of generation constraints, which is used to limit the large language model to generate a single assertion statement with no side effects and with actual constraint meaning based only on the source code fragment, the precise instrumentation position and the structured context.

[0033] The location correction phase converts the approximate source code location of candidate assertion anchors into actual instrumentable locations. For parameter-type anchors, the system confirms their existence in the method declaration parameter list and uses the first executable location after the method declaration as the instrumentation location; for return-type anchors, the system locates the return statement containing the anchor and uses the location before the return statement as the instrumentation location; for condition-type anchors, the system locates the minimum control structure and uses the reachable location after the end of the control structure as the instrumentation location; for ordinary execution-type anchors, the system locates the minimum complete statement and uses the reachable location after that statement as the instrumentation location.

[0034] The structured context construction phase is used to organize information related to candidate assertion anchors in the repository into input that can be used by the large language model. This structured context includes four types of information: variable source, method implementation, class structure, and related state, which correspond to the context construction section in the abstract figure.

[0035] The assertion generation phase is used for restricted reasoning based on a structured context. The system sets instrumentation markers at precise instrumentation locations and requires the large language model to only reference symbols accessible at those locations. It generates only one Java assertion statement around a single candidate assertion anchor and avoids generating null value checks, simple upper and lower bound checks, identity checks, type tautology checks, and method calls with side effects.

[0036] The output cleaning phase is used to extract assertion statements that can be written into source code from the output of the large language model. The system removes explanatory text, code block markers, redundant line breaks, and non-assertion content, retaining single candidate assertions that appear in the form of assert statements or assertion library calls, and uses these as target assertion statements.

[0037] In one embodiment, such as Figure 1 As shown, this invention provides an automatic method for constructing runtime assertions within the source code of a code repository. This method executes in the following order: "source code reading, anchor point identification, position correction, context construction, assertion generation, output cleaning, and target output," and includes the following steps: Step 101: Read the source code method to be processed and the relevant source code files in the code repository.

[0038] The source code method to be processed can be any method or constructor in a Java project. Related source code files may include the class containing the method to be processed, the class containing the associated type, the class containing the called method, the class containing the field declarations, and source code files within the project related to parameters or return expressions. The system records the source code file path, package name, class name, method signature, method start and end line numbers, and statement line number mappings.

[0039] Step 102: Perform semantic analysis based on predefined selection principles to generate a list of candidate assertion anchors.

[0040] Step 102-1: Configure predefined selection principles. These predefined principles include forward selection and reverse exclusion principles. Forward selection prioritizes program objects that reflect input constraints, return result formation processes, object state changes, branch effects, or calling protocols. Reverse exclusion excludes loop counter variables, log objects, temporary transition variables, variables that only forward parameters, and objects whose behavior is directly guaranteed by local control flow. The candidate assertion anchor list is generated in two phases. The first phase only determines whether the variable or method call result has verification value; the second phase supplements the identified objects with their name, type, category, and source code location, forming a candidate assertion anchor quadruple t. i = <name i type i , category i , line i The categories in a quadruple can include input parameter categories, return categories, condition categories, and ordinary execution categories.

[0041] Step 102-2: Output the set of candidate assertion anchors T. The corresponding formula is T = SelectTargets(C, R), and T... V(C), the system uses the set of candidate assertion anchor points as the position correction input for step 103.

[0042] Step 103: Perform position correction based on the tree-sitter source code syntax tree to obtain accurate instrumentation position and positioning information.

[0043] Step 103-1: The system uses a tree-sitter parser to parse the source code method to be processed into a source code syntax tree A, and adopts different correction strategies according to the category of candidate assertion anchors. For parameter-type anchors, the system confirms the anchor name in the parameter list of the method declaration and takes the first executable position after the method declaration as the precise instrumentation position; for return-type anchors, the system locates the return statement containing the anchor name and takes the position before the return statement as the precise instrumentation position; for condition-type anchors, the system locates the smallest control structure covering its approximate source code position and takes the reachable position after the end of the control structure as the precise instrumentation position; for ordinary execution-type anchors, the system locates the smallest complete statement covering its approximate source code position and takes the reachable position after that statement as the precise instrumentation position.

[0044] Step 103-2: After completing category location, the system performs reachability and visibility checks. The reachability check determines whether the precise instrumentation location is after the scope of a `return` statement, `throw` statement, or method. The visibility check determines whether the candidate assertion anchor and its potentially referenced parameters, local variables, fields, and methods are visible at that instrumentation location. If the candidate location is unreachable or the candidate object is not visible, the candidate assertion anchor is deleted or the system returns to step 102 for re-annotation. The final output location information includes the statement containing the candidate assertion anchor, the method it belongs to, the variables, fields, and methods visible at the precise instrumentation location, and the category matching result. (Corresponding formula: line) i = FixLine(t i (A, C) and satisfying Reachable(line i (, A, C) = true and Visible(t) i , line i = true.

[0045] Step 104: Construct a structured context around the candidate assertion anchors.

[0046] Specifically, such as Figure 3 As shown, the input for constructing a structured context includes candidate assertion anchors, precise instrumentation locations, location information, and source code from the code repository. The system extracts four types of information from the code repository, centered on the candidate assertion anchors: variable origin, method implementation, class structure, and related state. Variable origin includes definition statements, assignment statements, initial usage locations, and subsequent propagation locations; method implementation includes related method bodies, constructor bodies, call statements, and return expressions; class structure includes the class to which the candidate assertion anchor belongs, associated types, field declarations, constructor signatures, and accessible members; and related state includes static fields, shared state, usage locations before and after branches, and object state change information.

[0047] When constructing the structured context, the system adjusts the extraction focus based on the candidate assertion anchor category. Input parameter anchors emphasize the parameter type and its first computational entry; return parameter anchors emphasize the composition of the return expression and the source of the return value; conditional anchors emphasize state changes within and outside the control structure; and ordinary execution anchors emphasize the assignment source, related call implementation, and subsequent propagation path. The system also performs filtering, deduplication, and scope constraints, deleting simple value-taking methods, simple value-setting methods, standard library implementations, duplicate method bodies, and source code fragments unrelated to candidate assertion anchors. It also removes out-of-bounds information based on the visible symbol range obtained in step 103. Finally, the system combines the variable source, method implementation, class structure, and related states into Ctx(t i ) = <Obj(t i ), State(ti ), Exec(t i ), Scope(t i )>.

[0048] Step 105: Generate candidate assertion statements.

[0049] Specifically, the system sets an instrumentation marker at the precise instrumentation location obtained in step 103, and inputs the source code fragment with the instrumentation marker, candidate assertion anchors, location information, and structured context into the large language model. The large language model is required to only reference variables, fields, and methods visible at the precise instrumentation location, generate only one Java assertion statement around a single candidate assertion anchor, and must not generate multiple assertions, helper methods, explanatory text, or additional control structures. Furthermore, it must not call methods with state modification side effects, and must not generate null value checks, simple upper and lower bound checks, identity checks, type tautology checks, or checks that repeat local control flow conditions.

[0050] The large language model outputs candidate assertion statements under the above constraints. The corresponding formula is Gen(CodeMark, line i ,Ctx(t i ), P), where CodeMark represents a source code segment with instrumentation marks, line i Indicates the precise insertion position, Ctx(t) i ) represents the structured context, and P represents the set of generating constraints.

[0051] Step 106: Clean the output of candidate assertion statements.

[0052] Specifically, the system cleans the candidate assertion statements output by the large language model, removing natural language explanations, analysis processes, code block markers, redundant line breaks, and non-Java statements. It matches single assertion statements appearing as assertion statements or assertion library calls, and cleans up semicolons, indentation, and wrapping symbols on the retained assertion statements. If an assertion statement cannot be uniquely matched, the output is deemed invalid. Optionally, the system further performs syntax checks, scope checks, compilation verification, and runtime trigger verification to exclude assertion statements with syntax errors, out-of-bounds references, and those that cannot be executed. (Corresponding formula a) i = Clean(Gen(CodeMark, line i , Ctx(t i ), P)).

[0053] Step 107: Output the target assertion statement.

[0054] Specifically, the system identifies the target assertion statements by outputting cleaned and optional verified assertion statements. These target assertion statements can be written to the precise instrumentation location of the source code method to be processed, or they can be output as source code modification suggestions awaiting manual confirmation.

[0055] In another embodiment, such as Figure 2 As shown, candidate assertion anchor identification and position correction form a processing chain. Step 101 provides the source code method and line number mapping to be processed; Step 102 uses predefined selection principles and a large language model to output candidate assertion anchor quadruples; Step 103 uses a tree-sitter source code syntax tree, category-based positioning, reachability checks, and visibility checks to obtain the precise instrumentation position and positioning information.

[0056] In another embodiment, such as Figure 3 As shown, the construction of the structured context revolves around step 104. Candidate assertion anchors and source code from the code repository are jointly input into the context extraction and organization process. The system generates variable sources, method implementations, class structures, and related states, and outputs the structured context after filtering, deduplication, and scope constraints.

[0057] In another embodiment, such as Figure 4 As shown, the present invention also provides an automatic assertion construction system for runtime within source code repositories, including a source code reading module, an anchor point identification module, a position correction module, a context construction module, an assertion generation module, and an output cleaning module.

[0058] The source code reading module (corresponding to step 101) is used to read the source code method to be processed and related source code files. The anchor point identification module (corresponding to step 102) is used to generate candidate assertion anchor point quadruples. The position correction module (corresponding to step 103) is used to determine the precise instrumentation position and location information based on the tree-sitter source code syntax tree. The context construction module (corresponding to step 104) is used to construct a structured context. The assertion generation module (corresponding to step 105) is used to generate candidate assertion statements. The output cleaning module (corresponding to step 106) is used to clean and normalize the candidate assertion statements. The system finally outputs the target assertion statement, corresponding to step 107.

[0059] Those skilled in the art will understand that the above modules can be implemented in software, hardware, or a combination of both. When implemented in software, the modules can be deployed in the same computing device or in multiple computing devices; when implemented in hardware, the modules can be integrated into a processor, a programmable logic device, or a dedicated computing unit.

[0060] The above description is merely a preferred embodiment of the present invention and is not intended to limit the scope of protection of the present invention. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of the present invention should be included within the scope of protection of the present invention.

Claims

1. A method for automatically constructing runtime assertions within source code repositories, characterized in that, Includes the following steps: Read the source code method to be processed and the related source code files in the code repository where the source code method to be processed is located; The source code method to be processed is input into a large language model, and semantic analysis is performed on the source code method based on a predefined selection principle to obtain a candidate assertion anchor list; each candidate assertion anchor in the candidate assertion anchor list includes name, type, category and source code location; The source code position of the candidate assertion anchor is corrected based on the source code syntax tree to obtain the corresponding precise instrumentation position and positioning information. Around the candidate assertion anchor, variable source information, method implementation information, class structure information, and related state information are extracted from the code repository, and a structured context is constructed. The source code snippet with instrumentation tags, the precise instrumentation location, the positioning information, and the structured context are input into the large language model to generate candidate assertion statements; The candidate assertion statements are cleaned and verified to obtain target assertion statements that can be written into the source code.

2. The method for automatically constructing runtime assertions within source code for code repositories according to claim 1, characterized in that, The predefined selection principles include positive selection principles and negative exclusion principles; The positive selection principle is used to select program objects that reflect input constraints, return result formation process, state changes, branch effects, or method call protocols; The reverse exclusion principle is used to exclude loop counter variables, log objects, temporary transition variables, variables that only forward parameters, and objects that are already directly guaranteed by the local control flow.

3. The method for automatically constructing runtime assertions within source code for code repositories according to claim 1, characterized in that, The categories of candidate assertion anchors include input parameter type, return type, condition type, and normal execution type; The input parameter class corresponds to method parameters, the return class corresponds to variables or method calls in the return statement, the condition class corresponds to variables that affect the control flow and continue to have an effect in subsequent execution, and the ordinary execution class corresponds to objects with independent verification significance other than the input parameter class, return class, and condition class.

4. The method for automatically constructing runtime assertions within source code for code repositories according to claim 1, characterized in that, The source code syntax tree is generated by a tree-sitter parser; The process of obtaining the corresponding precise insertion position and positioning information specifically includes: When the candidate assertion anchor is an input parameter class, the candidate assertion anchor is confirmed in the parameter list of the method declaration, and the first executable position after the method declaration is determined as the precise instrumentation position. When the candidate assertion anchor is a return type, locate the return statement containing the candidate assertion anchor, and determine the position before the return statement as the precise instrumentation position; When the candidate assertion anchor is a conditional class, locate the minimum control structure that covers its source code location, and determine the reachable position after the minimum control structure ends as the precise instrumentation position. When the candidate assertion anchor is a normal execution class, locate the smallest complete statement that covers its source code location, and determine the reachable location after the smallest complete statement as the precise instrumentation location.

5. The method for automatically constructing runtime assertions within source code for code repositories according to claim 4, characterized in that, The process of obtaining the corresponding precise insertion position and positioning information also includes: Based on statement boundaries, code block boundaries, return statements, exception-throwing statements, and scope, the reachability of the precise instrumentation location is checked, and the visibility of the candidate assertion anchors is checked.

6. The method for automatically constructing runtime assertions within source code for code repositories according to claim 1, characterized in that, The process of extracting variable source information, method implementation information, class structure information, and related state information from the code repository around the candidate assertion anchor, and constructing a structured context, specifically includes: Extract the definition statement, assignment statement, first use position, and subsequent propagation position of the candidate assertion anchor points to form the variable source information; Extract the method body, constructor body, call statement, and return expression associated with the candidate assertion anchor to form the method implementation information; Extract the class, associated type, field declaration, constructor signature, and accessible members of the candidate assertion anchor to form the class structure information; Extract static fields, shared states, usage positions before and after branches, and object state change information related to the candidate assertion anchors to form the relevant state information; The variable source information, the method implementation information, the class structure information, and the relevant state information are combined into the structured context.

7. The method for automatically constructing runtime assertions within source code for code repositories according to claim 1, characterized in that, The generation of candidate assertion statements specifically includes: An insertion mark is set at the precise insertion position; The large language model is constrained to only reference variables, fields, and methods visible at the precise instrumentation location; The large language model is constrained to generate only one Java assertion statement around a single candidate assertion anchor.

8. The method for automatically constructing runtime assertions within source code for code repositories according to claim 7, characterized in that, The generation of candidate assertion statements also includes: The constraints on the large language model prohibit the generation of null value checks, simple upper and lower bound checks, identity checks, type tautology checks, checks of repeated local control flow conditions, and method calls that include state modification behavior.

9. A source code-based runtime assertion automatic construction system for code repositories, characterized in that, For executing the source code-based runtime assertion automatic construction method for code repositories as described in any one of claims 1 to 8, the system comprises: The source code reading module is used to read the source code methods to be processed, as well as related source code files in the code repository. Anchor point identification module is used to generate a list of candidate assertion anchor points based on predefined selection principles; The position correction module is used to obtain accurate instrumentation position and positioning information based on the source code syntax tree; The context building module is used to extract variable source information, method implementation information, class structure information, and related state information, and to build a structured context; The assertion generation module is used to generate candidate assertion statements based on source code snippets with instrumentation tags, precise instrumentation locations, location information, and structured context. The output cleaning module is used to clean and verify the candidate assertion statements and obtain the target assertion statement.

10. A computer device, characterized in that, include: Processor and memory storing computer program instructions; When the processor executes the computer program instructions, it implements the steps of the source code-oriented runtime assertion automatic construction method as described in any one of claims 1 to 8.