A program termination verification method based on rank function composition

CN122614693BActive Publication Date: 2026-09-25ZHONGKE NANJING SOFTWARE TECH RES INST
View PDF 2 Cites 0 Cited by

Patent Information

Application Number
CN202611097442.1
Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2026-07-23
Publication Date
2026-09-25
Estimated Expiration
2046-07-23

AI Technical Summary

Technical Problem

这种方法虽然突破了模板表达力的限制,但仍面临突出的可靠性挑战:由于秩函数定义抽象、终止性证明要求严格,大语言模型很容易在生成过程中产生事实性错误或不符合证明规范的内容,即“幻觉”现象,导致单次生成的候选结果往往存在断言逻辑不成立、变量命名不一致甚至程序语义被意外篡改等问题,且缺乏可靠的手段对生成结果的正确性进行系统性验证和修复

Benefits of technology

本发明基于秩函数合成的程序终止性验证方法通过大语言模型将抽象的程序循环终止性验证任务转化为受严格格式约束的代码占位符和断言占位符填充任务,降低了程序终止性验证的认知难度,使得大语言模型能够在预设的结构化提示词空间内可靠地发挥其生成潜力,从而突破了传统方法在表达能力上的固有瓶颈;同时,在大语言模型的结构化提示词的构建过程中融合了秩函数合成领域专家知识与少样本示例,能够有效引导大语言模型的上下文学习与推理过程,使其生成的候选程序具有更高的初始规范性与逻辑指向性。其次,将候选程序依次进行等价性检查、代码-断言完整性检查以及断言有效性检查,从程序语法等价性、断言规范完整性到逻辑有效性三个维度对候选程序进行逐层筛查,能够精准识别并定位候选程序中的错误,同时,能够基于候选程序中的诊断信息转化为可供大语言模型理解的自然语言反馈文本,指导大语言模型重新生成候选程序,抑制了大语言模型固有的幻觉缺陷,从而提升程序终止性验证的成功率。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122614693B_ABST
    Figure CN122614693B_ABST
Patent Text Reader

Abstract

The application relates to the technical field of program formal verification, and discloses a program termination verification method based on rank function synthesis, which comprises the following steps: performing program analysis and loop structure identification on program source code to be verified for program termination to obtain target loop nodes; for each target loop node, respectively inserting a code placeholder for rank function initialization and updating and an assertion placeholder for declaring rank function properties, generating a plugged program with constraint filling format, fusing structured prompt words of a large language model constructed by combining rank function synthesis domain expert knowledge and few-shot examples, calling the large language model, and generating a candidate program of rank function synthesis; sequentially performing equivalence checking, code-assertion integrity checking and assertion validity checking on the candidate program; and if all the checks are passed, determining that the program termination verification is passed. The application significantly improves the automation level and success rate of program termination verification.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of formal verification technology, and more specifically, to a method for verifying program termination based on rank function synthesis. Background Technology

[0002] With the widespread application of software systems in aerospace, autonomous driving, financial transactions, and industrial control, the reliability and correctness of software programs have become critical factors concerning the safety of life and property. Program termination is one of the fundamental properties of program correctness, meaning proving that a program will not fall into an infinite loop under all possible input conditions. For various types of basic software, industrial software, and embedded real-time systems, ensuring the termination of program loop structures is a prerequisite and a core challenge in building highly reliable software systems.

[0003] In the field of formal verification, the mainstream method for proving program termination is to synthesize a rank function for the loop structure to be verified. A rank function is a function that maps program states to a well-founded domain, whose value strictly decreases after each loop iteration and always remains non-negative. Once a rank function satisfying these conditions is synthesized for a program loop structure, it can be mathematically proven that the loop structure must terminate. Traditional automatic rank function synthesis techniques mainly rely on predefined templates. By pre-setting polynomial forms and linear combinations, the solution of the rank function is transformed into a constraint satisfaction problem, which is then solved using a symbolic solver. However, these template-based rank function synthesis methods are limited by the expressive power of the templates. When faced with real programs with nonlinear variable updates, complex branch control flow, or multiple nested structures, the predefined templates often cannot cover the actual form of the rank function, leading to proof failure. Although some studies have attempted to extend the complexity of templates to cover a wider range of program patterns, the difficulty of template design and maintenance increases dramatically, and universality remains severely insufficient.

[0004] In recent years, large language models have demonstrated powerful capabilities in code generation, and some studies have begun to attempt to directly utilize them to generate rank functions or related assertions. While this approach overcomes the limitations of template expressiveness, it still faces significant reliability challenges: due to the abstract definition of rank functions and the strict requirements of termination proofs, large language models are prone to generating factual errors or content that does not conform to proof specifications during the generation process—a phenomenon known as the "illusion" phenomenon. This often results in candidate results with issues such as invalid assertion logic, inconsistent variable naming, or even accidental alteration of program semantics. Furthermore, there is a lack of reliable means to systematically verify and correct the correctness of the generated results. Summary of the Invention

