Code traversal exception detection method and device, equipment and storage medium

By parsing Java files to generate an abstract syntax tree, it detects null data objects in code traversal operations, traverses the parent node list upwards and checks null operations, generates exception reports and repair suggestions, solves the shortcomings of code traversal exception detection, and improves code stability and development efficiency.

CN119311279BActive Publication Date: 2025-11-18PING AN BANK CO LTD
View PDF 2 Cites 0 Cited by

Patent Information

Application Number
CN202411343430.3
Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2024-09-25
Publication Date
2025-11-18
Estimated Expiration
2044-09-25

AI Technical Summary

Technical Problem

Existing technologies cannot effectively detect cases where data objects are empty during code traversal operations, leading to null pointer exceptions at runtime. This necessitates extensive testing with insufficient test coverage, impacting the stability and development efficiency of financial systems.

Method used

The abstract syntax tree is generated by parsing Java files in the project source code folder, the StatementExpression node of the traversal operation is found, the parent node list is traversed upwards, the conditional statement and null check operation are checked, an exception report is generated and a repair suggestion is provided.

Benefits of technology

It reduces the reliance on extensive testing during the development phase, detects traversal exceptions in advance, avoids null pointer exceptions at runtime, and improves code stability and development efficiency.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN119311279B_ABST
    Figure CN119311279B_ABST
Patent Text Reader

Abstract

The application relates to the technical field of research and development management and the field of financial technology, and discloses a code traversal exception detection method, which comprises the following steps: Java files in a project source code folder are parsed to generate an abstract syntax tree; a StatementExpression node of a traversal operation is searched in the syntax tree, and it is judged whether the name of the StatementExpression node starts with forEach or for; after confirming the traversal operation, parent nodes in the syntax tree are analyzed upwards to form a parent node list; the parent nodes are further analyzed to check whether the parent nodes contain conditional judgment statements, and it is determined whether there is a null judgment operation on a data object in the conditional judgment; if no null judgment operation is found, the traversal operation is marked as an exception, and a corresponding exception report is generated. The application can reduce the dependence on a large number of tests in the development stage, detect traversal exceptions in advance, avoid runtime null pointer exceptions, and improve the stability and development efficiency of the code.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the fields of R&D management technology and financial technology, and in particular to a method, apparatus, device and storage medium for detecting code traversal anomalies. Background Technology

[0002] In the development of financial systems, financial data structures are complex, involving multi-layered business logic and data transfer. Modern software development typically employs a data layering domain model to divide the data in financial systems into multiple data objects, such as data transfer objects, data access objects, business objects, and presentation layer objects. When transferring data between these objects, financial developers often use foreach or for loops to perform batch operations on all attributes of the data objects in order to improve development efficiency.

[0003] However, existing technologies present some potential problems with this traversal operation, especially when the data object is empty. Since foreach or for operations on data objects do not report errors during the compile-time phase, exceptions (such as null pointer exceptions) may occur during runtime. These problems are usually difficult to detect at runtime and can only be caught through extensive testing. Financial systems have extremely high requirements for accuracy and stability; any program exception can lead to business process interruptions or data errors.

[0004] However, existing technologies have the following shortcomings when handling these traversal operations:

[0005] Reliance on extensive testing: To avoid these traversal exceptions, a significant amount of testing manpower and time is typically required to check for potential problems in the code. This not only increases the development cost of financial projects but also negatively impacts project schedules.

[0006] Insufficient test coverage: Even with extensive testing, it is difficult to fully cover all potential problems in traversal operations, especially in complex data structures or special cases, where abnormal traversal issues may be missed.

[0007] Due to these issues, existing financial systems pose certain risks in code traversal operations. Financial institutions need to rely on more efficient and accurate code inspection tools to help developers identify these potential traversal anomalies in advance, thus avoiding unforeseen errors during system runtime. These tools need to utilize static analysis techniques to detect potential anomalies during the code writing phase, reducing the testing burden and improving system stability and security. Summary of the Invention

[0008] The main objective of this invention is to provide a method, apparatus, device, and storage medium for detecting code traversal anomalies, aiming to solve the technical problem that existing technologies cannot effectively detect when data objects are empty during traversal operations, thus failing to prevent potential anomalies in traversal operations.

[0009] To achieve the above objectives, the present invention provides a code traversal exception detection method, comprising:

[0010] Obtain the project source code folder and traverse the project source code folder, filter out the Java files, and store them in the Java file list;

[0011] Each Java file in the list of Java files is parsed to generate a corresponding abstract syntax tree;

[0012] In each abstract syntax tree, find the StatementExpression node that represents the expression operation, and determine whether the name attribute of the StatementExpression node ends with forEach or begins with for;

[0013] If so, confirm that the StatementExpression node is a traversal operation node, traverse the corresponding abstract syntax tree upwards, obtain all parent nodes of the traversal operation node, and generate a list of parent nodes;

[0014] Traverse the list of parent nodes, determine whether the parent node contains a conditional statement, and check whether the conditional statement contains an empty check operation on the data object.

[0015] If the conditional statement does not include a null check for the data object, then the corresponding StatementExpression node is confirmed to have a data object traversal exception, and an exception report is generated.

[0016] In one embodiment, the corresponding abstract syntax tree is traversed upwards to obtain all parent nodes of the traversal operation node, generating a list of parent nodes, including:

[0017] The position information of the traversal operation node is marked, and the file name, line number and column number of the traversal operation node are recorded for locating the location of the abnormal code;

[0018] Record the association between the traversal operation node and its direct parent node, and establish the hierarchical relationship between the traversal operation nodes in the context syntax structure;

[0019] Using the hierarchical relationship, all parent nodes of the operation node are recursively searched upwards in the corresponding abstract syntax tree, and the syntax type of each parent node is marked. The syntax type is used to identify conditional statements.

[0020] Each parent node is stored in the parent node list according to the syntax structure, generating a hierarchical parent node path.

[0021] In one embodiment, the parent node list is traversed to determine whether each parent node contains a conditional statement, and the conditional statement is checked to see if it contains a null check operation on a data object, including:

[0022] Iterate through the list of parent nodes, starting from the first node in the list, and process each parent node in turn.

[0023] The syntax type of each parent node is determined to identify whether it is a conditional statement, including if statements, else if statements, and switch statements.

[0024] Analyze the identified conditional statements to check whether the conditional expressions contain null checks for ! = null on the data objects in the traversal operation;

[0025] If any conditional statement does not include an empty check operation, then the corresponding traversal operation node is marked as an abnormal node.

[0026] In one embodiment, generating an anomaly report includes:

[0027] Generate an exception report and list the StatementExpression nodes marked as exceptions. The exception report includes the file path, line number, and column number of the exception nodes.

[0028] Based on the anomaly report, a repair suggestion is generated, which includes a code example of adding "! = null" to check for null values ​​before the anomaly node.

[0029] Send the aforementioned anomaly report and repair suggestions to the developers, notifying them of the issues that need to be addressed;

[0030] In the development environment, exception nodes are highlighted to help developers locate problematic code;

[0031] Upon receiving an automatic repair instruction, null check code is inserted before the abnormal node according to the repair suggestion, and the inserted code is marked.

[0032] In one embodiment, the project source code folder is retrieved and traversed to filter out Java files and store them in a Java file list, including:

[0033] Extract the project source code folder from the project root directory, recursively traverse the subfolders within the project source code folder, and process each subfolder and the files contained within it layer by layer.

[0034] During the traversal, hidden files, non-code files, build folders, and test folders are filtered out based on file extensions, hidden attributes, and code file types in the project.

