A C++ code coverage visualization detection method
By constructing an abstract syntax tree and an improved depth-first traversal algorithm, combined with probe instrumentation and code coloring, the problems of low instrumentation efficiency and inaccurate data collection in C++ code testing are solved, achieving efficient and accurate coverage evaluation and display.
Patent Information
- Application Number
- CN202510291928.8
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2025-03-12
- Publication Date
- 2025-11-18
- Estimated Expiration
- 2045-03-12
AI Technical Summary
Existing technologies struggle to perform efficient and low-overhead instrumentation of C++ code, and they also have difficulty accurately collecting code execution data and demonstrating test coverage, leading to inaccurate assessments of code test adequacy.
An ANTLR-generated lexical and parser algorithm is used to construct an abstract syntax tree. An improved depth-first traversal algorithm is combined to extract code structure information, and probes are inserted at key locations to record execution path information. Coverage is displayed by generating statistical tables and code coloring.
It enables precise instrumentation and data collection of C++ code, reduces the impact on program performance, ensures the accuracy and reliability of test data, provides intuitive coverage display, and helps to quickly locate weak areas in testing.
Smart Images

Figure CN120234241B_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the technical field of software testing, and more specifically, to a method for visualizing and detecting C++ code coverage. Background Technology
[0002] In the current technological context, as software systems continue to expand in scale and increase in complexity, the importance of software testing and quality assurance is becoming increasingly prominent. This is especially true for C++, whose complex syntax, flexible semantics, and high execution efficiency requirements often make it difficult for traditional testing methods to accurately and quantitatively assess the adequacy of code testing. Existing code coverage analysis tools primarily focus on dynamic languages or programming languages with simpler structures, exhibiting significant shortcomings in handling the complex control flow and diverse syntax of C++ code. Specifically, these shortcomings manifest in the following ways:
[0003] First, the C++ language is highly complex at the lexical and syntactic levels. Because traditional tools struggle to fully analyze the structure of C++ code, they cannot accurately capture the hierarchical relationships between various logical units during testing, thus affecting the comprehensive collection of code execution path information.
[0004] Secondly, since C++ code testing involves a large number of conditional statements, loop structures, and multi-branch statements, achieving accurate code instrumentation without changing the original code semantics is a major challenge. In existing technologies, manual instrumentation or simple automation tools tend to introduce excessive instrumentation code when handling conditions such as if statements without curly braces, switch-case structures, and complex loops. This increases runtime overhead and may lead to semantic distortion, thus affecting the normal execution of the program.
[0005] Furthermore, existing coverage analysis tools also have shortcomings in data collection and processing. Due to the massive amount of code execution data generated during the execution of C++ programs, and the overlap of data between different code blocks, designing efficient and low-interference data collection and statistical methods to accurately calculate statement and branch coverage has always been a pressing issue in the technical field. Traditional methods often write data in real-time or rely on simple statistical techniques, making it difficult to meet the dual requirements of coverage data accuracy and execution efficiency.
[0006] Therefore, there is an urgent need for a tool that can automatically perform efficient and low-overhead instrumentation on C++ code, accurately collect code execution data, and display test coverage in an intuitive way, so as to achieve quantitative evaluation of the adequacy of C++ code testing and improve software testing quality and system stability. Summary of the Invention
[0007] The purpose of this invention is to address the lack of effective code coverage analysis tools in C++ program testing by proposing a method that can automatically instrument C++ code, record execution paths, calculate coverage, and visually display test coverage.
[0008] The technical solution of this invention is: to provide a C++ code coverage visualization detection method, the method comprising:
[0009] S1. Lexical and syntax analysis of C++ code: ANTLR is used to generate a lexical analyzer and a syntax analyzer, and an abstract syntax tree is constructed; an improved depth-first traversal algorithm with added extraction of code structure information is used to traverse the C++ code and obtain code structure information;
[0010] S2. Based on the obtained code structure information, instrument the C++ code by inserting probes at appropriate locations in the code to record the code execution status.
[0011] S3. Run the code and wait for the code execution to complete. In the class destructor, collect the code execution path information. In the destructor, use the variable that records the current number of probes to traverse the array that stores probe data. Write the start line number and end line number of each probe record in the array into a newly generated text file.
[0012] S4. Calculate the C++ code coverage using the code structure information constructed in step S1 and the code execution path information collected in step S3.
[0013] S5. Visualize C++ code coverage by generating statistical tables and using different colors to indicate whether the code was executed.
[0014] The improved depth-first traversal algorithm for extracting code structure information added in step S1 includes:
[0015] The system traverses all nodes from the root of the abstract syntax tree. Whenever a node is encountered in the abstract syntax tree, the system determines whether the number of child nodes of the node is greater than 1, or whether it has only one child node and that child node is a leaf node. If the condition is met, the current node is considered to have independent structural meaning and an AstNode node is generated.
[0016] Each AstNode includes several attributes, including the node name, the corresponding line number of code, the parent node, and a list of child nodes. Each AstNode is also added to the list of child nodes of its corresponding parent node.
[0017] After traversing the substructure of the current node, it automatically returns to the parent node of that node and continues to complete the traversal of the remaining parts.
[0018] In any of the above technical solutions, the visualization in step S5 further includes:
[0019] The system generates a table to display the coverage of each code module. The table lists the name of each function, statement coverage, and branch coverage data, and gives the overall total result in the last row. At the code level, the system colors each line of code based on the probe data, using different colors to mark executed and unexecuted statements.
[0020] In any of the above technical solutions, the step of constructing the abstract syntax tree in step S1 further includes: using the open-source tool ANTLR to generate a lexical analyzer and a syntax analyzer; using the lexical analyzer to decompose the C++ code into basic lexical units; and using the syntax analyzer to combine the decomposed lexical units into expressions, statements, and higher-level code blocks that conform to the grammatical structure according to predefined C++ language syntax rules, forming an abstract syntax tree that intuitively reflects the hierarchical structure of the source code and the relationship between its components.
[0021] In any of the above technical solutions, step S2 further defines a structure representing the data structure of the probe, using the following C language structure definition:
[0022] typedef struct{
[0023] int beg;
[0024] int end;
[0025] }ins1;
[0026] int ins_p1 = 0;
[0027] ins1 inss
[26] ;
[0028] The structure is declared at the beginning of the C++ class definition file, including the variable start line beg and end line end. From beg to end, it represents the range of code lines covered by the probe; inss
[26] is the probe array, and the size of the array represents the number of probes in the class definition file; ins_p1 is an integer variable used as the index of the probe array inss. Its function is to record the number of probes that have been inserted and to indicate the position in the array where the next probe should be stored. Each time a new probe information is inserted into the ins array, ins_p1 will automatically increment by 1.
[0029] In any of the above technical solutions, step S2 further sets corresponding instrumentation strategies for different types of code structures, as follows:
[0030] For sequential code blocks, the instrumentation strategy is to insert probe code at the end of the last line of the block to record the execution from the beginning to the end of the block.
[0031] For code blocks containing conditional statements, the instrumentation strategy is to insert a probe after the last statement in the conditional statement block to record the code execution when the condition is true.
[0032] For code blocks containing switch-case statements, the instrumentation strategy is to insert probes between each case statement and its corresponding break statement to record the execution status of different case branches;
[0033] For code blocks containing loop structures, including for, while, and do-while statements, loop structures typically involve conditional branches. The instrumentation strategy is as follows:
[0034] First, determine the location of the loop condition, that is, identify the conditional statement in the loop structure used to determine whether to continue executing the loop body;
[0035] If the judgment result is true, that is, the loop body will continue to execute, a probe code is inserted after the last statement of the loop body to record the execution status of this loop iteration;
[0036] If the judgment result is false, the loop will terminate. A probe is inserted at the corresponding position after the loop condition judgment fails to record the exit from the loop.
[0037] In any of the above technical solutions, further, in the instrumentation strategy, for a code block containing a conditional statement if, it first checks whether the code block contains curly braces. If there are no curly braces, then curly braces are added at the corresponding position according to C++ syntax.
[0038] In any of the above technical solutions, further, in the instrumentation strategy, for if statements with branches, probes need to be inserted on the true and false states of the if statement. If there is an else statement paired with the if statement, the probe is inserted in the last statement of the else statement block. If there is no else statement, an empty else statement needs to be added, and the probe code is inserted in the empty else statement.
[0039] In any of the above technical solutions, the C++ code coverage calculated in step S4 further includes statement coverage and branch coverage. Statement coverage is defined as the ratio of the number of executed statements to the total number of statements in the tested code, and branch coverage is defined as the ratio of the number of executed branches to the total number of branches in the tested code.
[0040] The beneficial effects of this invention are:
[0041] This invention can automatically perform precise lexical and syntactic analysis on C++ code, construct a complete code structure tree, and automatically insert probes at key locations without changing the original code semantics, thereby accurately collecting execution path information during program runtime. In particular, by adding the extraction of code structure information during the traversal of the abstract syntax tree generated by ANTLR, this invention can obtain more detailed and accurate code location information and control flow boundaries, thereby ensuring the precise implementation of instrumentation operations, avoiding interference with the original code semantics, and effectively improving the accuracy and reliability of coverage calculation data.
[0042] The probe data structure designed in this invention has low overhead, only recording the start and end lines covered by the probe. Furthermore, it employs instrumentation at critical locations such as the end of code blocks, conditional statements, and loop structures, which significantly reduces the impact of instrumentation on program performance while ensuring the integrity and accuracy of the test data.
[0043] By adopting a method of uniformly collecting probe recording data after program execution (in the class destructor), the interference of real-time data writing on program running speed is effectively avoided, and the data acquisition process is separated from the program execution logic, thereby ensuring the stability of the test environment and the consistency of data.
[0044] Traditional methods for handling complex control structures such as conditional statements, loop structures, and switch-case statements suffer from problems such as improper instrumentation placement, excessive runtime overhead, or semantic distortion. This invention designs a special instrumentation strategy for various types of statements and achieves accurate processing of complex syntax structures and low-interference data acquisition by pre-filling curly braces in if statements without curly braces and inserting probes at the true / false branches.
[0045] This invention further presents test results through intuitive coverage statistics tables and code coloring. It not only provides detailed statistics on statement coverage and branch coverage for each function or code block, but also uses intuitive markers such as green and red to help testers quickly locate uncovered or weak areas, providing a valid basis for the improvement of subsequent test cases and code optimization. Attached Figure Description
[0046] The advantages of the above and additional aspects of the present invention will become apparent and readily understood in the description of the embodiments in conjunction with the following drawings, wherein:
[0047] Figure 1 This is a schematic diagram of the C++ code instrumentation process of a C++ code coverage visualization detection method according to an embodiment of the present invention;
[0048] Figure 2This is a schematic diagram of the class definition of a node in the code structure of a C++ code coverage visualization detection method according to an embodiment of the present invention;
[0049] Figure 3 This is a schematic diagram illustrating the code structure of a C++ code coverage visualization detection method according to an embodiment of the present invention;
[0050] Figure 4 This is a schematic diagram illustrating a sequential structure instrumentation example of a C++ code coverage visualization detection method according to an embodiment of the present invention;
[0051] Figure 5 This is a schematic diagram illustrating an example of instrumentation of an if statement in a C++ code coverage visualization detection method according to an embodiment of the present invention.
[0052] Figure 6 This is a schematic diagram illustrating an example of case statement instrumentation in a C++ code coverage visualization detection method according to an embodiment of the present invention.
[0053] Figure 7 This is an example diagram illustrating the collection of code execution information in the destructor of a class using a C++ code coverage visualization detection method according to an embodiment of the present invention.
[0054] Figure 8 This is a schematic diagram of coverage statistics for a C++ code coverage visualization detection method according to an embodiment of the present invention;
[0055] Figure 9 This is a schematic diagram of statement coverage coloring in a C++ code coverage visualization detection method according to an embodiment of the present invention. Detailed Implementation
[0056] To better understand the above-mentioned objectives, features, and advantages of the present invention, the present invention will be further described in detail below with reference to the accompanying drawings and specific embodiments. It should be noted that, unless otherwise specified, the embodiments of the present invention and the features thereof can be combined with each other.
[0057] In the following description, many specific details are set forth in order to provide a full understanding of the invention. However, the invention may also be practiced in other ways different from those described herein, and therefore the scope of protection of the invention is not limited to the specific embodiments disclosed below.
[0058] like Figure 1 As shown in the figure, this embodiment provides a C++ code coverage visualization detection method, which includes:
[0059] S1. First, perform lexical and syntactic analysis on the C++ source code to accurately obtain the hierarchical relationships between various statements, code blocks, and control structures in the C++ source code, providing detailed structural information for subsequent automatic instrumentation and execution path data collection.
[0060] Specifically, this embodiment uses the open-source tool ANTLR (Another Tool for Language Recognition) to generate a lexical analyzer and a syntax analyzer. The lexical analyzer decomposes C++ code into basic lexical units (such as keywords, identifiers, operators, delimiters, etc.), while the syntax analyzer combines these lexical units into expressions, statements, and higher-level code blocks that conform to the grammatical structure, according to predefined C++ language syntax rules. In this way, ANTLR can output an Abstract Syntax Tree (AST), which intuitively reflects the hierarchical structure of the source code and the relationships between its components.
[0061] However, the abstract syntax tree generated by ANTLR cannot directly meet the instrumentation requirements. The abstract syntax tree generated by ANTLR is mainly used to parse and express the syntactic structure of code, but its output usually focuses on matching and simplifying syntactic rules and may not contain all the details required for precise instrumentation.
[0062] Therefore, during the traversal of the abstract syntax tree, this invention adds the extraction of code structure information to the standard traversal algorithm. The improved depth-first traversal algorithm includes:
[0063] The system traverses all nodes from the root of the abstract syntax tree. Whenever a node is encountered in the abstract syntax tree, the system determines whether the number of child nodes of the node is greater than 1, or whether it has only one child node and that child node is a leaf node. If the condition is met, the current node is considered to have independent structural meaning and an AstNode node is generated.
[0064] Each AstNode includes attributes such as node name, corresponding line number, parent node, and list of child nodes. Each AstNode is also added to the list of child nodes of its corresponding parent node.
[0065] After traversing the substructure of the current node, it automatically returns to the parent node of that node and continues to complete the traversal of the remaining parts.
[0066] Figure 2 The invention demonstrates the node class definition used to describe code structure, which details the attributes contained in the node (such as node name, line number, parent node, child node, etc.).
[0067] Figure 3The code structure fragments formed after the above traversal and extraction are displayed intuitively, proving that the method can capture all code information and the hierarchical relationship between codes.
[0068] This condition-based node generation and hierarchical relationship maintenance method ensures that the final extracted code structure is both comprehensive and hierarchical, accurately reflecting the inherent relationships between various control structures and sequentially executed code blocks in the C++ code.
[0069] S2. Based on the obtained code structure information, instrument the C++ code, that is, insert probes at appropriate locations in the code to record the code execution status and provide data support for subsequent coverage calculation.
[0070] Step S2 specifically includes two aspects: probe design and instrumentation strategies for different code structures, which are detailed below:
[0071] First, regarding the design of the probe, this invention defines a structure representing the data structure of the probe, using the following C language structure definition:
[0072] typedef struct{
[0073] int beg;
[0074] int end;
[0075] }ins1;
[0076] int ins_p1 = 0;
[0077] ins1 inss
[26] ;
[0078] The structure is declared at the beginning of the C++ class definition file, which includes the start line (beg) and end line (end). From beg to end, it represents the range of code lines covered by the probe. inss
[26] is the probe array, and the size of the array represents the number of probes in the class definition file. ins_p1 is an integer variable used as the index of the probe array inss. Its function is to record the number of probes that have been inserted and to indicate the position in the array where the next probe should be stored. Each time a new probe information is inserted into the ins array, ins_p1 will automatically increment by 1.
[0079] Secondly, regarding instrumentation strategies, this invention sets corresponding instrumentation rules for different types of code structures, as follows:
[0080] 1. For sequential code blocks (a sequential code block is a part of the code that is executed line by line without any jumps in between), the instrumentation strategy is to insert probe code at the end of the last line of the block to record the execution status from the beginning to the end of the block.
[0081] For example, in Figure 4 In the sequential structure shown, by inserting probe codes such as inss[ins_p1].beg=6;inss[ins_p1].end=8;, it indicates that the probe covers code lines 6-8, that is, the code range from int score=90; to int j=0;.
[0082] Second, for code blocks containing conditional statements, the instrumentation strategy is to insert a probe after the last statement in the conditional statement block to record the code execution when the condition is true.
[0083] like Figure 5 The image shows an example of instrumentation for the most common conditional statement, the if statement. The probe data inss[ins_p1].beg = 37; inss[ins_p1].end = 39; indicates that the probe covers lines 37-39, that is, the code range from if(i>0) to i++;.
[0084] Adding a probe directly to an if statement without curly braces will change the semantics of the original code; in addition, adding a probe directly to an if statement with else after it will cause a syntax error (because the presence or absence of curly braces does not affect the execution of an if statement that only executes one line of code, so programmers may have the habit of omitting curly braces).
[0085] To solve this problem, when a code block containing an if statement is detected, a search is first performed to determine whether it contains curly braces. If no curly braces are found, curly braces are added at the appropriate position according to C++ syntax.
[0086] For if statements with branches, in order to achieve branch coverage, probes need to be inserted on both the true and false states of the if statement. If there is an else statement that matches the if statement, the probe is inserted in the last statement of the else statement block. If there is no else statement, an empty else statement needs to be added, and the probe code is inserted in the empty else statement.
[0087] III. Figure 6 As shown, for code blocks containing switch-case statements, the instrumentation strategy is to insert probes between each case statement and its corresponding break statement to record the execution status of different case branches.
[0088] IV. For code blocks with loop structures, including for, while, and do-while statements, loop structures typically involve conditional branches. The instrumentation strategy is as follows:
[0089] First, determine the location of the loop condition, that is, identify the conditional statement in the loop structure used to determine whether to continue executing the loop body.
[0090] If the judgment result is true, meaning the loop body will continue to execute, probe code is inserted after the last statement of the loop body to record the execution status of this loop iteration.
[0091] If the judgment result is false, the loop will terminate. A probe is inserted at the corresponding position after the loop condition judgment fails to record the exit from the loop.
[0092] Throughout the program's execution, the probe data is simply updated and stored in an array, without any time-consuming operations such as direct file writing.
[0093] S3. Since frequent file writing operations during program execution can affect code execution efficiency, after the code execution is completed, the code execution path information is collected in the class destructor. In the destructor, the array storing probe data is traversed using a variable that records the current number of probes (such as ins_p1). The start line number and end line number of each probe record in the array are written to a newly generated text file in sequence.
[0094] like Figure 7 As shown, code execution information is collected in the class's destructor, which generates a text file and writes the probe's data into the text file.
[0095] S4. Calculate C++ code coverage. C++ code coverage includes statement coverage and branch coverage. Statement coverage is defined as the ratio of the number of executed statements to the total number of statements in the code under test. Branch coverage is defined as the ratio of the number of executed branches to the total number of branches in the code under test.
[0096] For statement coverage, the total number of statements in the tested code is obtained from the code structure information constructed in step S1, and the number of executed statements is obtained from the code execution path information collected in step S3.
[0097] For branch coverage, the number of executed branches and the total number of branches in the tested code are both obtained from the code structure information constructed in step S1. The number of executed branches is the number of branches that are true, and the total number of branches is the sum of the number of branches that are false and the number of branches that are true.
[0098] S5, Visualizes C++ code coverage, such as Figure 8As shown, the system generates a table to display the coverage of each code module. The table lists the name of each function, statement coverage, and branch coverage data, and gives the overall total result in the last row. At the code level, the system colors each line of code based on the probe data, using different colors to mark executed and unexecuted statements, so that developers can easily find test blind spots.
[0099] like Figure 9 As shown, we can use green to mark executed statements and red to mark unexecuted statements, as is customary.
[0100] Through the above implementation steps, the C++ code coverage analysis tool provided by this invention achieves automated code instrumentation, accurate execution path data collection, and intuitive coverage calculation and display, which not only ensures the accuracy of test data but also reduces the impact on program running efficiency.
[0101] In summary, this invention provides a C++ code coverage visualization detection method, which includes:
[0102] S1. Lexical and syntax analysis of C++ code: ANTLR is used to generate a lexical analyzer and a syntax analyzer, and an abstract syntax tree is constructed; an improved depth-first traversal algorithm with added extraction of code structure information is used to traverse the C++ code and obtain code structure information.
[0103] S2. Based on the obtained code structure information, instrument the C++ code by inserting probes at appropriate locations in the code to record the code execution status.
[0104] S3. Run the code and wait for it to finish executing. In the class's destructor, collect the code execution path information. Inside the destructor, use a variable that records the current number of probes to traverse the array storing probe data. Write the start and end line numbers of each probe record in the array into a newly generated text file.
[0105] S4. Calculate the C++ code coverage using the code structure information constructed in step S1 and the code execution path information collected in step S3.
[0106] S5. Visualize C++ code coverage by generating statistical tables and coloring code that was not executed differently.
[0107] The improved depth-first traversal algorithm for extracting code structure information added in step S1 includes:
[0108] The system traverses all nodes from the root of the abstract syntax tree. Whenever a node is encountered in the abstract syntax tree, the system determines whether the number of child nodes of the node is greater than 1, or whether it has only one child node and that child node is a leaf node. If the condition is met, the current node is considered to have independent structural meaning and an AstNode node is generated.
[0109] Each AstNode includes several attributes, including the node name, the corresponding line number of code, the parent node, and a list of child nodes. Each AstNode is also added to the list of child nodes of its corresponding parent node.
[0110] After traversing the substructure of the current node, it automatically returns to the parent node of that node and continues to complete the traversal of the remaining parts.
[0111] The steps in this invention can be adjusted, combined, or deleted according to actual needs.
[0112] The units in the device of the present invention can be merged, divided, or reduced according to actual needs.
[0113] Although the invention has been disclosed in detail with reference to the accompanying drawings, it should be understood that these descriptions are merely exemplary and not intended to limit the application of the invention. The scope of protection of the invention is defined by the appended claims and may include various modifications, alterations, and equivalents made to the invention without departing from the scope and spirit of the invention.
Claims
1. A method for visualizing and detecting C++ code coverage, characterized in that, The method includes: S1. Lexical and syntax analysis of C++ code: ANTLR is used to generate a lexical analyzer and a syntax analyzer, and an abstract syntax tree is constructed; an improved depth-first traversal algorithm with added extraction of code structure information is used to traverse the C++ code and obtain code structure information; S2. Based on the obtained code structure information, instrument the C++ code by inserting probes at appropriate locations in the code to record the code execution status. S3. Run the code and wait for the code execution to complete. In the class destructor, collect the code execution path information. In the destructor, use the variable that records the current number of probes to traverse the array that stores probe data. Write the start line number and end line number of each probe record in the array into a newly generated text file. S4. Calculate the C++ code coverage using the code structure information constructed in step S1 and the code execution path information collected in step S3. S5. Visualize C++ code coverage by generating statistical tables and using different colors to indicate whether the code was executed. The improved depth-first traversal algorithm for extracting code structure information added in step S1 includes: The system traverses all nodes from the root of the abstract syntax tree. Whenever a node is encountered in the abstract syntax tree, the system determines whether the number of child nodes of the node is greater than 1, or whether it has only one child node and that child node is a leaf node. If the condition is met, the current node is considered to have independent structural meaning and an AstNode node is generated. Each AstNode includes several attributes, including the node name, the corresponding line number of code, the parent node, and a list of child nodes. Each AstNode is also added to the list of child nodes of its corresponding parent node. After traversing the substructure of the current node, it automatically returns to the parent node of that node and continues to complete the traversal of the remaining part. Step S2 first defines a structure representing the probe's data structure, using the following C language structure definition: typedef struct{ int beg; int end; }ins1; int ins_p1 = 0; ins1 inss[26]; The structure is declared at the beginning of the C++ class definition file, including the variable start line beg and end line end. From beg to end, it represents the range of code lines covered by the probe; inss[26] is the probe array, and the size of the array represents the number of probes in the class definition file; ins_p1 is an integer variable used as the index of the probe array inss. Its function is to record the number of probes that have been inserted and to indicate the position in the array where the next probe should be stored. Each time a new probe information is inserted into the ins array, ins_p1 will automatically increment by 1.
2. The C++ code coverage visualization detection method as described in claim 1, characterized in that, The visualization in step S5 specifically includes: The system generates a table to display the coverage of each code module. The table lists the name of each function, statement coverage, and branch coverage data, and gives the overall total result in the last row. At the code level, the system colors each line of code based on the probe data, using different colors to mark executed and unexecuted statements.
3. The C++ code coverage visualization detection method as described in claim 1, characterized in that, The step of constructing the abstract syntax tree in step S1 includes: using the open-source tool ANTLR to generate a lexical analyzer and a syntax analyzer; using the lexical analyzer to decompose the C++ code into basic lexical units; and using the syntax analyzer to combine the decomposed lexical units into expressions, statements, and higher-level code blocks that conform to the grammatical structure, forming an abstract syntax tree that intuitively reflects the hierarchical structure of the source code and the relationships between its components.
4. The C++ code coverage visualization detection method as described in claim 1, characterized in that, Step S2 sets corresponding instrumentation strategies for different types of code structures, as follows: For sequential code blocks, the instrumentation strategy is to insert probe code at the end of the last line of the code block to record the execution status from the beginning to the end of the block; For code blocks containing conditional statements, the instrumentation strategy is to insert a probe after the last statement in the conditional statement block to record the code execution when the condition is true. For code blocks containing switch-case statements, the instrumentation strategy is to insert probes between each case statement and its corresponding break statement to record the execution status of different case branches; For code blocks containing loop structures, including for, while, and do-while statements, loop structures typically involve conditional branches. The instrumentation strategy is as follows: First, determine the location of the loop condition, that is, identify the conditional statement in the loop structure used to determine whether to continue executing the loop body; If the judgment result is true, that is, the loop body will continue to execute, a probe code is inserted after the last statement of the loop body to record the execution status of this loop iteration; If the judgment result is false, the loop will terminate. A probe is inserted at the corresponding position after the loop condition judgment fails to record the exit from the loop.
5. The C++ code coverage visualization detection method as described in claim 4, characterized in that, In the instrumentation strategy, for a code block containing a conditional statement (if), it is first checked whether the code block contains curly braces. If there are no curly braces, curly braces are added at the appropriate position according to C++ syntax.
6. The C++ code coverage visualization detection method as described in claim 4, characterized in that, In the instrumentation strategy, for if statements with branches, probes need to be inserted on both the true and false states of the if statement. If there is an else statement that matches the if statement, the probe is inserted in the last statement of the else statement block. If there is no else statement, an empty else statement needs to be added, and the probe code is inserted in the empty else statement.
7. The C++ code coverage visualization detection method as described in claim 1, characterized in that, The C++ code coverage calculated in step S4 includes statement coverage and branch coverage. Statement coverage is defined as the ratio of the number of executed statements to the total number of statements in the tested code, and branch coverage is defined as the ratio of the number of executed branches to the total number of branches in the tested code.
Citation Information
Patent Citations
Code coverage rate detection method and device
CN113836006A
Branch coverage rate test method, coverage rate test method, electronic equipment and storage medium
CN116257448A