[0005] To address the problems existing in the prior art, this invention provides a program termination verification method based on rank function synthesis. This method can fully utilize the generation capabilities of large language models to overcome template limitations, effectively suppress model illusions and ensure the correctness and reliability of results through a rigorous formal verification mechanism, and automatically iterate and repair erroneous candidate programs, thereby significantly improving the automation level and success rate of program termination verification.

[0006] To achieve the above technical objectives, the present invention adopts the following technical solution:

[0007] A method for verifying program termination based on rank function synthesis includes the following steps: Step S1: Perform program parsing and loop structure identification on the source code of the program to be terminated to obtain the target loop node; Step S2: For each target loop node, insert code placeholders for rank function initialization and update, and assertion placeholders for declaring the properties of the rank function, to generate an instrumentation program with constraint-filled format; Step S3: Integrate the generated instrumentation program with expert knowledge in the rank function synthesis field and few-sample examples to construct structured prompt words for the large language model, call the large language model, and generate candidate programs for rank function synthesis; Step S4: Perform equivalence checks, code-assertion integrity checks, and assertion validity checks on the candidate programs in sequence; Step S5: If all checks pass, the program termination verification is deemed successful; otherwise, the program termination verification is deemed unsuccessful.

[0008] Further, step S1 includes the following sub-steps: Step S1.1: Perform lexical and syntactic analysis on the source code of the program to be terminated and construct a complete abstract syntax tree structure; Step S1.2: Traverse all nodes of the abstract syntax tree structure, identify all target loop nodes that constitute the loop based on the syntactic features of the program loop statement, and locate the key components of each target loop node, including: loop entry, loop guard and loop body.

[0009] Furthermore, the specific process of step S2 is as follows: The loop entry point and loop guard of each target loop node are used to determine the loop preposition. The first code placeholder is inserted at the loop preposition to generate the initialization statement and auxiliary variable declaration required for the rank function. The auxiliary variable declaration includes at least a first variable for recording the value of the rank function in the previous iteration and a second variable for storing the value of the rank function in the current iteration. Insert a second code placeholder at the beginning of the loop body of each target loop node to generate an assignment statement that assigns the current iteration rank function value to the first variable; Insert a third code placeholder at the end of the loop body of each target loop node to generate an assignment statement for the second variable that updates the value of the current iteration rank function; Insert an assertion placeholder at the end of the loop body of each target loop node, after the third code placeholder, to generate one or more assertions for the constrained rank function property.

[0010] Furthermore, the assertions include at least: strictly decreasing assertions, nonnegative assertions, and termination condition assertions; The strict decreasing assertion requires that the first variable of the rank function value in the previous iteration is greater than the second variable of the rank function value in the current iteration. The nonnegativity assertion requires at least that the first variable of the rank function value is not less than a preset lower bound; The termination condition assertion requires that the loop condition is not met when the rank function value is below a preset lower bound.

[0011] Furthermore, the structured prompts for the large language model in step S3 include: system role, code to be filled, task instructions, and output format requirements; in: The system role is used to set the large language model as an expert proficient in program termination verification; The code to be filled is used to fill the generated instrumentation program; The task instructions describe the objective of filling in code placeholders and assertion placeholders based on the context to verify the termination of the program loop. The context includes domain expert knowledge on rank function synthesis and few-sample examples; The expert knowledge in the field of rank function synthesis includes at least a single-rank function proof pattern, a lexicographical rank function proof pattern, and a multi-stage rank function proof pattern. The few-sample example is at least one case selected from a pre-built program termination verification case library that has similar characteristics to the currently pending program loop verification.

[0012] Furthermore, step S5 also includes: i: If any check fails, collect the diagnostic information of the corresponding check, convert the diagnostic information into natural language feedback text, update the structured prompt words of the large language model using the natural language feedback text, and re-invoke the large language model to regenerate the candidate program. ii: Perform equivalence checks, code-assertion integrity checks, and assertion validity checks on the regenerated candidate programs in sequence; iii: If all checks pass, the program termination verification is deemed successful; otherwise, repeat steps i-ii until the iteration termination condition is met, at which point the program termination verification is deemed unsuccessful.