[0035] Filter source code files with the .java extension and store the path of each filtered Java file in a Java file list;

[0036] Using file path identifiers, processed file paths are separated from unprocessed file paths, and the processing status of each file is recorded during the traversal, including whether the file has been processed, the file processing time, and the processing result.

[0037] In one embodiment, each Java file in the list of Java files is parsed to generate a corresponding abstract syntax tree, including:

[0038] Lexical analysis is performed on the Java file by reading the source code line by line and dividing the source code into lexical units, which include keywords, identifiers, operators and delimiters.

[0039] Based on the lexical unit, the parser sequentially parses the source code in the Java file and generates corresponding syntax nodes according to the syntax structure of the Java language.

[0040] An abstract syntax tree corresponding to a Java file is constructed based on the syntax nodes. The abstract syntax tree consists of multiple syntax nodes, each of which represents a syntax structure element in the Java file.

[0041] In one embodiment, lexical analysis is performed on the Java file, and the source code in the Java file is read line by line, including:

[0042] The Java files are grouped based on their size and historical processing time in the Java file list, and each group of Java files is assigned to an independent thread for processing.

[0043] Each Java file is assigned a processing priority based on its importance and modification time.

[0044] The assigned independent thread reads the source code of the Java files in the group line by line according to the processing priority.

[0045] Furthermore, to achieve the above objectives, the present invention also provides a code traversal anomaly detection device, the code traversal anomaly detection device including a memory, a processor, and a code traversal anomaly detection program stored in the memory and executable on the processor, wherein when the code traversal anomaly detection program is executed by the processor, it implements the steps of the code traversal anomaly detection method as described above.

[0046] Furthermore, to achieve the above objectives, the present invention also provides a computer storage medium storing a code traversal exception detection program, wherein the code traversal exception detection program, when executed by a processor, implements the steps of the code traversal exception detection method described above.

[0047] Beneficial Effects: This invention relates to a method for detecting code traversal exceptions. It generates an abstract syntax tree by parsing Java files in the project's source code folder. The method searches for the `StatementExpression` node representing the traversal operation within the syntax tree and determines if its name begins with `forEach` or `for`. After confirming the traversal operation, it analyzes the parent nodes in the syntax tree upwards to form a list of parent nodes. Further analysis of the parent nodes checks for conditional statements and determines if any of these conditional statements perform null checks on data objects. If no null checks are found, the traversal operation is marked as an exception, and a corresponding exception report is generated. This invention reduces the reliance on extensive testing during the development phase, detects traversal exceptions in advance, avoids runtime null pointer exceptions, and improves code stability and development efficiency. Attached Figure Description

[0048] The present invention will be further described below with reference to the accompanying drawings and embodiments. In the accompanying drawings:

[0049] Figure 1 This is a flowchart illustrating an embodiment of the code traversal anomaly detection method of the present invention;

[0050] Figure 2 This is a schematic diagram of the functional modules of a preferred embodiment of the code traversal anomaly detection device of the present invention;

[0051] Figure 3 This is a schematic diagram of the hardware operating environment of the device involved in the embodiment of the code traversal anomaly detection device of the present invention. Detailed Implementation

[0052] It should be understood that the specific embodiments described herein are for illustrative purposes only and are not intended to limit the scope of the invention.

[0053] In the development of financial systems, financial data structures are complex, involving multi-layered business logic and data transfer. Modern software development typically employs a data layering domain model to divide the data in financial systems into multiple data objects, such as data transfer objects, data access objects, business objects, and presentation layer objects. When transferring data between these objects, financial developers often use foreach or for loops to perform batch operations on all attributes of the data objects in order to improve development efficiency.

[0054] However, existing technologies present some potential problems with this traversal operation, especially when the data object is empty. Since foreach or for operations on data objects do not report errors during the compile-time phase, exceptions (such as null pointer exceptions) may occur during runtime. These problems are usually difficult to detect at runtime and can only be caught through extensive testing. Financial systems have extremely high requirements for accuracy and stability; any program exception can lead to business process interruptions or data errors.

[0055] However, existing technologies have the following shortcomings when handling these traversal operations:

[0056] Reliance on extensive testing: To avoid these traversal exceptions, a significant amount of testing manpower and time is typically required to check for potential problems in the code. This not only increases the development cost of financial projects but also negatively impacts project schedules.

[0057] Insufficient test coverage: Even with extensive testing, it is difficult to fully cover all potential problems in traversal operations, especially in complex data structures or special cases, where abnormal traversal issues may be missed.

[0058] Due to these issues, existing financial systems pose certain risks in code traversal operations. Financial institutions need to rely on more efficient and accurate code inspection tools to help developers identify these potential traversal anomalies in advance, thus avoiding unforeseen errors during system runtime. These tools need to utilize static analysis techniques to detect potential anomalies during the code writing phase, reducing the testing burden and improving system stability and security.

[0059] Please see Figure 1 , Figure 1 This is a flowchart illustrating an embodiment of the code traversal exception detection method provided by the present invention. It should be noted that although the logical order is shown in the flowchart, in some cases, the steps shown or described may be performed in a different order than that shown here.

[0060] like Figure 1 As shown, the code traversal exception detection method proposed in this invention includes the following steps:

[0061] S10, obtain the project source code folder and traverse the project source code folder, filter out the Java files, and store them in the Java file list;

[0062] In this embodiment, the project source code folder is extracted from the project root directory specified by the system. The source code folder is a container for the entire project files, typically containing code files, configuration files, resource files, etc. The source code folder structure is crucial in project development, determining how files are organized. The project's root folder is pulled or loaded from the specified path by calling a file system API or version control system (such as Git). It is ensured that the folder path is correct and that all relevant source code files are correctly loaded into the system.

[0063] This function recursively traverses all files and subfolders within the project's source code folder. Recursive traversal is a common file processing method, iterating through each subfolder level by level until all files have been traversed. It uses a recursive algorithm to iterate through every file and subfolder in the folder. System file handling tools (such as Java's Files.walkFileTree()) can be used to read the folder contents level by level and record the files.

[0064] After traversing the folder, filter out Java files (i.e., files with the .java extension). This ensures that only source code files are processed, ignoring non-Java files (such as configuration files, images, and other file types). Filtering by file extension uses a filtering mechanism to determine the file type. You can check the extension of each file in the traversed file list and add .java files to the results list.

[0065] The filtered Java file paths are stored in a dedicated list for use in subsequent processing steps. This list is the result of iteration and filtering, ensuring that all Java files are stored in an ordered structure. A list or array structure is created to store the complete path (including filename, folder path, etc.) of each filtered Java file. This step can use a collection class (such as ArrayList in Java) to store the file paths.

[0066] In one specific implementation, the project source code folder is cloned from a remote Git repository to the local system, and the complete project source code folder is obtained using the `git clone` command. During traversal, a file monitoring mechanism is used to ensure that newly added files or folders in the project folder are captured during traversal, achieving dynamic traversal. Java file filtering is based not only on file extensions but also on configuration files in the project (such as `.ignore` files) to exclude Java files that do not need to be processed. When storing Java file paths, they are stored in JSON format in the file system for direct use by subsequent automation tools.

[0067] By pre-fetching the project source code folder and traversing all subfolders, the system can ensure that all relevant Java files are captured during processing, avoiding omissions. Simultaneously, filtering out irrelevant files by selecting Java files improves the efficiency of subsequent code processing steps. Storing the paths of the selected Java files simplifies subsequent operations, ensures the completeness and accuracy of the file list, and effectively improves development efficiency and the precision of code management.