[0013] Furthermore: The equivalence check compares the candidate program with the corresponding source code of the program to be terminated for verification in terms of syntax equivalence. If there is an inconsistency in syntax, it is determined that the candidate program has tampered with the logic of the source code of the program to be terminated for verification. The equivalence check fails and program tampering diagnosis information is generated. Code-assertion integrity check is performed after the equivalence check passes. The code is filled into the candidate program for structured integrity verification. If the verification fails, integrity diagnostic information containing missing structural items and verification error types is generated. Assertion validity verification is performed after the code-assertion integrity check passes. The symbol validator is then called to check the validity of assertions in the candidate program. If there is a counterexample path that causes the assertion to be violated, the check fails and validity diagnostic information containing the counterexample path is generated.

[0014] Furthermore, the code-assertion integrity check includes: variable declaration integrity check, update statement integrity check, assertion form integrity check, and assertion property check; in: The variable declaration integrity check is used to extract all auxiliary variables declared in the first code placeholder, and divide all auxiliary variables into an old value variable set and a new value variable set according to whether the auxiliary variables have been assigned an initial value. If the old value variable set and the new value variable set are inconsistent, the check fails. The update statement integrity check is used to verify whether the assignment statement in the second code placeholder assigns each variable in the old value variable set to the form of the corresponding variable in the new value variable set, and at the same time verifies whether the assignment statement in the third code placeholder updates each variable in the new value variable set to the form of the same expression as in the first code placeholder. If any one of the checks is negative, the check fails. The assertion form integrity check is used to verify whether the assertions in the assertion placeholders match the rank function synthesis domain expert knowledge given in the structured prompt and to verify whether the termination condition assertion is complete. If any one of the checks is not met, the check fails. The assertion property check is used to verify whether the assertions in the assertion placeholders satisfy strict decreasing property and non-negativity, and whether the termination condition assertion is complete. If any of the checks are not satisfied, the check fails.

[0015] Furthermore, the assertion validity verification specifically involves: The assertions in the candidate program are transformed into mathematical formulas to be verified. The symbolic verifier is called to check whether the mathematical formulas are true on all reachable paths of the program. If there is a counterexample path that violates the assertion, the check fails.

[0016] Furthermore, the specific process of converting the diagnostic information into natural language feedback text is as follows: Identify the logical location and content of the tampered program source code awaiting program termination verification from the program tampering diagnostic information, and generate the first natural language feedback text. Extract structural missing items and check error types from integrity diagnostic information containing structural missing items and check error types, and generate second natural language feedback text; Parse the variable assignment sequence on the counterexample path from the validity diagnostic information containing the counterexample path, and generate a third natural language feedback text describing the specific execution scenario of the assertion violation.

[0017] Compared with the prior art, the present invention has the following beneficial effects: This invention presents a program termination verification method based on rank function synthesis. By transforming the abstract task of program loop termination verification into a task of filling code placeholders and assertion placeholders with strict format constraints using a large language model, the cognitive difficulty of program termination verification is reduced. This allows the large language model to reliably realize its generation potential within a pre-defined structured cue space, thus overcoming the inherent bottleneck of traditional methods in terms of expressive power. Simultaneously, the construction of the structured cue in the large language model incorporates expert knowledge from the rank function synthesis domain and few-sample examples, effectively guiding the contextual learning and reasoning process of the large language model, resulting in candidate programs with higher initial standardization and logical orientation. Furthermore, the candidate programs are sequentially subjected to equivalence checks, code-assertion integrity checks, and assertion validity checks. This layer-by-layer screening of candidate programs from three dimensions—program syntactic equivalence, assertion standardization integrity, and logical validity—can accurately identify and locate errors in the candidate programs. Moreover, the diagnostic information in the candidate programs can be transformed into natural language feedback text that the large language model can understand, guiding the large language model to regenerate candidate programs. This suppresses the inherent illusionary defects of the large language model, thereby improving the success rate of program termination verification. Attached Figure Description

[0018] Figure 1 This is a flowchart of the program termination verification method based on rank function synthesis according to the present invention. Detailed Implementation

[0019] The technical solution of the present invention will be further explained and described below with reference to the accompanying drawings.

[0020] like Figure 1This is a flowchart of the program termination verification method based on rank function synthesis according to the present invention. The program termination verification method includes the following steps: Step S1: Perform program parsing and loop structure identification on the source code of the program to be terminated to obtain the target loop node; including the following sub-steps: Step S1.1: Obtain the source code of the program to be terminated for verification. This source code can be provided directly by the user or automatically extracted from a specified code repository or project. The obtained source code is not limited to a specific programming language, but it is usually preprocessed to adapt to the subsequent parsing toolchain. The source code to be terminated for verification is then parsed. The parsing process relies on mature compiler front-end technology or static analysis frameworks. For example, an abstract syntax tree parser is used to perform lexical and syntactic analysis on the source code, constructing a complete abstract syntax tree structure. This abstract syntax tree expresses all syntactic units of the source code in a tree-like form, including function definitions, statement blocks, and expressions. Step S1.2: Traverse all nodes of the abstract syntax tree structure. Based on the syntactic feature of the program loop statement, the "while" keyword is used to identify all target loop nodes that constitute the loop. For nested loops, all levels are recursively identified. The key components of each target loop node are located, including: the loop entry point, the loop guard, and the loop body.

[0021] Step S2: For each target loop node, insert code placeholders for rank function initialization and update, and assertion placeholders for declaring the properties of the rank function, to generate an instrumentation program with a constraint-filled format, transforming the abstract problem of proving loop termination into a code filling task with a strictly constrained format.

[0022] In one technical solution of the present invention, based on the loop entry point and loop guard of each target loop node, the loop pre-position is determined by searching immediately before the loop keyword or the loop initialization part. A first code placeholder is inserted at the loop pre-position to generate the initialization statements and auxiliary variable declarations required for the rank function. The auxiliary variable declarations include at least a first variable for recording the value of the rank function in the previous iteration and a second variable for storing the value of the rank function in the current iteration, with the second variable assigned an initial value. The first code placeholder is used to generate initialization statements for candidate rank function variables, for example, assigning initial values ​​to the introduced rank function variables.

[0023] Insert a second code placeholder at the beginning of the loop body of each target loop node to generate an assignment statement that assigns the current iteration rank function value to the first variable, so as to save the rank function value before the iteration, for example: old_rank = new_rank.

[0024] A third code placeholder is inserted at the end of the loop body of each target loop node. This placeholder is used to generate an assignment statement for the second variable that updates the rank function value of the current iteration, thus calculating the new rank function value after the current iteration ends. For example, `new_rank = ...`. The third code placeholder is used to generate update statements for the candidate rank function variables, describing how the variables should change after each iteration.

[0025] Insert an assertion placeholder at the end of the loop body of each target loop node, after the third code placeholder, to generate one or more assertions for the constrained rank function property.

[0026] In one technical solution of the present invention, the assertion includes at least: strictly decreasing assertion, non-negative assertion, and termination condition assertion; The strict decreasing assertion requires that the first variable of the rank function value in the previous iteration is greater than the second variable of the rank function value in the current iteration. The nonnegativity assertion requires at least that the first variable of the rank function value is not less than a pre-defined lower bound; The termination condition assertion requires that the loop condition is not met when the rank function value is below a preset lower bound.

[0027] In a preferred embodiment, these placeholders are not simple empty strings, but rather markers with specific identifiers and syntactic structures. For example, the first code placeholder might be " / / >>>Infill Define<<<", the second code placeholder might be " / / >>>Infill Update Begin<<<", the third code placeholder might be " / / >>>InfillUpdate End<<<", and the assertion placeholder might be " / / >>>Infill Assert<<<". Through this precise instrumentation, the original program awaiting termination verification is transformed into an instrumentation program. This instrumentation program fully preserves the computational logic of the original program, but uses placeholders to explicitly define the areas that require creative filling by the large language model. The large language model is strictly constrained to only understand and fill these specific placeholders without modifying any line of the original program code. This approach cleverly avoids the challenge of directly explaining the complex definition of rank functions to large language models, transforming a highly abstract theorem proof task into a context-sensitive code completion and assertion generation task that large language models are better at, thus laying a structural foundation for improving the accuracy and reliability of the final generated results.

[0028] Step S3: Integrate the generated instrumentation program with domain expert knowledge of rank function synthesis and few-sample examples to construct structured prompts for the large language model. Call the large language model to generate candidate programs for rank function synthesis. The structured prompts constrain the large language model to only fill code placeholders and assertion placeholders.

[0029] The structured prompts for the large language model include: system role, code to be filled, task instructions, and output format requirements; in: The system role is used to set the large language model as an expert proficient in program termination verification; The code to be filled is used to populate the generated instrumentation program; Task instructions are used to describe the goal of filling code placeholders and assertion placeholders based on context to verify the termination of the program loop; The context includes domain expert knowledge of rank function synthesis and few-shot examples; The domain expert knowledge synthesized by rank functions is not implicit training data, but rather is encoded as argument logic and proof patterns described in natural language, including at least: single-rank function proof patterns, lexicographical rank function proof patterns, and multi-stage rank function proof patterns. By synthesizing domain expert knowledge by rank functions, the reasoning process of human experts is provided as context to the large language model, thereby enhancing the understanding and reasoning ability of the large language model.