[0068] S20, parse each Java file in the Java file list and generate the corresponding abstract syntax tree;

[0069] In this embodiment, each selected Java file is parsed, breaking down its content into basic syntactic units that can be analyzed and processed. The parsing process includes lexical analysis and syntax analysis to understand the syntactic structure of the code in the file. Lexical analysis is responsible for breaking down the code into the smallest syntactic units such as keywords, variable names, and operators; while syntax analysis is responsible for checking the compositional relationships between these units. In implementation, the Java compiler API or open-source static code analysis tools (such as Javaparser or ANTLR) can be used to parse the Java files. These tools read the code content as text, process the code line by line, generate lexical units, and then perform syntax analysis to check the syntactic structure and generate an abstract syntax tree.

[0070] An Abstract Syntax Tree (AST) is a tree-like data structure generated after code parsing, where each node represents a syntax element, such as a variable declaration, method call, or control structure. The AST is used for subsequent code analysis and manipulation. It is the output of syntax analysis, showing the hierarchical relationship of the code structure for further analysis and modification. The parser constructs the AST based on the syntax rules of the Java language. Each syntax element generates a corresponding node, and the hierarchical structure between nodes reflects the logical order and scope of the code. The AST can be stored in memory or serialized into a file for use in subsequent steps.

[0071] In another specific implementation, the Javaparser library is used to parse Java files and generate an abstract syntax tree (AST). After the system reads the file content, the Javaparser parses each line of code into lexical units and constructs the AST according to Java's syntax rules. The AST structure is stored as an object for use in subsequent steps. The advantage of Javaparser lies in its support for in-depth code parsing and comment analysis, which helps in handling complex code structures.

[0072] By parsing Java files and generating abstract syntax trees (ASTs), a deeper understanding of the code structure of each file can be achieved, supporting subsequent traversal operations and exception detection. ASTs accurately represent the syntactic relationships of code in a hierarchical manner, improving the accuracy of code inspection and optimization, and reducing the risk of exceptions caused by code errors.

[0073] S30, in each abstract syntax tree, find the StatementExpression node that represents the expression operation, and determine whether the name attribute of the StatementExpression node ends with forEach or begins with for;

[0074] In this embodiment, specific nodes representing traversal operations are located within the Abstract Syntax Tree (AST). In Java, a StatementExpression node represents an expression operation in the program, such as variable assignment or method call. By scanning the AST, all these expression operation nodes can be identified, providing a foundation for subsequent traversal detection. Each AST is traversed, visiting nodes one by one, and the type information of each node is used to identify nodes of the StatementExpression type. Syntax analysis tools (such as Javaparser, ANTLR, etc.) provide APIs for finding and filtering syntax nodes of a specified type. This process uses recursive traversal of the syntax tree or a depth-first search (DFS) algorithm to ensure that all possible nodes are processed.

[0075] After locating the StatementExpression node, its name attribute needs further examination to determine if it's an operation used for iteration. Specifically, check if its name ends with "forEach" (typically used for collection iteration) or begins with "for" (typically used for for loops). This helps filter out expressions related to iteration operations and prevents misidentification of other non-iteration expressions. After finding the StatementExpression node, obtain its name (such as a method name or variable name) through its attributes. Then, use string matching functions (such as String.endsWith() and String.startsWith()) to check if the name matches the pattern "forEach" or "for". If a match is found, mark the node as an iteration operation node for further processing in subsequent steps.

[0076] In another specific implementation, a custom syntax tree traversal algorithm is used to perform a depth-first search (DFS) on the abstract syntax tree of each Java file. At each StatementExpression node, the name attribute is read, and regular expression matching is used to check if it ends with "forEach" or begins with "for". Nodes that match successfully are added to a list for use in subsequent anomaly detection steps.

[0077] By locating StatementExpression nodes in the abstract syntax tree and examining their name attributes, traversal operations in the code can be efficiently identified. This automates the identification process, avoids the tedious work of manually checking for traversal operations in the code, reduces the complexity of code maintenance, and improves the accuracy of code detection.

[0078] S40, if so, confirm that the StatementExpression node is a traversal operation node, traverse the corresponding abstract syntax tree upwards, obtain all parent nodes of the traversal operation node, and generate a list of parent nodes;

[0079] In this embodiment, after determining that the name attribute of the StatementExpression node meets the conditions for a traversal operation (such as ending with "forEach" or starting with "for"), the node is confirmed as a traversal operation node. This means that the code snippet represented by the node may contain traversal operations on collections or arrays. After the name check in the previous step, if the conditions match, the system marks this StatementExpression node as a traversal operation node. This marking clarifies that the node is related to a traversal operation in subsequent analysis, allowing for further examination of contextual information.

[0080] After identifying the node to be traversed, it's necessary to traverse the abstract syntax tree upwards from that node to find its parent node. The parent node typically contains contextual information about the traversal operation, such as whether it's nested within a conditional statement or related to other statements. Obtaining these parent nodes allows for a better understanding of the code logic. Use the upward traversal functionality of the tree structure to visit the parent node of the current node level by level. You can use recursion or iteration to backtrack from the traversed node along the syntax tree to the root node or other logically higher nodes.

[0081] During the upward traversal, all visited parent nodes are recorded, forming a parent node list. This list helps in detailed analysis of the traversal operation's context, such as determining whether the traversal operation was executed under specific conditions. The parent node list stores the traversed node and all its parent nodes. During the upward traversal, each encountered parent node is added to the list. The generated parent node list is sorted hierarchically, with higher-level parent nodes appearing earlier in the list. This list will be used for subsequent conditional checks to further analyze the traversal operation's context.

[0082] In other implementations, a custom abstract syntax tree traversal tool is used to identify the nodes to be traversed and then iteratively retrieve the parent nodes. Each time, the search proceeds upwards from the child nodes until the root node, generating a list of parent node paths. This list of parent nodes can be used to mark the hierarchical relationship of each node, aiding in subsequent structured code analysis.

[0083] By traversing the abstract syntax tree upwards and obtaining the parent node of the traversal operation node, contextual information of the code can be effectively captured, helping developers understand the logical structure of the traversal operation. The process of generating a list of parent nodes facilitates further analysis of the safety and exception handling of the traversal operation, avoiding potential code errors.

[0084] S50, traverse the list of parent nodes, determine whether the parent node contains a conditional judgment statement, and check whether the conditional judgment statement contains a null check operation on the data object.

[0085] In this embodiment, the list of parent nodes generated during upward traversal of the syntax tree is processed. Each parent node in the list is visited sequentially, and their type and structure are analyzed. By traversing the parent nodes, the logical level of the traversal operation can be identified, and its contextual relationships can be understood. Using iterative or recursive methods, each node in the parent node list is visited sequentially, and the type and content of each node are checked for subsequent conditional statement analysis. The type of a parent node can be obtained through the attributes of the syntax tree node; tools such as Javaparser can obtain the type information of each node through its API.

[0086] Conditional statements typically include if, else if, and switch statements. In this step, the system needs to check if these conditional structures exist in the parent node to determine if the traversal operation is controlled by certain specific conditions. If the traversal operation executes under certain conditions, understanding these conditions helps determine the logical robustness of the code. By checking the type of the parent node, it can be determined whether it belongs to a conditional statement (such as if, else if, switch, etc.). The node type can be obtained by calling the getType() method of the syntax tree traversal tool and matching common conditional statement types. If the parent node is a conditional statement, its specific content is further analyzed.