[0030] Few-shot examples are at least one case selected from a pre-built library of program termination verification cases that shares similar characteristics with the currently pending program loop verification. Each case contains a pair of inputs and outputs, where the input is a similar instrumentation program and the output is the complete program with all four placeholders in the instrumentation program fully and correctly filled in. These few-shot examples follow the domain expert knowledge description of rank function synthesis, providing a concrete and imitable implementation paradigm for large language models.

[0031] Therefore, structured prompts integrate system roles, domain knowledge of rank function synthesis, few-sample examples, and the current instrumentation procedure, providing strong constraints. They can clearly indicate that the only task of the large language model is to generate the code and assertions needed to fill the placeholders, rather than modifying program logic or performing other irrelevant operations. This effectively suppresses the "illusion" tendency of the large language model and guides it to generate highly standardized and correctly formatted candidate programs.

[0032] In one technical solution of this invention, the invoked large language model is a generative model pre-trained on a large-scale code corpus and fine-tuned with instructions. The calling interface can be an application programming interface (API) for locally deployed models or a cloud-based inference service. Structured prompts are sent to the large language model as the sole input. In a preferred embodiment, appropriate decoding parameters are set, such as using a low random sampling temperature value, to ensure that the large language model's generated results are both deterministic and reasonable, avoiding excessive divergence. After receiving the structured prompts, the large language model, based on its powerful context understanding and sequence generation capabilities, performs joint reasoning on all the information in the structured prompts, understands the system role, comprehends the task instructions, draws on proof patterns from expert knowledge, and imitates the filling format of few-shot examples. Finally, the large language model outputs a complete candidate program. In this candidate program, all placeholders in the instrumentation program: / / >>>InfillDefine<<<, / / >>>Infill Update Begin<<<, / / >>>Infill Update End<<<, and / / >>>Infill Assert<<< have been replaced by the large language model with concrete code expressions or assertion logic statements that it deems correct.

[0033] A candidate program is a code entity with a complete syntactic structure that can be compiled or parsed by subsequent tools. Since the large language model is not created out of thin air after understanding complex global termination theory, but rather "generated with evidence" under the constraints of highly structured cue words, combined with domain expert knowledge of rank function synthesis and few sample examples, the resulting candidate program is not only a textual completion, but its internal code and assertion logic have also initially possessed a semantic orientation toward a correct rank function proof.

[0034] Step S4: After generating the candidate program, although its format is standardized, its logical correctness is still unknown. The candidate program is subjected to equivalence check, code-assertion integrity check, and assertion validity check in sequence as quality checkpoints. The candidate program is subjected to a progressive automated review. Only when a candidate program can pass all the above checks is it considered a correct and reliable valid result that can prove the termination of the target loop.

[0035] Equivalence checks are used to prevent large language models from unintentionally or intentionally tampering with the non-loop-related logic of the original program when filling in placeholders. Therefore, the candidate program is compared with the corresponding source code of the program awaiting termination verification for syntactic equivalence. If inconsistencies exist, such as the deletion or modification of an assignment statement in the original program, the candidate program is determined to have tampered with the logic of the source code of the program awaiting termination verification. The equivalence check fails, program tampering diagnostic information is generated, clearly indicating the location and content differences of the tampering, and subsequent verification is immediately terminated.

[0036] Code-assertion integrity checking involves performing structured integrity checks on the code filled into the candidate program after the equivalence check passes. If the check fails, integrity diagnostic information containing missing structural items and check error types is generated. Code-assertion integrity checking includes: variable declaration integrity checking, update statement integrity checking, assertion form integrity checking, and assertion property checking. in: The variable declaration integrity check is used to extract all auxiliary variables declared in the first code placeholder. Based on whether the auxiliary variables have been assigned initial values, all auxiliary variables are divided into a set of old value variables and a set of new value variables. The check verifies that the set of old value variables and the set of new value variables must be equal, ensuring that each rank function component has a corresponding record before iteration and a record after iteration. If the set of old value variables and the set of new value variables are inconsistent, the check fails.

[0037] The update statement integrity check verifies whether the assignment statement in the second code placeholder assigns each variable in the old value variable set to the form of the corresponding variable in the new value variable set, that is, updates the old value variable with the current rank function value. At the same time, it verifies whether the assignment statement in the third code placeholder updates each variable in the new value variable set to the form of the same expression as in the first code placeholder, ensuring the consistency of the rank function update logic. If any check fails, the check fails.

[0038] The assertion form integrity check verifies whether the assertions in the assertion placeholders match the domain expert knowledge of the rank function synthesis given in the structured prompts, and whether the termination condition assertions are complete. For example, the single-rank function pattern requires strict decrementing and non-negative rank function values ​​before iteration; the multi-stage rank function pattern allows different rank function components to be used in different stages; and the lexicographical rank function pattern requires that all components decrease lexicographically. If any of these checks are not met, the check fails.

[0039] The assertion property check is used to verify whether the assertions in the assertion placeholders satisfy strict decreasing property and non-negativity, as well as to verify whether the assertion termination condition is complete. If any of the checks are not met, the check fails.

[0040] Assertion validity verification is performed after the code-assertion integrity check passes. The symbolic validator is then called to check the validity of the assertions in the candidate program. If there is a counterexample path that violates the assertion, the check fails, and validity diagnostic information containing the counterexample path is generated. Specifically, the assertions in the candidate program are converted into mathematical formulas to be verified, and the symbolic validator is called to check whether the mathematical formula is true on all reachable paths of the program. If there is a counterexample path that violates the assertion, the check fails.

[0041] Step S5: If all checks pass, the procedure termination verification is deemed successful; otherwise, the procedure termination verification is deemed unsuccessful. Specifically, this also includes: i: If any check fails, collect the diagnostic information of the corresponding check, convert the diagnostic information into natural language feedback text, use the natural language feedback text to update the structured prompt words of the large language model, and call the large language model again to regenerate the candidate program. ii: Perform equivalence checks, code-assertion integrity checks, and assertion validity checks on the regenerated candidate programs in sequence; iii: If all checks pass, the program termination verification is deemed successful; otherwise, repeat steps i-ii until the iteration termination condition is met, at which point the program termination verification is deemed unsuccessful.

[0042] This invention constructs an intelligent closed-loop feedback iteration mechanism based on diagnostic information, upgrading candidate program generation from "single generation, passive verification" to "co-evolution, proactive repair." Diagnostic information is typically structured, machine-oriented, and difficult for large language models to understand directly. Converting diagnostic information into natural language feedback text allows for the use of predefined templates and conversion rules for different types of diagnostic information, translating it into feedback text that large language models can read fluently. In this way, erroneous data is transformed into instructive repair suggestions. The specific process is as follows: Identify the logical location and content of the tampered program source code awaiting program termination verification from the program tampering diagnostic information, and generate the first natural language feedback text. Extract structural missing items and check error types from integrity diagnostic information containing structural missing items and check error types, and generate second natural language feedback text; Parse the variable assignment sequence on the counterexample path from the validity diagnostic information containing the counterexample path, and generate a third natural language feedback text describing the specific execution scenario of the assertion violation.

[0043] After generating the natural language feedback text, an iterative update process for the structured prompt words is initiated. The natural language feedback text generated in this round, along with the candidate programs that failed in this round of validation, are added or integrated into the structured prompt words used to generate the next round of candidate programs, forming a new prompt word with richer content and error correction context. This chain combination of "prompt word - generation result - feedback information" constitutes a powerful contextual learning environment. Then, using this new prompt word, the large language model is invoked again. The large language model reflects on and corrects its previous error experience, generating a new candidate program. This new candidate program undergoes equivalence checks, code-assertion completeness checks, and assertion validity checks again.

[0044] In a preferred embodiment, an iteration termination condition is also set. The iteration termination condition may be that the cumulative number of calls to the large language model reaches a set limit, or the total computation time of symbol verification exceeds a preset time budget. Once the iteration termination condition is met, the process will stop and output a proof failure message even if no valid candidate program has been generated. Conversely, if a candidate program successfully passes the full process check during the iteration, the iteration will terminate immediately, and a valid candidate program will be obtained.

[0045] This invention constructs a closed-loop collaborative mechanism that deeply integrates the generation capabilities of a large language model with symbolic formal verification technology to achieve program termination verification. Firstly, this method innovatively transforms the abstract task of proving loop termination into a code placeholder filling task subject to strict format constraints, reducing the cognitive difficulty of problem-solving. This allows the large language model to reliably unleash its generation potential within a pre-defined structured space, thus overcoming the inherent bottleneck of traditional template methods in terms of expressive power. Simultaneously, a structured hint construction strategy that integrates expert knowledge in the termination proof domain with few-shot examples effectively guides the model's contextual learning and reasoning process, resulting in candidate results with higher initial standardization and logical orientation. More importantly, a three-level progressive symbolic verification pipeline—comprising equivalence checks, code-assertion integrity checks, and assertion validity checks—acts as an indispensable quality checkpoint, screening the generated results layer by layer from program syntactic equivalence and assertion standardization integrity to logical validity, accurately identifying and locating various subtle errors. The iterative feedback optimization loop based on diagnostic information automatically transforms the knowledge of verification failures into natural language repair guidance that can be understood by the large language model. This drives the large language model to reflect on itself and make targeted corrections, forming an intelligent evolutionary closed loop of candidate program "generation-verification-diagnosis-repair". This fully automatic, highly reliable, and self-improving collaborative paradigm has achieved a breakthrough improvement in the success rate of program termination verification, suppresses the inherent illusion defects of large language models, and ensures that every candidate program output can withstand rigorous formal mathematical testing under the adopted symbolic verification framework, thus avoiding the limitation of program termination verification results relying on the underlying verification tools.