[0087] Null checks are a crucial step in preventing NullPointerExceptions, typically performed in Java using `!= null` to check if an object is null. The goal of this step is to check conditional statements for null checks on data objects, ensuring that null values ​​are adequately handled during iteration to avoid runtime exceptions. After identifying the conditional statement, the conditional expression is further parsed to check for `!= null` null checks. Syntax tree analysis tools can be used to obtain child nodes of the conditional expression, analyze their content, and determine if null checks are present. If a null check is found, the conditional statement is marked as safe; otherwise, the node is marked as a potential exception.

[0088] In another specific implementation, a custom syntax tree traversal algorithm is used to perform a deep check on each parent node in the list. When determining the type of each parent node, keywords such as `if`, `else if`, or `switch` are matched using regular expressions. The content of the conditional expressions is analyzed to check for null operations (e.g., `!= null`). If no null operation is found, the traversed node is marked as an anomaly.

[0089] By traversing the list of parent nodes and checking whether the conditional statements contain null checks, null pointer exceptions during traversal can be effectively prevented. Ensuring that data objects undergo safety checks before traversal operations reduces the risk of runtime exceptions and improves code robustness and reliability.

[0090] S60. If the conditional statement does not include a null check for the data object, then the corresponding StatementExpression node is confirmed to have a data object traversal exception, and an exception report is generated.

[0091] In this embodiment, after checking the conditional statements in the previous step, if the conditional statements do not contain a null check (e.g., != null), the system considers the traversal operation potentially risky. The absence of a null check could lead to a NullPointerException being thrown during traversal when the data object is null, affecting system stability. Each conditional statement's expression is parsed, particularly the conditional expression itself, to determine if it contains != null or other forms of null checks. If no such operation is found, the system marks this conditional statement as an unsafe traversal and generates an exception report for the identified abnormal node, sending it to the developers for reference.

[0092] If the system confirms through analysis that no null check was found in the conditional statements, it will mark the current StatementExpression node as an abnormal traversal node. This means that this traversal operation may cause an exception due to a null data object and should be fixed. The system marks the corresponding traversal operation node (i.e., the StatementExpression node) as an abnormal node. The node's information (including file path, line number, column number, etc.) is recorded for subsequent exception reporting and repair suggestions. Through this marking, subsequent code processing tools can identify the potential problem with this node.

[0093] In one specific implementation, if a null check (!= null) is missing after checking the conditional statement, the system marks the traversed node as an exception using the Javaparser API. Information about the traversed node, including its file path, line number, and column number, is stored to generate an exception report. Subsequent automation tools can then automatically add null check code before traversing the node based on this exception flag.

[0094] By detecting null checks in conditional statements, potential traversal operation exceptions can be effectively identified, preventing null pointer exceptions caused by empty data objects. Once the abnormal traversal node is identified, the system can provide clear remediation guidance, helping developers improve code robustness and reduce the risk of runtime errors and system crashes.

[0095] This invention relates to a method for detecting code traversal exceptions. It generates an abstract syntax tree (AST) by parsing Java files in the project's source code folder. The method searches for StatementExpression nodes involved in traversal operations within the AST and determines if their names begin with "forEach" or "for". After confirming the traversal operation, it analyzes the parent nodes in the AST upwards, forming a list of parent nodes. Further analysis of the parent nodes checks for conditional statements and determines if any of these conditional statements perform null checks on data objects. If no null checks are found, the traversal operation is marked as an exception, and a corresponding exception report is generated. This invention reduces the reliance on extensive testing during development, detects traversal exceptions early, avoids runtime null pointer exceptions, and improves code stability and development efficiency.

[0096] In one embodiment, in S40 above, traversing upwards through the corresponding abstract syntax tree to obtain all parent nodes of the traversal operation node and generating a parent node list includes:

[0097] S401, mark the position information of the traversal operation node, and record the file name, row number and column number of the traversal operation node for locating the location of the abnormal code;

[0098] S402, record the association between the traversal operation node and the direct parent node, and establish the hierarchical relationship of the traversal operation node in the context syntax structure.

[0099] S403, using the hierarchical relationship, recursively search upwards in the corresponding abstract syntax tree to traverse all parent nodes of the operation node, and mark the syntax type of each parent node, the syntax type being used to identify conditional statements;

[0100] S404, store each parent node in the parent node list according to the syntax structure to generate a hierarchical parent node path.

[0101] In this embodiment, the abstract syntax tree (AST) recursively traverses upwards from the traversal operation node, focusing on its parent nodes. Parent nodes represent higher-level structures in the code, and obtaining these nodes helps in understanding the context of the traversal operation. The AST is recursively traversed using depth-first search (DFS) or other traversal algorithms, retrieving parent nodes one by one. Whenever a parent node is found, it is added to the parent node list, and the traversal continues upwards until the root node.

[0102] During the process of marking traversal operation nodes, their specific location in the source code (filename, line number, column number) is recorded. This information is crucial for subsequent exception reporting and for developers to locate problematic code. The location information (filename, line number, column number) of each traversal operation node is obtained through a parser (such as Javaparser or ANTLR), and this data is stored as part of the exception detection system for easy tracking and remediation.

[0103] During traversal, the association between the traversal operation node and its direct parent node is recorded. This hierarchical relationship helps understand the position of the traversal operation in the code structure and its related context, such as whether it is nested within a conditional statement or a loop. During upward traversal, the system associates the traversal operation node with its parent node, establishing its hierarchical structure in the code. This hierarchical structure can be stored using a tree data structure and used for further contextual analysis.

[0104] While recursively searching upwards for parent nodes, it's necessary to label the syntax type of each parent node. The syntax type can be a conditional statement, method call, loop statement, etc. This information helps determine whether the traversal operation is executed under certain specific conditions. Using the parser API or a custom recursive function, while retrieving each parent node, call its `getType()` method to obtain the syntax type, and store the syntax type along with the node for further analysis.

[0105] All retrieved parent nodes are stored in a list according to their hierarchical structure, forming a complete parent node path. This path information helps analyze the position and impact of the traversal operation within the overall code structure. During the traversal, each parent node is stored in a list, arranged in hierarchical order, forming a parent node path from the bottom layer to the top layer. This structured storage method allows for easy retrieval of the traversal operation's context information.

[0106] In one specific implementation, the abstract syntax tree is parsed using a Javaparser. After identifying the traversable nodes, all parent nodes are recursively traversed upwards. Each time a parent node is found, its position information (filename, row number, column number) is recorded, and its syntax type (such as if statement, for loop, etc.) is marked. All parent nodes are stored in a linked list, arranged in hierarchical order, ultimately forming a parent node path from the traversed nodes to the root node.

[0107] This embodiment traverses the abstract syntax tree upwards and obtains all parent nodes of the traversal operation node, enabling a comprehensive analysis of the traversal operation's context information. Marking the position information and syntax type of the traversal operation node and its parent nodes not only helps developers quickly locate potential abnormal code but also effectively understands the hierarchical relationship of traversal operations, ensuring code security and robustness.

[0108] In one embodiment, the above S50 includes:

[0109] S501, Traverse the list of parent nodes, starting from the first node in the list, and process each parent node in turn;

[0110] S502, determine the syntax type of each parent node and identify whether it is a conditional statement, including if statement, else if statement and switch statement;

[0111] S503, Analyze the identified conditional statements and check whether the conditional expression contains a null check for ! = null on the data object in the traversal operation;

[0112] S504 If any conditional statement does not contain an empty check operation, then mark the corresponding traversal operation node as an abnormal node.

[0113] In this embodiment, starting from the first node in the parent node list, all parent nodes are processed sequentially. The parent node list stores all the ancestral nodes of the node being traversed. By traversing this list, the type and logical structure of each node can be checked sequentially to determine whether it is a conditional statement. In implementation, the system processes parent nodes one by one according to the order of the list. Each parent node can be traversed using an iterator or recursion and passed to subsequent steps for detailed analysis. The type information of each parent node can be obtained through the attributes of the syntax tree node.

[0114] The syntax type of the parent node is checked to determine if it belongs to a conditional statement type, such as if, else if, or switch. Conditional statements are typically used to control the execution logic of traversal operations, and identifying these statements is a crucial prerequisite for subsequent null checks. The system identifies whether each parent node is a conditional statement by checking its type information. Parser tools usually provide APIs for obtaining node types (such as getType()), which can determine their syntax type by matching keywords (such as if, switch).

[0115] Once a conditional statement is identified, the system further analyzes its expression to check for null checks (i.e., `!= null`). Null checks are crucial for preventing null pointer exceptions; confirming their presence ensures safe execution of the traversal operation. Within identified conditional statements, the system examines the expression. Expression parsing tools can be used to retrieve child nodes of the condition and match expressions where `!= null`. If a null check is found, the system considers the traversal operation safe.

[0116] If no null check is found for the data object in the conditional statement, the system considers the traversal operation potentially abnormal and marks the corresponding traversal node as an abnormal node. This means that a runtime error may occur during code execution due to a null data object. If, after traversing all child nodes of the conditional statement, the system finds no null check, the current traversal node is marked as abnormal. This marking information is usually stored and used to generate an exception report later, reminding developers to fix code issues.

[0117] In one specific implementation, the abstract syntax tree is parsed using a Javaparser. While traversing the list of parent nodes, the type of each parent node is checked to identify if, else if, or switch statements. The content of the conditional statements is analyzed to check for null checks such as != null. If no null condition is found, the traversed node is marked as an exception, and its location information is stored for later exception reporting.

[0118] This embodiment, by traversing the list of parent nodes, allows the system to identify the logical context of the traversal operation and detect whether the conditional statements contain null checks on data objects. This helps to detect potential traversal exceptions in advance and avoids null pointer exceptions at runtime. By automatically marking abnormal nodes, the system provides developers with a clear path to fix the issues, effectively improving code robustness and development efficiency.

[0119] In one embodiment, in step S60 above, generating an anomaly report includes:

[0120] S701, Generate an exception report and list the StatementExpression nodes marked as exceptions. The exception report includes the file path, line number, and column number of the exception nodes.

[0121] S702, Generate a repair suggestion based on the anomaly report. The repair suggestion includes a code example of adding a null check operation (!=null) before the anomaly node.

[0122] S703, the error report and repair suggestions are sent to the developers, notifying them of the issues that need to be addressed;

[0123] S704 uses highlighting to mark abnormal nodes in the development environment, helping developers locate problematic code.

[0124] S705, upon receiving an automatic repair instruction, inserts null check code before the abnormal node according to the repair suggestion, and marks the inserted code.

[0125] In this embodiment, upon detecting an anomaly in data object traversal within a StatementExpression node, a detailed anomaly report is generated, listing all traversed nodes marked as an anomaly. The report includes the specific location information of the anomaly nodes, such as file path, line number, and column number, helping developers accurately locate the problematic code. The system obtains the location information of the anomaly nodes using static analysis tools (such as Javaparser or ANTLR). This location information includes the path to the code file and the specific line and column numbers of the anomaly node. This information is formatted into an anomaly report and stored as a visual file or log entry for later use by developers.

[0126] Based on the exception report, a remedial suggestion is generated and provided to developers. It recommends adding a null check (`!= null`) before the exception node to ensure the code safely handles null objects during iteration. The remedial suggestion also includes specific code examples to guide developers on how to modify their code. The system automatically generates the remedial suggestion by analyzing the context of the exception node. The core of the suggestion is to ensure the safety of the iteration operation through a null check. A specific code example could be `if(object!= null){}`, placed before the iteration operation to ensure that the data object is validated before iteration.

[0127] After generating an anomaly reports and remediation suggestions, the system pushes this information to relevant developers via email or developer tools, reminding them to fix the anomalies. This notification method can be implemented through an Integrated Development Environment (IDE) or project management tools (such as JIRA). Reports can be sent to developers through the system's notification module. This can be achieved by sending reports via email or by integrating reports directly into code review tools, helping developers quickly receive issues and suggestions.

[0128] In the development environment, exception nodes are highlighted so developers can quickly identify problems while reviewing the code. This step provides visual cues in the IDE, making problematic code clearly visible and easier to fix. The system integrates with the developer's IDE (such as Eclipse or IntelliJ IDEA) to mark exception lines of code using highlighting. The system locates and highlights relevant code snippets based on the location information of the exception node.

[0129] If developers select the automatic fix feature, the system will automatically insert null checks (!= null) into the code according to the fix suggestions, ensuring a safety check is performed before any traversal operation. Simultaneously, the system will mark the inserted code so developers can track the fixes. Upon receiving the automatic fix instruction, the system automatically edits the source code, inserting the != null check before any abnormal traversal nodes. After insertion, the system marks the line number and modification history of the fix code for version control and subsequent code review.

[0130] In one specific implementation, upon detecting a traversal exception, the system generates a detailed exception report containing the file path, line number, and column number, and sends it to the developers via a plugin in the integrated development environment (such as IntelliJ IDEA). The report also provides suggestions for fixing null checks; developers can manually add `!= null` checks to their code. In the development environment, the exception line is automatically highlighted, allowing developers to click on it to view and fix the problem.

[0131] This embodiment helps developers quickly locate and fix traversal exceptions by generating exception reports and repair suggestions, reducing runtime errors caused by null pointer exceptions. By highlighting exception code and automatically inserting repair code, the workload for developers is greatly reduced, significantly improving code robustness and development efficiency.

[0132] In one embodiment, S10 includes:

[0133] S101: Extract the project source code folder from the project root directory, recursively traverse the subfolders in the project source code folder, and process each subfolder and the files contained in the subfolders layer by layer.

[0134] S102, during the traversal, filters out hidden files, non-code files, build folders and test folders based on file extensions, hidden attributes and code file types in the project;

[0135] S103, filter source code files with the .java extension and store the path of each filtered Java file in the Java file list;

[0136] S104 uses file path identifiers to separate processed file paths from unprocessed file paths, and records the processing status of each file during the traversal process, including whether the file has been processed, the file processing time, and the processing result.