[0046] In one embodiment of the present invention, a computer-readable storage medium is also provided, storing a computer program that enables a computer to execute the program termination verification method based on rank function synthesis of the present invention.

[0047] In one technical solution of the present invention, an electronic device is also provided, including: a memory, a processor, and a computer program stored in the memory and executable on the processor. When the processor executes the computer program, it implements the program termination verification method based on rank function synthesis of the present invention.

[0048] In the embodiments disclosed in this application, a computer storage medium may be a tangible medium that may contain or store programs for use by or in conjunction with an instruction execution system, apparatus, or device. The computer storage medium may include, but is not limited to, electronic, magnetic, optical, electromagnetic, infrared, or semiconductor systems, apparatus, or devices, or any suitable combination of the foregoing. More specific examples of computer storage media include electrical connections based on one or more wires, portable computer disks, hard disks, random access memory (RAM), read-only memory (ROM), erasable programmable read-only memory (EPROM or flash memory), optical fibers, and portable compact disc read-only memory (CD). ROM), optical storage devices, magnetic storage devices, or any suitable combination of the foregoing.

[0049] Those skilled in the art will recognize that the units and algorithm steps of the various examples described in conjunction with the embodiments disclosed in this application can be implemented in electronic hardware or a combination of computer software and electronic hardware. Whether these functions are implemented in hardware or software depends on the specific application and design constraints of the technical solution. Those skilled in the art can use different methods to implement the described functions for each specific application, but such implementation should not be considered beyond the scope of this application.

[0050] The above are merely preferred embodiments of the present invention. The scope of protection of the present invention is not limited to the above embodiments. All technical solutions falling within the scope of the present invention's concept are within the scope of protection of the present invention. It should be noted that for those skilled in the art, any improvements and modifications made without departing from the principles of the present invention should be considered within the scope of protection of the present invention.

Claims

1. A method for verifying program termination based on rank function synthesis, characterized in that, Includes the following steps: Step S1: Perform program parsing and loop structure identification on the source code of the program to be terminated to obtain the target loop node; Step S2: For each target loop node, insert code placeholders for rank function initialization and update, and assertion placeholders for declaring the properties of the rank function, to generate an instrumentation program with constraint-filled format; Step S3: Integrate the generated instrumentation program with expert knowledge in the rank function synthesis field and few-sample examples to construct structured prompt words for the large language model, call the large language model, and generate candidate programs for rank function synthesis; Step S4: Perform equivalence checks, code-assertion integrity checks, and assertion validity checks on the candidate programs in sequence; Step S5: If all checks pass, the program termination verification is deemed successful; otherwise, the program termination verification is deemed unsuccessful. The specific process for determining whether the termination verification of the procedure fails is as follows: i: If any check fails, collect the diagnostic information of the corresponding check, convert the diagnostic information into natural language feedback text, update the structured prompt words of the large language model using the natural language feedback text, and re-invoke the large language model to regenerate the candidate program. ii: Perform equivalence checks, code-assertion integrity checks, and assertion validity checks on the regenerated candidate programs in sequence; iii: If all checks pass, the program termination verification is deemed successful; otherwise, repeat steps i-ii until the iteration termination condition is met, at which point the program termination verification is deemed unsuccessful.

2. The program termination verification method based on rank function synthesis according to claim 1, characterized in that, Step S1 includes the following sub-steps: Step S1.1: Perform lexical and syntactic analysis on the source code of the program to be terminated and construct a complete abstract syntax tree structure; Step S1.2: Traverse all nodes of the abstract syntax tree structure, identify all target loop nodes that constitute the loop based on the syntactic features of the program loop statement, and locate the key components of each target loop node, including: loop entry, loop guard and loop body.

3. The program termination verification method based on rank function synthesis according to claim 2, characterized in that, The specific process of step S2 is as follows: The loop entry point and loop guard of each target loop node are used to determine the loop preposition. The first code placeholder is inserted at the loop preposition to generate the initialization statement and auxiliary variable declaration required for the rank function. The auxiliary variable declaration includes at least a first variable for recording the value of the rank function in the previous iteration and a second variable for storing the value of the rank function in the current iteration. Insert a second code placeholder at the beginning of the loop body of each target loop node to generate an assignment statement that assigns the current iteration rank function value to the first variable; Insert a third code placeholder at the end of the loop body of each target loop node to generate an assignment statement for the second variable that updates the value of the current iteration rank function; Insert an assertion placeholder at the end of the loop body of each target loop node, after the third code placeholder, to generate one or more assertions for the constrained rank function property.