[0137] In this embodiment, the entire project's source code folder is extracted from the project's root directory, and then this folder and its contained subfolders are recursively traversed. Recursive traversal is a common file system operation that processes files and subfolders level by level by traversing each level of the folder, ensuring that all files are accessed. Starting from the root directory, a recursive algorithm is used to traverse all subfolders via a file system API (such as Java's File class). Each time a subfolder is encountered, the system enters that folder and continues processing the files within it until all levels have been traversed.

[0138] While traversing folders, the system filters files, removing unnecessary files (such as hidden files, non-code files, build files, and test files) based on criteria like file extensions and hidden attributes. This aims to improve processing efficiency and ensure only source code files are processed. By checking file attributes (such as filename and extension) and folder names, the system excludes files or folders that do not meet the criteria. For file extensions and hidden attributes, filtering can be performed using API methods such as `isHidden()` and `getName().endsWith()`.

[0139] This process filters all files to identify Java files (with the .java extension) and stores their paths in a list for later use, such as code parsing. Each time a matching Java file is encountered, its full path is saved to a list. You can determine the file type using `file.getName().endsWith(".java")` and store the paths using an ArrayList or a similar data structure.

[0140] To avoid redundant file processing and ensure efficient traversal, the system uses file path identifiers to distinguish between processed and unprocessed files. The system also records the processing status of each file, including whether it has been processed, the processing time, and the processing result. Two lists can be created to store the paths of processed and unprocessed files, respectively. When processing each file, the system records its processing status, including the processing time (using a system timestamp) and the result (e.g., whether parsing was successful). This data can be stored in log files or a database for later analysis.

[0141] In one specific implementation, the system clones the project source code folder from the Git repository, recursively traverses each subfolder, and uses Java's File API to filter out hidden files, test files, and build files. The system uses regular expressions to filter out all files with the .java extension and stores their paths in an ArrayList. After processing each file, the system records its processing status, including whether it has been processed, the processing time, and the processing result, storing this status information in a local log file to avoid subsequent duplicate processing.

[0142] This embodiment recursively traverses the project source code folder and filters out Java files. This allows the system to efficiently process the source code of large projects, avoiding the processing of irrelevant files and folders. Using file path identifiers to record the status of processed and unprocessed files avoids repetitive operations, improves processing efficiency, and accurately records file processing time and results, which is helpful for subsequent code analysis and project management.

[0143] In one embodiment, S20 includes:

[0144] S201, perform lexical analysis on the Java file, read the source code in the Java file line by line, and divide the source code into lexical units, the lexical units including keywords, identifiers, operators and delimiters;

[0145] S202, Based on the lexical unit, the source code in the Java file is parsed sequentially using a syntax analyzer, and corresponding syntax nodes are generated according to the syntax structure of the Java language;

[0146] S203, construct an abstract syntax tree corresponding to the Java file based on the syntax nodes. The abstract syntax tree consists of multiple syntax nodes, each of which represents a syntax structure element in the Java file.

[0147] In this embodiment, lexical analysis is the first step in parsing the source code. It is responsible for segmenting the character sequences in the code into the smallest lexical units (tokens). These units represent basic elements in the code, such as keywords, identifiers, operators, and delimiters. Lexical analysis scans the source code, identifies different types of lexical units, and builds the foundation required for subsequent syntax analysis. The lexical analyzer reads the Java file content line by line, scans the code characters, and breaks them down into lexical units according to the lexical rules of the Java language. These lexical units can be automatically generated using regular expressions or built-in lexical analysis tools (such as Javaparser or ANTLR). Each lexical unit will be classified as a keyword, identifier, operator, etc.

[0148] Syntax analysis is performed based on the lexical units generated by lexical analysis. Following the syntax rules of the Java language, these units are combined to generate syntax nodes. Syntax nodes represent the logical structure of the code, such as expressions, control flow, and method calls. The system inputs the lexical units into the parser, which then constructs each node in the syntax tree step by step according to Java's syntax rules. The parser is responsible for checking whether the combination of these lexical units conforms to Java syntax, parsing the code structure, and generating syntax nodes representing these structures (such as expression nodes, statement nodes, etc.).

[0149] An Abstract Syntax Tree (AST) is the final result of syntax analysis. It represents the syntactic hierarchy of code using a tree structure. Each syntax node in the tree has its own parent and child nodes, reflecting the structure and logical order of the code. The AST is used for further code analysis and manipulation. The syntax nodes generated by the parser are organized into a tree structure one by one according to the logical order of the code. Each syntax node has a corresponding parent and child node, representing its hierarchical relationship in the code structure. After construction, the AST can be stored in memory for subsequent analysis.

[0150] In one specific implementation, the Javaparser tool is used to perform lexical analysis on the source code when parsing Java files. First, the system reads the Java file line by line, identifying all lexical units and classifying them into keywords, operators, identifiers, etc. Next, the Javaparser's syntax analysis function is used to generate syntax nodes according to the rules of the Java language. The generated syntax nodes are then organized into an Abstract Syntax Tree (AST) and stored as a tree structure for subsequent processing.

[0151] This embodiment generates an Abstract Syntax Tree (AST) through lexical and syntactic analysis of Java files, enabling the system to efficiently understand the syntactic structure of the code. The AST provides a logical representation of the code, which can be used for subsequent code optimization, static analysis, and error detection. Through this hierarchical parsing approach, the system can capture syntax errors and potential code problems before compilation, thereby improving code reliability and robustness.

[0152] In one embodiment, S201 above, performing lexical analysis on the Java file and reading the source code of the Java file line by line, includes:

[0153] S2011, Based on the size and historical processing time of the Java files in the Java file list, the Java files are grouped, and each group of Java files is assigned to an independent thread for processing;

[0154] S2012 assigns processing priority to each Java file based on its importance and modification time.

[0155] S2013, the assigned independent thread reads the source code of the Java files in the group line by line according to the processing priority.

[0156] In this embodiment, Java files are grouped for optimized processing by analyzing their size and historical processing time. File size affects processing complexity, while historical processing time reflects the efficiency of the previous processing. This step optimizes performance through grouping and reduces the burden on a single thread when processing large or complex files. The system first reads the metadata of the Java files, including file size and last processing time. An algorithm groups these files to ensure a balanced total processing load for each group. Then, an independent thread is allocated to each group, utilizing multi-threaded parallel processing technology to accelerate the lexical analysis of the Java files.

[0157] First, the system needs to obtain the basic attributes of each Java file, including file size and historical processing time:

[0158] File size: The file size in bytes can be obtained directly through system file APIs (such as File.length() in Java).

[0159] Historical processing time: Historical processing time refers to the time when a file was last modified or processed. The system can obtain the last modification time by calling `File.lastModified()` using the file's metadata. If the file is managed by a version control system (such as Git), the commit history of the file can be retrieved using Git commands.

[0160] The goal of grouping Java files by file size and historical processing time is to balance the processing load across groups while prioritizing important files. Specific strategies can be implemented based on file size, historical processing time, and predefined rules.

[0161] File size grouping: Files are divided into three categories: small, medium, and large based on their size. Different thresholds can be defined (e.g., less than 100KB for small files, 100KB to 1MB for medium files, and more than 1MB for large files) to ensure balanced distribution of files of different sizes during processing.

[0162] Processing large files consumes more resources and time. Therefore, grouping large files separately and assigning them to different threads during processing can prevent a single thread from slowing down the overall efficiency due to processing large files. Small files are processed relatively quickly and can be processed in batches and distributed to multiple threads to improve processing efficiency and resource utilization. By grouping files according to size, it is ensured that the load is balanced across each thread, preventing any single thread from consuming too many resources and causing a system performance bottleneck due to processing large files.

[0163] Historical processing time grouping: The historical processing time of a file affects its priority. Files that were most recently modified are placed in the priority group, while files last modified more recently are placed in the low priority group. For example, files modified within the last week belong to the "high priority group," while files modified more than a month ago belong to the "low priority group."

[0164] Recently modified files typically represent more active parts of the project or frequently updated modules. These files may be critical to the overall operation of the system and therefore require priority processing and inspection. Files that haven't been modified for a long time have usually undergone multiple verifications and may pose less risk. Assigning them a lower priority is reasonable because they have lower urgency and importance in the project. By grouping files by historical processing time, the newest and most important files that developers care about can be prioritized, ensuring that this code can be quickly detected and fixed at critical moments in the project.

[0165] During implementation, the system can group files by size by traversing a list of Java files:

[0166] Small filegroups: Store files smaller than 100KB.

[0167] Medium file group: Stores files with a size between 100KB and 1MB.

[0168] Large file group: Stores files larger than 1MB.

[0169] Files in each group will be evenly distributed among different processing threads. In this way, the system can process a large number of small files simultaneously, and can also process large files through independent threads, avoiding large files consuming too many resources.

[0170] The system first iterates through the file's metadata or version control information to obtain the historical processing time for each file:

[0171] High priority group: contains files that have been recently modified (e.g., within 1 week). These files may be core modules of the project and require priority processing.

[0172] Medium priority group: contains files modified between 1 week and 1 month ago.

[0173] Low priority group: contains files that were modified more than a month ago.

[0174] After grouping, the system assigns these files to different processing threads according to their priority, ensuring that recently modified important files are processed first.

[0175] The system can group files in a more granular way by combining file size and historical processing time.

[0176] For example:

[0177] High-priority large file group: Recently modified and large files that may have a significant impact on the project and should be processed first.

[0178] High-priority small file group: Files that have been recently modified but are small in size and can be processed quickly.

[0179] Low-priority large file group: Files that are old but large may not be the focus of the project.

[0180] Low-priority small file group: files that are old and small in size.

[0181] Grouping files by combining file size and historical processing time not only balances the load across threads but also ensures that critical modules in the project are prioritized. Grouping large files prevents resources from being concentrated on a single thread, while assigning higher priority to recently modified files improves project stability and maintainability. This combination allows the system to allocate different processing strategies based on the characteristics of each file. Large and high-priority files are processed independently, while small and low-priority files can be processed in batches. This approach maximizes the system's parallel processing capabilities and avoids processing bottlenecks.

[0182] The processing priority of each Java file depends on its importance within the project (e.g., core business module code) and its most recent modification time (the most recently modified files may require priority processing). This prioritizes files with a greater overall impact on the project, ensuring critical code is promptly reviewed and addressed. The system calculates the processing priority for each Java file based on its attributes (e.g., file location, importance tags, dependencies) and last modification time. Important and recently modified files are assigned higher priority, ensuring these files can enter the lexical analysis phase as quickly as possible.

[0183] Importance typically reflects a file's role in the project. For example, code files for core business logic, key algorithms, or main modules are clearly more important than auxiliary files (such as test files or utility classes). The following methods can be used to determine file importance:

[0184] File path: The location of a file can determine its importance. For example, a file located in the "src / main / " directory may be more important than a file located in the "test / " directory.

[0185] Project configuration: Projects sometimes have configuration files (such as pom.xml or build.gradle) that list the dependencies and criticality of certain modules or packages. The system can prioritize processing related code files based on these configurations.

[0186] Historical modification record: If a file is modified multiple times or frequently accessed by multiple developers, it can be inferred that the file is of high importance.

[0187] Tags or comments: In large projects, developers may mark certain files as key modules in code comments or project documentation. This information can be used as a reference.

[0188] Modification time is another important factor affecting processing priority. Recently modified files are generally more likely to contain potential errors or content that needs to be retested and checked. The modification time of a file can be obtained in the following ways:

[0189] File system metadata: The last modification time of a file can be obtained through operating system APIs (such as Java's File.lastModified()).

[0190] Version control systems: When using version control systems such as Git and SVN, these tools can be used to retrieve the modification history of files. For example, Git's `git log` command can provide a record of file modifications.

[0191] Processing priorities can be assigned based on the importance of the file and its modification time, using the following priority levels:

[0192] High priority: Core business files or recently modified files. For example, files last modified within the last week or files located in the main business logic module.

[0193] Medium priority: Functional files or files modified within the last 1-4 weeks. They are of high importance but not the most critical part of the project.

[0194] Low priority: Test files, utility files, or files that haven't been modified in a long time; these files have little impact on the project.

[0195] By reading the metadata of each Java file and analyzing its file path and modification time, the system can assign a weight to each file. For example, files that are important in both file importance and modification time have a high weight and can be marked as high priority.

[0196] After allocating a separate thread to each set of files, the threads read the Java file's source code line by line according to file priority and begin lexical analysis. By processing line by line, the system can effectively handle large files, avoiding memory overflows or excessively long processing times. Each independent thread reads the Java file line by line from beginning to end according to file priority, converting the code content into lexical units. The system processes file content through memory buffers or streaming methods, ensuring efficient parsing even for large files.

[0197] In another implementation, Java files are grouped based on their importance tags (such as code marked as a core business module) and modification history. The system assigns a separate thread to each group, reading the code according to priority, processing important files first. Each thread reads the file line by line, using a buffer to store the read data, and performs lexical analysis on the source code to generate a series of lexical units. The file size affects the grouping method, ensuring load balancing for each thread.

[0198] This embodiment improves file parsing efficiency and avoids performance bottlenecks associated with single-threaded processing by grouping Java files based on file size, modification time, and importance. Multi-threaded parallel processing ensures the system can handle multiple Java files simultaneously; this optimization strategy significantly reduces lexical analysis and overall parsing time, especially in large-scale projects.

[0199] The present invention also provides a code traversal exception detection device, referring to Figure 2 , Figure 2 This is a functional module diagram of a preferred embodiment of the code traversal anomaly detection device of the present invention. The code traversal anomaly detection device includes:

[0200] The file management and filtering module 10 is used to obtain the project source code folder and traverse the project source code folder, filter out Java files, and store them in the Java file list.

[0201] Code parsing module 20 is used to parse each Java file in the Java file list and generate a corresponding abstract syntax tree;

[0202] The traversal operation identification module 30 is used to find the StatementExpression node representing the expression operation in each abstract syntax tree and determine whether the name attribute of the StatementExpression node ends with forEach or begins with for.

[0203] Syntax tree traversal module 40 is used to confirm that the StatementExpression node is a traversal operation node if so, traverse the corresponding abstract syntax tree upwards, obtain all parent nodes of the traversal operation node, and generate a list of parent nodes.

[0204] The parent node analysis module 50 is used to traverse the list of parent nodes, determine whether the parent node contains a conditional judgment statement, and check whether the conditional judgment statement contains a null check operation on the data object.

[0205] The anomaly detection module 60 is used to confirm that there is a data object traversal anomaly in the corresponding StatementExpression node if the conditional statement does not contain a null check operation for the data object.

[0206] The specific implementation of the code traversal anomaly detection device of the present invention is basically the same as the embodiments of the above-described code traversal anomaly detection method, and will not be repeated here.

[0207] This invention also provides a code traversal exception detection device, such as... Figure 3 As shown, the code traversing the anomaly detection device may include: a processor 1001, such as a CPU; a communication bus 1002; a user interface 1003; a network interface 1004; and a memory 1005. The communication bus 1002 is used to implement communication between these components. The user interface 1003 may include a display screen or an input unit such as a keyboard; optionally, the user interface 1003 may also include a standard wired interface or a wireless interface. The network interface 1004 may optionally include a standard wired interface or a wireless interface (such as a Wi-Fi interface). The memory 1005 may be high-speed RAM or stable non-volatile memory, such as a disk drive. Optionally, the memory 1005 may also be a storage device independent of the aforementioned processor 1001.

[0208] Those skilled in the art will understand that Figure 3 The hardware structure of the code traversal exception detection device shown in the figure does not constitute a limitation on the code traversal exception detection device. It may include more or fewer components than shown, or combine certain components, or have different component arrangements.

[0209] like Figure 3As shown, the memory 1005, which serves as a storage medium, may include an operating system, a network communication module, a user interface module, and a code traversal exception detection program. The operating system is a program that manages and controls the code traversal exception detection device and software resources, supporting the operation of the network communication module, the user interface module, the code traversal exception detection program, and other programs or software. The network communication module manages and controls the network interface 1004; the user interface module manages and controls the user interface 1003.

[0210] exist Figure 3 In the hardware structure of the code traversal anomaly detection device shown, the network interface 1004 is mainly used to connect to the backend server and communicate data with the backend server; the user interface 1003 is mainly used to connect to the client and communicate data with the client; the processor 1001 can call the code traversal anomaly detection program stored in the memory 1005 and perform the same operation as the code traversal anomaly detection method.

[0211] The specific implementation of the code traversal anomaly detection device of the present invention is basically the same as the various embodiments of the code traversal anomaly detection method described above, and will not be repeated here.

[0212] Furthermore, this embodiment of the invention also proposes a computer storage medium storing a code traversal exception detection program, which, when executed by a processor, implements the steps of the code traversal exception detection method described above.

[0213] The specific implementation of the computer storage medium of the present invention is basically the same as the embodiments of the above-described code traversal anomaly detection method, and will not be repeated here.

[0214] It should be noted that if any software tools or components not belonging to our company appear in the embodiments of this application, they are merely for illustrative purposes and do not represent actual use.

Claims

1. A method of code traversal anomaly detection, characterized by, The method comprises the following steps: Obtaining a project source code folder and traversing the project source code folder to screen out java files and store the java files into a java file list; Parsing each java file in the java file list to generate a corresponding abstract syntax tree; Finding a StatementExpression node representing an expression operation in each abstract syntax tree, and judging whether a name attribute of the StatementExpression node ends with forEach or starts with for; If yes, confirming that the StatementExpression node is a traversal operation node, marking position information of the traversal operation node, recording a file name, a line number and a column number of the traversal operation node for positioning an abnormal code position; Recording an association relationship between the traversal operation node and a direct parent node, and establishing a hierarchical relationship of the traversal operation node in a context syntax structure; Using the hierarchical relationship, recursively finding all parent nodes of the traversal operation node upwards in the corresponding abstract syntax tree, and marking a syntax type of each parent node, the syntax type being used for identifying a conditional judgment statement; Storing each parent node into a parent node list according to a syntax structure to generate a hierarchical parent node path; Traversing the parent node list, starting from a first node of the parent node list, and processing each parent node in turn; Judging a syntax type of each parent node to identify whether it is a conditional judgment statement, the conditional judgment statement including an if statement, an else if statement and a switch statement; Analyzing the identified conditional judgment statement to check whether a condition judgment expression contains a null judgment check of!=null of a data object in the traversal operation; If any conditional judgment statement does not contain the null judgment check, marking the corresponding traversal operation node as an abnormal node; If the conditional judgment statement does not contain the null judgment check of the data object, confirming that the corresponding StatementExpression node has a data object traversal exception, and generating an exception report.

2. The code traversal anomaly detection method of claim 1, wherein, Generating the exception report, including: Generating the exception report and listing the marked StatementExpression node as an abnormal node, the exception report including a file path, a line number and a column number of the abnormal node; Generating a repair suggestion based on the exception report, the repair suggestion including a code example of adding a!=null null judgment operation before the abnormal node; Sending the exception report and the repair suggestion to a developer to inform the developer of a problem to be handled; Marking the abnormal node in a development environment in a highlighted manner to help the developer locate a problem code; When receiving an automatic repair instruction, inserting a null judgment check code before the abnormal node according to the repair suggestion, and marking the inserted code.

3. The code traversal anomaly detection method as recited in claim 1, wherein, Obtaining a project source code folder and traversing the project source code folder to screen out java files and store the java files into a java file list, including: Extracting a project source folder from a project root directory, recursively traversing subfolders in the project source folder, and processing each subfolder and files contained in the subfolder layer by layer; In the traversal process, according to the file extension, hidden attribute and code file type in the project, filtering out hidden files, non-code files, build folders and test folders; Filtering source code files with.java extension, and storing each filtered java file path into a java file list; Using a file path identifier, separating the processed file paths from the unprocessed file paths, and recording the processing status of each file in the traversal process, including whether the file has been processed, file processing time and processing result.

4. The code traversal anomaly detection method of claim 1, wherein, Parsing each java file in the java file list to generate a corresponding abstract syntax tree, including: Performing lexical analysis on the java file, reading the source code in the java file line by line, and dividing the source code into lexical units, including keywords, identifiers, operators and separators; Based on the lexical units, using a syntax analyzer to sequentially analyze the source code in the java file, and generating corresponding syntax nodes according to the syntax structure of the java language; Based on the syntax nodes, constructing an abstract syntax tree corresponding to the java file, the abstract syntax tree is composed of multiple syntax nodes, each syntax node represents a syntax structure element in the java file.

5. The code traversal anomaly detection method of claim 4, wherein, Performing lexical analysis on the java file, reading the source code in the java file line by line, including: Grouping java files based on the size and historical processing time of the java files in the java file list, and assigning each group of java files to an independent thread for processing; Assigning a processing priority to each java file based on the importance and modification time of the java file; The independent thread after assignment reads the source code of the java file in the group line by line according to the processing priority.

6. A code traversal anomaly detection apparatus, characterized by, The code traversal exception detection device comprises: A file management and screening module for obtaining a project source folder and traversing the project source folder, screening out java files and storing them into a java file list; A code analysis module for parsing each java file in the java file list to generate a corresponding abstract syntax tree; A traversal operation identification module for finding a StatementExpression node representing an expression operation in each abstract syntax tree, and judging whether the name attribute of the StatementExpression node ends with forEach or starts with for. The syntax tree traversal module is configured to, if the StatementExpression node is confirmed as a traversal operation node, mark the position information of the traversal operation node, record the file name, line number and column number of the traversal operation node, and locate the abnormal code position; record the association relationship between the traversal operation node and the direct parent node, establish the hierarchical relationship of the traversal operation node in the context syntax structure; utilize the hierarchical relationship to recursively search for all parent nodes of the traversal operation node upwards in the corresponding abstract syntax tree, and mark the syntax type of each parent node, the syntax type being used to identify the conditional judgment statement; and store each parent node in the parent node list according to the syntax structure, and generate a hierarchical parent node path. The parent node analysis module is configured to traverse the parent node list, and process each parent node in turn from the first node of the parent node list; judge the syntax type of each parent node, identify whether it is a conditional judgment statement, the conditional judgment statement including an if statement, an else if statement and a switch statement; analyze the identified conditional judgment statement, check whether the!=null null judgment of the data object in the traversal operation is contained in the conditional judgment expression; and if any one of the conditional judgment statements does not contain the null judgment operation, mark the corresponding traversal operation node as an abnormal node. The abnormal detection module is configured to, if the!=null null judgment of the data object is not contained in the conditional judgment statement, confirm that the corresponding StatementExpression node has the data object traversal abnormality.

7. A code traversal anomaly detection device, characterized by, The code traversal abnormality detection device includes a memory, a processor and a code traversal abnormality detection program stored on the memory and executable on the processor, and the code traversal abnormality detection program is executed by the processor to implement the steps of the code traversal abnormality detection method in any one of claims 1-5.

8. A computer storage medium, characterized in that, The storage medium stores a code traversal abnormality detection program, and the code traversal abnormality detection program is executed by the processor to implement the steps of the code traversal abnormality detection method in any one of claims 1-5.

Citation Information

Patent Citations

  • Java null pointer reference detection method and system based on data flow propagation analysis

    CN114595148A

  • Empty judgment detection method and device, terminal equipment and storage medium

    CN118445198A