4. The program termination verification method based on rank function synthesis according to claim 3, characterized in that, The assertions include at least: strictly decreasing assertions, non-negative assertions, and termination condition assertions; The strict decreasing assertion requires that the first variable of the rank function value in the previous iteration is greater than the second variable of the rank function value in the current iteration. The nonnegativity assertion requires at least that the first variable of the rank function value is not less than a preset lower bound; The termination condition assertion requires that the loop condition is not met when the rank function value is below a preset lower bound.

5. The program termination verification method based on rank function synthesis according to claim 3, characterized in that, In step S3, the structured prompts for the large language model include: system role, code to be filled, task instructions, and output format requirements; in: The system role is used to set the large language model as an expert proficient in program termination verification; The code to be filled is used to fill the generated instrumentation program; The task instructions describe the objective of filling in code placeholders and assertion placeholders based on the context to verify the termination of the program loop. The context includes domain expert knowledge on rank function synthesis and few-sample examples; The expert knowledge in the field of rank function synthesis includes at least a single-rank function proof pattern, a lexicographical rank function proof pattern, and a multi-stage rank function proof pattern. The few-sample example is at least one case selected from a pre-built program termination verification case library that has similar characteristics to the currently pending program loop verification.

6. The program termination verification method based on rank function synthesis according to claim 1, characterized in that: The equivalence check compares the candidate program with the corresponding source code of the program to be terminated for verification in terms of syntax equivalence. If there is an inconsistency in syntax, it is determined that the candidate program has tampered with the logic of the source code of the program to be terminated for verification. The equivalence check fails and program tampering diagnosis information is generated. Code-assertion integrity check is performed after the equivalence check passes. The code is filled into the candidate program for structured integrity verification. If the verification fails, integrity diagnostic information containing missing structural items and verification error types is generated. Assertion validity verification is performed after the code-assertion integrity check passes. The symbol validator is then called to check the validity of assertions in the candidate program. If there is a counterexample path that causes the assertion to be violated, the check fails and validity diagnostic information containing the counterexample path is generated.

7. The program termination verification method based on rank function synthesis according to claim 6, characterized in that, The code-assertion integrity check includes: variable declaration integrity check, update statement integrity check, assertion form integrity check, and assertion property check; in: The variable declaration integrity check is used to extract all auxiliary variables declared in the first code placeholder, and divide all auxiliary variables into an old value variable set and a new value variable set according to whether the auxiliary variables have been assigned an initial value. If the old value variable set and the new value variable set are inconsistent, the check fails. The update statement integrity check is used to verify whether the assignment statement in the second code placeholder assigns each variable in the old value variable set to the form of the corresponding variable in the new value variable set, and at the same time verifies whether the assignment statement in the third code placeholder updates each variable in the new value variable set to the form of the same expression as in the first code placeholder. If any one of the checks is negative, the check fails. The assertion form integrity check is used to verify whether the assertions in the assertion placeholders match the rank function synthesis domain expert knowledge given in the structured prompt and to verify whether the termination condition assertion is complete. If any one of the checks is not met, the check fails. The assertion property check is used to verify whether the assertions in the assertion placeholders satisfy strict decreasing property and non-negativity, and whether the termination condition assertion is complete. If any of the checks are not satisfied, the check fails.

8. The program termination verification method based on rank function synthesis according to claim 6, characterized in that, The assertion validity verification specifically involves: The assertions in the candidate program are transformed into mathematical formulas to be verified. The symbolic verifier is called to check whether the mathematical formulas are true on all reachable paths of the program. If there is a counterexample path that violates the assertion, the check fails.

9. The program termination verification method based on rank function synthesis according to claim 6, characterized in that, The specific process of converting the diagnostic information into natural language feedback text is as follows: Identify the logical location and content of the tampered program source code awaiting program termination verification from the program tampering diagnostic information, and generate the first natural language feedback text. Extract structural missing items and check error types from integrity diagnostic information containing structural missing items and check error types, and generate second natural language feedback text; Parse the variable assignment sequence on the counterexample path from the validity diagnostic information containing the counterexample path, and generate a third natural language feedback text describing the specific execution scenario of the assertion violation.

Citation Information

Patent Citations

  • Loop program termination judgment method based on boundary function synthesis

    CN112698891A

  • Loop program termination judgment method based on lexicographical order neural rank function

    CN122261969A