Method for semi-automated refactoring of software projects based on dependency tree construction and ai assistance

By constructing a dependency tree and combining it with artificial intelligence analysis, the dependencies of software projects are automatically parsed and graphically presented, solving the problems of difficult architectural understanding and low efficiency in the refactoring of outdated projects, and realizing an efficient and low-risk refactoring process.

CN122111411APending Publication Date: 2026-05-29SHENGWEI DIGITAL (SHENZHEN) TECHNOLOGY CO LTD

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
SHENGWEI DIGITAL (SHENZHEN) TECHNOLOGY CO LTD
Filing Date
2026-02-24
Publication Date
2026-05-29

AI Technical Summary

Technical Problem

Existing technologies face challenges in maintaining and refactoring legacy software projects, including difficulties in understanding the architecture, the inability to intuitively represent dependencies, low analysis efficiency, a lack of intelligent assistance, and insufficient adaptability to large-scale projects. These issues result in high costs and risks for refactoring efforts.

Method used

By constructing a dependency tree and combining it with artificial intelligence analysis, the system automatically resolves the dependencies between project files, generates a graphical dependency tree structure, supports interactive operation, identifies circular dependencies and design smells, and provides refactoring suggestions, combined with manual verification to reduce risks.

Benefits of technology

It improves the efficiency of understanding outdated project architectures, reduces the manpower costs and risks of refactoring, enhances the adaptability to large-scale projects, and provides reliable refactoring suggestions.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122111411A_ABST
    Figure CN122111411A_ABST
Patent Text Reader

Abstract

The application discloses a software project semi-automatic reconstruction method based on a dependency tree construction and artificial intelligence assistance, receives a software project root directory and automatically determines a construction root file; parses the construction root file to identify an executable file and a source file list thereof, and determines a program entry file; scans a project directory to construct a file tree data structure; parses a header file from the program entry file, recursively constructs a dependency tree based on an analyzed set; performs interactive graphical display on the dependency tree, and performs layout, color coding and dependency direction identification according to node levels and the number of child nodes; calls an artificial intelligence model to generate summary annotations for leaf node files of the dependency tree and recursively aggregates from bottom to top to form a project summary; performs cyclic dependency detection on the dependency relationship and identifies design bad smells, generates reconstruction suggestions based on analysis results, and presents the reconstruction suggestions on a graphical interface; and receives user confirmation and / or adjustment to output final reconstruction suggestion results.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the fields of software engineering and program analysis technology, specifically to a semi-automated refactoring method for software projects based on dependency tree construction and AI assistance. Background Technology

[0002] In the field of software engineering, the maintenance and refactoring of outdated (heavy) projects is a long-standing core technical challenge throughout the entire lifecycle of a software project. Such projects often suffer from incomplete or poorly documented information due to long development cycles and frequent personnel changes, leading to unclear project architecture and chaotic dependencies, which significantly hinders subsequent maintenance, iteration, and refactoring efforts.

[0003] To understand the architecture of legacy projects and drive their refactoring, existing technologies primarily employ the following three types of solutions: 1. Manual code reading method: Programmers directly browse the project's header files (such as .h files) and implementation files (such as .cpp files) through the file system and text editor, analyzing the #include directives line by line to infer the dependencies between files. This method relies entirely on the programmer's personal experience, professional skills, and memory, requiring a significant time investment and being highly susceptible to overlooking critical dependencies due to human error, resulting in overall low efficiency. 2. System Analysis Methods: Analysis is conducted using dependency information generated by build tools such as CMake and Makefile. For example, the project structure, executable file, and library dependency definitions can be obtained by parsing the CMakeLists.txt file, or code comments can be extracted using tools like Doxygen. However, the output of these tools is mostly in text format (such as the compilation rules and dependency lists in Makefiles), containing a large amount of redundant build-irrelevant information, requiring programmers to manually filter valid dependencies. Furthermore, commenting tools like Doxygen can only extract function-level comments and cannot intuitively present the overall architecture hierarchy of the project. 3. Basic visualization tools: Some tools (such as Graphviz) can convert text-based dependency descriptions into simple graphs, but such graphs have inherent defects: the layout is static and fixed, and interactive operations (such as zooming, selection, and node positioning) are not supported; intelligent annotation functions are lacking, which cannot help programmers understand the functions of the file; and input parameters need to be manually configured, and artificial intelligence-assisted analysis capabilities are not integrated, making it difficult to adapt to the architectural analysis needs of complex projects.

[0004] In summary, the core limitation of existing technologies lies in the lack of an integrated solution that combines automation, graphical representation, and intelligence, specifically exhibiting the following significant shortcomings: Non-intuitive: Dependencies are presented in text form, with low information density. They cannot be identified using graphical elements such as color coding and hierarchical layout. Complex relationships such as circular dependencies and cross-branch dependencies are difficult to detect. Programmers need to subjectively reconstruct the architecture, which is prone to errors and time-consuming. Inefficient: From dependency filtering and architecture analysis to comment writing, the entire process relies on manual operation. It takes several days or even weeks to understand the architecture of a medium-sized project. The redundant information in the text files generated by CMake further increases the burden of manual filtering. Lack of intelligent assistance: It does not integrate artificial intelligence technology, and cannot automatically generate code comments, project summaries and architecture optimization suggestions. The identification and judgment of refactoring points rely entirely on the programmer's experience, which easily leads to the omission of "code smells" such as "excessive inheritance" and "God objects" as well as hidden logic bugs. Poor adaptability: Text-based tools experience performance degradation and slow response when handling large projects containing thousands of files; visualization tools lack optimized layout algorithms, and when nodes are dense, graphics are prone to overlap and chaos, making it impossible to clearly display the architectural hierarchy. Weak Refactoring Support: Existing technologies can only go as far as basic dependency analysis and have not formed a complete refactoring support system. They cannot automatically generate targeted refactoring suggestions, and there is a lack of data-driven and systematic decision-making basis when manual refactoring is involved.

[0005] The aforementioned shortcomings directly lead to a "high-cost, high-risk" dilemma in refactoring old projects: most programmers shy away from refactoring old projects, opting instead to add independent code to the existing architecture. With personnel changes and feature iterations, the project architecture becomes increasingly chaotic, "code smells" accumulate, and ultimately, a vicious cycle of "difficult maintenance and more bugs appearing with each fix" occurs, severely impacting the software project's lifecycle and iteration efficiency. Therefore, the industry urgently needs an integrated solution that can automatically parse the architecture, intuitively display dependencies, and intelligently provide refactoring suggestions to overcome the technical bottlenecks in refactoring old projects. Summary of the Invention

[0006] The purpose of this invention is to overcome the problems of existing technologies in the maintenance and refactoring of outdated (heavy) software projects, such as difficulties in understanding the architecture, difficulty in intuitively presenting dependencies, low analysis efficiency, lack of intelligent assistance, and insufficient adaptability to large projects. This invention provides a semi-automated refactoring method for software projects based on dependency tree construction and AI assistance. This invention automatically constructs a dependency tree structure reflecting the dependencies between project files by parsing project build information and combining it with source code inclusion relationships. An interactive visual layout mechanism presents dependencies in a scalable, locatable, and filterable graphical format, helping users quickly grasp the overall project architecture and key dependencies. Simultaneously, AI-assisted analysis is introduced to generate annotations for key or leaf node files and aggregate them hierarchically to form a module / project overview. Combined with circular dependency detection and architectural problem identification, refactoring suggestions are generated. The end-to-end analysis-suggestion process retains manual intervention and verification steps, thereby reducing the human cost and risk of refactoring while ensuring feasibility and controllability, and improving the systematicness and efficiency of refactoring decisions.

[0007] To achieve the above objectives, the technical solution adopted by this invention is: a semi-automatic refactoring method for software projects based on dependency tree construction and AI assistance, comprising the following steps: S1. Receive the root directory path of the software project, automatically detect and determine the root file to build; S2. Parse the root file of the build, identify at least one executable file in the software project, and extract the corresponding source file list for each executable file; S3. For each executable file, determine its program entry file based on build information or file naming conventions; S4. Scan the software project directory, register project file information, and build an internal file tree data structure, where tree nodes represent files and tree edges represent the file's hierarchical relationship in the directory hierarchy; S5. Starting from the program entry file, parse the header file inclusion information, distinguish between user header files and system / third-party header files, and perform subsequent dependency analysis only on user header files; S6. Construct a dependency tree with the program entry file as the root node: register the user header files contained in the program entry file as child nodes, and recursively parse the header file inclusion relationships of each child node to add new child nodes; during the recursion process, deduplication is performed based on the analyzed set, and the recursion is stopped when the preset recursion termination condition is met; S7. Interactively draw and display the dependency tree: Arrange the nodes according to the node hierarchy and the number of child nodes, color-code the nodes, and use arrowed edges to indicate the dependency direction; S8. Connect to the AI ​​model interface, automatically analyze the leaf node files of the dependency tree to generate summary annotations, and recursively aggregate the summary annotations from the leaf nodes upwards to the root node to form a project overview. S9. Perform architecture analysis: Detect circular dependencies and identify design smells; S10. Generate refactoring suggestions based on the architecture analysis results, present the refactoring suggestions in the graphical interface, receive user confirmation, filtering and / or manual adjustment instructions for the refactoring suggestions, and output the final refactoring suggestion results based on the instructions.

[0008] Furthermore, step S1 includes: detecting the CMakeLists.txt file in the root directory as the build root file, and adapting the parsing of the corresponding build file when the software project uses other build systems; step S2 includes: matching and parsing the content in the build root file used to define executable files and their source file sets to obtain a list of source files corresponding to each executable file, and the matching and parsing includes using regular expressions to match key instructions in the build root file; step S3 includes: determining the program entry file based on the parsing information of the build root file, and / or automatically identifying the entry file based on file naming conventions.

[0009] Furthermore, in step S4, the node attributes of the internal file tree data structure include at least the file name, file path, and file type, and the file type includes at least the header file and the implementation file; and / or the internal file tree data structure is stored using an adjacency list or a tree object.

[0010] Furthermore, in step S5, distinguishing between user header files and system / third-party header files includes: using regular expressions or equivalent matching rules to distinguish between double quote inclusion and angle bracket inclusion, and skipping the angle bracket inclusion instructions corresponding to system / third-party header files, retaining only the double quote inclusion instructions corresponding to user header files for dependency analysis.

[0011] Furthermore, step S6 includes: taking the program entry file as the root node, registering the user header files contained in the program entry file as child nodes; and during the recursive parsing process, when the file corresponding to the child node to be parsed is not in the analyzed set, parsing the user header file inclusion relationship of the file and adding a new child node, while adding the file to the analyzed set; when the file corresponding to the child node to be parsed is already in the analyzed set, stopping the recursive parsing of the child node; wherein the preset recursive termination condition includes: the file corresponding to the current node does not have a user header file inclusion relationship, and / or the file corresponding to the current node already exists in the analyzed set.

[0012] Furthermore, the interactive graphical drawing and display in step S7 includes: presenting the dependency tree through a graphical interface and supporting interactive operations such as scaling, dragging, selection, and / or node positioning; initializing the graphical scene and setting the interaction mode; establishing a node data model and parsing the node hierarchy to determine the number of root nodes, leaf nodes, and child nodes; determining the initial position of nodes based on the tree layout and iteratively optimizing the node position through force-directed layout; rendering node graphics and dependency edges in real time and drawing arrows at the endpoints of dependency edges; distinguishing and displaying root nodes, intermediate nodes, and leaf nodes; and displaying statistical information related to the number of child nodes at the nodes.

[0013] Furthermore, step S8 includes: using the code text corresponding to the leaf node as input to call the AI ​​model interface to output a summary annotation in natural language form; and summarizing and generalizing the annotations of the parent nodes from the leaf nodes upwards, aggregating them level by level until the root node to form a project overview; wherein the automatic analysis through the AI ​​model interface includes: initializing the model call configuration and establishing a log; verifying and reading the input file; preprocessing the code text; extracting semantic and structural features; calling the core analysis interface to generate analysis results; generating a structured report; formatting the structured report and outputting it as readable text; and cleaning up resources and returning the results.

[0014] Furthermore, the circular dependency detection in step S9 includes: treating the dependency relationship corresponding to the dependency tree as a directed graph and performing cycle detection to identify circular dependencies; wherein the cycle detection uses depth-first search to detect strongly connected components, and / or uses an equivalent cycle detection method to identify circular dependencies.

[0015] Furthermore, the design odor identification in step S9 includes at least identifying excessively deep inheritance and God objects, using heuristic rules and / or machine learning models.

[0016] Furthermore, the refactoring suggestions in step S10 include at least: providing suggestions for interface extraction or dependency decoupling for circular dependencies, providing suggestions for module merging for redundant structures, providing code similarity analysis results to assist in refactoring decisions, and / or providing hints of potential logical problems based on AI analysis; and presenting the refactoring suggestions in a graphical interface, receiving user confirmation, filtering and / or manual adjustment of the refactoring suggestions, outputting the final refactoring suggestion results based on the adjustment results and / or performing refactoring processing.

[0017] By adopting the above technical solution, the present invention has at least the following beneficial effects: By automatically parsing and building root files, identifying executable files and program entry files, the analysis scope and key entry points of a project can be quickly determined, reducing the workload of manually sorting out the project structure and improving the efficiency of understanding outdated project architectures.

[0018] By constructing a dependency tree and presenting it graphically, combined with node hierarchy layout, color coding, and dependency edges with arrows, the dependencies between files can be made more intuitive; it also supports interactive operations such as zooming, dragging, selection, and node positioning, making it easy to locate and analyze dependencies in complex scenarios.

[0019] By distinguishing between user header files and system / third-party header files, dependency analysis is performed only on user header files, which helps to focus on the true dependencies within the project. Combined with deduplication of the analyzed set and control of recursive termination conditions, the stability and processing efficiency of dependency analysis are improved, and the adaptability to projects of different sizes is enhanced.

[0020] By integrating an artificial intelligence model to generate summary annotations for dependent leaf node files and recursively aggregating them from bottom to top to form a project overview, project description information can be supplemented when documents are missing or have low reference value, providing reusable textual support for project handover, maintenance and reconstruction.

[0021] By performing circular dependency detection on dependencies and identifying design smells such as excessively deep inheritance and God objects, structural problems affecting maintainability can be discovered in advance. Furthermore, refactoring suggestions such as interface extraction / dependency decoupling, module merging, similarity analysis, and potential logical problem hints can be generated to provide a basis for refactoring decisions and reduce refactoring risks.

[0022] By presenting refactoring suggestions through a graphical interface and receiving user confirmation, filtering, or adjustment instructions before outputting the final result, the analysis and suggestion generation process is automated while retaining necessary manual verification and control, making it suitable for software project refactoring scenarios of varying complexity. Attached Figure Description

[0023] To more clearly illustrate the technical solutions in the embodiments of the present invention or the prior art, the drawings used in the description of the embodiments or the prior art will be briefly introduced below. Obviously, the drawings described below are only some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0024] Figure 1 This is a flowchart of the semi-automated refactoring method for software projects according to the present invention; Figure 2 This is a diagram of the code file dependency architecture before the reconstruction of this invention; Figure 3 This is a well-reconstructed tree structure diagram of the present invention. Detailed Implementation

[0025] Exemplary embodiments will now be described in detail, examples of which are illustrated in the accompanying drawings. When the following description relates to the drawings, unless otherwise indicated, the same numerals in different drawings denote the same or similar elements. The embodiments described in the following exemplary embodiments do not represent all embodiments consistent with the present invention. Rather, they are merely examples of apparatuses and methods consistent with some aspects of the invention as detailed in the appended claims.

[0026] Example 1 like Figure 1 As shown, this embodiment provides a semi-automated refactoring method for software projects based on dependency tree construction and AI assistance, including the following steps: S1. Receive the root directory path of the software project, automatically detect and determine the root file to build; S2. Parse the root file of the build, identify at least one executable file in the software project, and extract the corresponding source file list for each executable file; S3. For each executable file, determine its program entry file based on build information or file naming conventions; S4. Scan the software project directory, register project file information, and build an internal file tree data structure, where tree nodes represent files and tree edges represent the file's hierarchical relationship in the directory hierarchy; S5. Starting from the program entry file, parse the header file inclusion information, distinguish between user header files and system / third-party header files, and perform subsequent dependency analysis only on user header files; S6. Construct a dependency tree with the program entry file as the root node: register the user header files contained in the program entry file as child nodes, and recursively parse the header file inclusion relationships of each child node to add new child nodes; during the recursion process, deduplication is performed based on the analyzed set, and the recursion is stopped when the preset recursion termination condition is met; S7. Interactively draw and display the dependency tree: Arrange the nodes according to the node hierarchy and the number of child nodes, color-code the nodes, and use arrowed edges to indicate the dependency direction; S8. Connect to the AI ​​model interface, automatically analyze the leaf node files of the dependency tree to generate summary annotations, and recursively aggregate the summary annotations from the leaf nodes upwards to the root node to form a project overview. S9. Perform architecture analysis: Detect circular dependencies and identify design smells; S10. Generate refactoring suggestions based on the architecture analysis results, present the refactoring suggestions in the graphical interface, receive user confirmation, filtering and / or manual adjustment instructions for the refactoring suggestions, and output the final refactoring suggestion results based on the instructions.

[0027] As one implementation, step S1 in this embodiment includes: detecting the CMakeLists.txt file in the root directory as the build root file, and adapting the parsing of the corresponding build file when the software project uses other build systems; step S2 includes: matching and parsing the content in the build root file used to define executable files and their source file sets to obtain a list of source files corresponding to each executable file, and the matching and parsing includes using regular expressions to match key instructions in the build root file; step S3 includes: determining the program entry file based on the parsing information of the build root file, and / or automatically identifying the entry file based on file naming conventions. In this embodiment, the "key instructions" may include instructions used to define executable files and their dependencies, such as add_executable and target_link_libraries, thereby enabling the extraction of the source file sets of each executable file in a multi-executable scenario, providing a clear analysis boundary for subsequent dependency tree construction.

[0028] In addition, if the project uses other build systems (such as Makefile), adaptation and parsing can be performed while keeping the overall process unchanged, but CMake is the preferred implementation for more stable location of executable files and entry files.

[0029] As one implementation method, in this embodiment, the node attributes of the internal file tree data structure in step S4 include at least filename, file path, and file type, where the file type includes at least header files and implementation files; and / or the internal file tree data structure is stored using an adjacency list or a tree object. By establishing the internal file tree data structure, file paths and types can be quickly located in subsequent dependency extraction and recursive analysis, thereby reducing the overhead of repeated directory scanning and improving the processing efficiency and stability under large-scale project file sets.

[0030] As one implementation method, step S5 in this embodiment, distinguishing between user header files and system / third-party header files, includes: using regular expressions or equivalent matching rules to distinguish between double-quoted inclusion forms and angle bracket inclusion forms, and skipping the angle bracket inclusion instructions corresponding to system / third-party header files, retaining only the double-quoted inclusion instructions corresponding to user header files for dependency analysis. In this embodiment, the regular expression can set matching modes for double-quoted inclusion forms and angle bracket inclusion forms respectively to distinguish between local header files and system header files; by skipping system / third-party header files, irrelevant dependencies can be avoided from interfering with the analysis results, making the dependency tree more focused on the real dependency relationships within the project, facilitating subsequent visualization and refactoring decisions.

[0031] As one implementation method, step S6 in this embodiment includes: taking the program entry file as the root node, registering the user header files contained in the program entry file as child nodes; and during the recursive parsing process, when the file corresponding to the child node to be parsed is not in the analyzed set, parsing the user header file inclusion relationship of the file and adding a new child node, while adding the file to the analyzed set; when the file corresponding to the child node to be parsed is already in the analyzed set, stopping the recursive parsing of the child node; wherein the preset recursion termination condition includes: the file corresponding to the current node does not have a user header file inclusion relationship, and / or the file corresponding to the current node already exists in the analyzed set. In this embodiment, the dependency tree construction can be implemented iteratively using an explicit stack or queue: pushing the entry file onto the stack, and cyclically popping the files to be processed; if the file is already in the analyzed set, skipping it; otherwise, adding it to the analyzed set and parsing its user header file inclusion relationship, adding the newly discovered user header files as child nodes to the dependency tree, and pushing the files corresponding to the unanalyzed child nodes onto the stack, thereby ensuring deduplication while achieving controllable recursive expansion and avoiding repeated parsing or even infinite recursion.

[0032] The deduplication and termination controls described above enable the stable construction of dependency trees in projects with a large number of files and complex dependencies (such as loops or cross-references), thereby improving overall processing efficiency.

[0033] As one implementation method, the interactive graphics drawing and display in step S7 of this embodiment includes: presenting the dependency tree through a graphical interface and supporting interactive operations such as scaling, dragging, selection, and / or node positioning; initializing the graphics scene and setting the interaction mode; establishing a node data model and parsing the node hierarchy to determine the number of root nodes, leaf nodes, and child nodes; determining the initial position of nodes based on the tree layout and iteratively optimizing the node position through force-directed layout; rendering node graphics and dependency edges in real time and drawing arrows at the endpoints of dependency edges; distinguishing and displaying root nodes, intermediate nodes, and leaf nodes; and displaying statistical information related to the number of child nodes at the nodes. In this embodiment, the Qt graphics framework can be used to implement interactive drawing, for example, using QGraphicsView as the main view and QGraphicsScene as the graphics container, and configuring interactive modes such as rectangular selection; nodes and edges can be drawn as graphic items, and the root nodes, intermediate nodes, and leaf nodes are color-coded during the drawing process to enhance readability.

[0034] In terms of layout, an initial tree layout can be given first based on hierarchical relationships, and then the node positions can be updated iteratively through a force-directed model to reduce node overlap and improve the overall aesthetics and recognizability of the architecture diagram. The direction of dependency is clearly indicated by the edges with arrows, and statistical information such as the number of child nodes is displayed at the nodes to facilitate the rapid identification of densely dependent areas and key modules.

[0035] Through the interactive visualization presented above, the problem of traditional text dependency lists being difficult to understand intuitively can be transformed into visualized structured information, improving the efficiency of locating complex dependencies (such as circular dependencies and cross-layer dependencies).

[0036] As one implementation method, step S8 in this embodiment includes: using the code text corresponding to the leaf node as input to call the AI ​​model interface to output a natural language summary annotation; summarizing and generalizing the annotations of the parent nodes from the leaf nodes upwards, aggregating level by level until the root node to form a project overview; wherein the automatic analysis through the AI ​​model interface includes: initializing the model call configuration and establishing a log; verifying and reading the input file; preprocessing the code text; extracting semantic and structural features; calling the core analysis interface to generate analysis results; generating a structured report; formatting the structured report and outputting it as readable text; and cleaning up resources and returning the results. In this embodiment, the AI ​​model can be DeepSeek, OpenAI, or other models; the AI ​​model input is code text, and the output is natural language annotation. Through recursive aggregation from the leaf nodes upwards, a structured overview can be formed layer by layer at the module level, subsystem level, and even project level, thereby supplementing project description information when project documents are missing or have low reference value, and providing reusable text support for handover and maintenance.

[0037] As one implementation method, the structured report described in this embodiment can organize key points in, for example, JSON format, and can be converted into a readable report format such as Markdown, so as to be output in conjunction with the visual architecture diagram, thereby improving the efficiency of understanding and review.

[0038] As one implementation method, the circular dependency detection in step S9 of this embodiment includes: treating the dependency relationship corresponding to the dependency tree as a directed graph and performing cycle detection to identify the circular dependency relationship; wherein the cycle detection adopts depth-first search to detect strongly connected components, and / or adopts an equivalent cycle detection method to identify the circular dependency relationship.

[0039] As one implementation method, the design smell identification in step S9 of this embodiment includes at least identifying excessively deep inheritance and God objects, and the identification method is heuristic rules and / or machine learning models. In this embodiment, the dependency relationship can be abstracted as a directed graph G=(V,E), where V is the set of file nodes and E is the set of containment edges; cyclic dependencies correspond to cycles in the graph, and the set of cyclic dependencies can be obtained by identifying strongly connected components through methods such as DFS, thereby providing input for subsequent dependency decoupling suggestions.

[0040] Bad smell identification can be combined with heuristic rules or machine learning models to provide hints about typical problems, such as identifying excessive inheritance and God objects, thereby exposing structural risk points that affect maintainability in advance.

[0041] As one implementation method, the refactoring suggestions in step S10 of this embodiment include at least: providing suggestions for interface extraction or dependency decoupling for circular dependencies, providing suggestions for module merging for redundant structures, providing code similarity analysis results to assist in refactoring decisions, and / or providing hints of potential logical problems based on AI analysis; and presenting the refactoring suggestions in a graphical interface, receiving user confirmation, filtering and / or manual adjustment of the refactoring suggestions, outputting the final refactoring suggestion results based on the adjustment results and / or performing refactoring processing.

[0042] By aggregating the results of circular dependency detection, off-odor identification, and AI analysis to generate reconstruction suggestions, a closed-loop process of problem localization, suggestion output, and manual confirmation can be formed. The graphical interface is used to present the suggestions and conduct interactive confirmation, which enables the suggestion output to be automated while retaining the necessary manual verification, thereby reducing the risk of direct changes to heavy projects.

[0043] Through the process described in Implementation Example 1, on the one hand, a code file dependency architecture diagram starting from the program entry file can be output, visually presenting the dependency logic between files; on the other hand, comments can be automatically generated for leaf node files and recursively aggregated to form a project overview, thereby supplementing structured explanations in scenarios where documentation is missing; at the same time, key issues are located through circular dependency detection and bad smell identification, and refactoring suggestions such as interface extraction / dependency decoupling, module merging, similarity analysis, and potential logical problem prompts are output. Finally, after confirmation and adjustment in the graphical interface, the refactoring suggestion results are output, making the overall solution both efficient and controllable.

[0044] Example 2 This embodiment provides a semi-automated refactoring method for software projects based on dependency tree construction and AI assistance. The specific steps are as follows: Step 1: Enter the project root directory The system receives the project root directory path input by the user and automatically detects the CMakeLists.txt file in the root directory as the entry point. If the project uses other build systems (such as Makefile), it can be adapted for parsing, but CMake is the preferred implementation.

[0045] Step 2: Analyze the CMakeLists.txt file Parse CMake syntax to identify all executable files (exe) in the project. For each executable file, extract its corresponding list of source files. The CMake parsing algorithm uses regular expressions to match key instructions such as `add_executable` and `target_link_libraries`. Mathematically, the set of executable files can be represented as:

[0046] Each of them For each executable file, its source file set is:

[0047] Step 3: Determine the program entry file For each executable file, locate its program entry file (usually main.cpp or similar). This is automatically identified via CMake information or file naming conventions.

[0048] Step 4: Construct the file tree data structure The system scans the project directory, registers all filenames, and constructs an internal file tree data structure. Tree nodes represent files, and edges represent inclusion relationships. The data structure uses an adjacency list or tree object for storage, and node attributes include filename, path, and type (header file / implementation file).

[0049] Step 5: Parse the entry file and header file inclusions Starting with the entry file, its header file inclusion section is parsed. Only user header files (such as #include "xxx.h") are analyzed, skipping system or third-party header files (such as #include...). <qdebug>Regular expressions are used to distinguish between local and system header files. - Local header file mode: #include\s*\"([^\"]+)\" - System header file mode: #include\s*<([^>]+)> Step 6: Build the dependency tree Using the entry file as the root node, register the included user header files as child nodes. Recursively analyze each child node: if a child node has not been analyzed (not in the array of analyzed filenames), parse its header file inclusions and add a new child node; otherwise, stop the recursion. The recursion terminates when: - The node has no user header file inclusion.

[0050] - The node already exists in the analyzed set.

[0051] Dependency tree construction algorithm pseudocode: function build_dependency_tree(root_file): analyzed_set = set() tree = Tree(root_file) stack = [root_file] while stack is not empty: current_file = stack.pop() if current_file in analyzed_set: continue analyzed_set.add(current_file) includes = parse_includes(current_file) / / User header files only for inc in includes: child_node = Tree.Node(inc) tree.add_child(current_file, child_node) if inc not in analyzed_set: stack.push(inc) return tree Step 7: Visual Drawing Interactive graphics drawing is performed using QGraphicsView from the Qt framework. The layout algorithm is based on a force-directed graph or tree layout, considering node hierarchy and the number of child nodes. Each node is color-coded (e.g., red for leaf nodes, blue for root nodes), and arrows indicate dependency directions. The layout optimization formula references the force-directed model. (Repulsive force) (Attraction) in The node spacing, and It is a constant. Aesthetically pleasing layouts are achieved by iteratively calculating node positions.

[0052] The following is a demonstration of the implementation process: STEP 1: Qt Graphics Framework Initialization and Scene Setup Create a QGraphicsView as the main view and instantiate a QGraphicsScene as the graphics container. Call setRenderHint(QPainter::Antialiasing) to enable anti-aliasing and set the viewport background color to light gray.

[0053] The initial scene boundaries are defined using `setSceneRect()`, and `setDragMode(QGraphicsView::RubberBandDrag)` is configured to support rectangular selection interaction. Node and Edge classes are created that inherit from `QGraphicsItem`, and the `paint()` and `boundingRect()` methods are overridden.

[0054] STEP2: Node Data Modeling and Hierarchical Analysis Define a GraphNode data structure, including attributes such as node ID, hierarchy level, list of child nodes, and dependencies. Call TreeParser::buildHierarchy() to parse the input data, calculate the number of child nodes for each node, and determine the root and leaf nodes. Implement color encoding using ColorCoder::assignColor()—blue (0xFF1E90FF) represents the root node, green (0xFF32CD32) represents intermediate nodes, and red (0xFFFF4500) represents leaf nodes.

[0055] STEP3: Calculation of Initial Position of Force-Oriented Layout A tree-like initial layout is adopted based on node hierarchy: `TreeLayout::initializePositions()` is called to arrange the nodes hierarchically, with the root node centered and child nodes evenly distributed. The initial node spacing is calculated. = sqrt(sceneWidth * sceneHeight / nodeCount) * 2.0. Defines the attraction constant. = 150.0, repulsive force constant =10000.0 STEP4: Iterative Layout Optimization Calculation 4.1. Traverse all node pairs and call calculateRepulsion() to calculate the repulsive force. 4.2. Traverse the dependency edges and call calculateAttraction() to calculate the attraction. 4.3. Integrating Child Node Constraints: Calling `HierarchyConstraint::applyParentAttraction()` enhances the attraction between parent and child nodes. 4.4. Limit Boundaries: Call BoundaryChecker::confineToScene() to prevent nodes from moving out of the scene. STEP 5: Real-time rendering of graphic elements In the `Node::paint()` method, use `QPainter::drawEllipse()` to draw the node disk, filling the inner layer with the main color. Then, call `QPainter::drawText()` to display statistics at the center of the node based on the number of child nodes. In the `Edge::paint()` method, use `QPainterPath` to draw the node connection line, and call `drawArrowHead()` to draw a triangular arrow at the endpoint.

[0056] Complete the visualization drawing.

[0057] Step 8: Connect to the AI ​​interface to generate annotations The system integrates AI models (such as DeepSeek and OpenAI) to automatically analyze the content of leaf node files and generate summary annotations. The annotation process is recursive: starting from the leaf nodes, after generating annotations, it aggregates upwards to the root node to form a project overview. The AI ​​model takes code text as input and outputs natural language annotations. Training data comes from open-source project documentation to ensure annotation accuracy.

[0058] Interface implementation examples: The process of implementing the String AI_Analyze(string file_path) C++ interface: Step 1: Initialize SDK configuration The deep learning inference framework is initialized by calling deepseek::SDK::Initialize(), the pre-trained model file path is set by Config::SetModelPath(), and the GPU-accelerated computing backend is specified by Config::SetComputeBackend(CUDA).

[0059] Step 2: Establish a logging system Create a file logger using Logger::CreateFileLogger("ai_analysis.log").

[0060] Step 3: Verify and read the input file The FileSystem::ValidatePath() function is called to validate the file path and access permissions. The FileReader::ReadBinary() function is used to read the file content in binary mode. The ContentValidator::CheckEncoding() function is used to check the file encoding format.

[0061] Step 4: Data Preprocessing and Cleaning For text files, TextProcessor::RemoveNoise() is called to remove irrelevant characters and formatting noise; for code files, CodeParser::Normalize() is used for syntax standardization; and Tokenizer::Segment() is used for intelligent tokenization.

[0062] Step 5: Extract multi-dimensional features The deepseek::FeatureExtractor::ExtractSemantic() function is called to extract semantic features, the StructureAnalyzer::ParseHierarchy() function is used to analyze the document structure, and the PatternDetector::FindAnomalies() function is used to identify potential problem patterns.

[0063] Step 6: Call the DeepSeek core analysis interface The code is analyzed in depth by calling the deepseek::CodeAnalysis::DeepAnalyze() interface, supplemented by deepseek::NLP::UnderstandContext() to understand the semantics of the text, and security checks are performed by deepseek::Security::ScanVulnerabilities().

[0064] Step 7: Generate structured analysis results The ReportGenerator::CreateStructured() function generates a JSON structured report, the InsightSummarizer::GenerateSummary() function creates a summary of key points, and the RecommendationEngine::SuggestActions() function generates improvement suggestions.

[0065] Step 8: Format the output results The analysis results are passed to ResultFormatter::ToHumanReadable() to be converted into readable text, Visualization::CreateMarkdownReport() is called to generate a Markdown format report, and Localization::TranslateToChinese() is used for Chinese localization.

[0066] Step 9: Resource Cleanup and Result Return Call MemoryManager::ReleaseAnalysisCache() to release the analysis cache, execute FileHandle::CloseAll() to close all file handles, use deepseek::SDK::Cleanup() to clean up SDK resources, and finally return the formatted analysis result string.

[0067] Step 9: Architecture Analysis Cyclic dependency detection: Analyzing cycles in dependency trees. Depth-first search (DFS) is used to detect strongly connected components. Mathematically, a dependency tree is viewed as a directed graph G=(V,E), where V is the set of file nodes and E is the set of inclusion edges (formed by include directives such as #include). Cyclic dependencies correspond to cycles in the graph, and the detection algorithm has a time complexity of O(|V| + |E|).

[0068] Other design pattern analysis: Identifying common design smells, such as excessive inheritance and God objects. Based on heuristics (such as class method count thresholds) or machine learning models.

[0069] Step 10: Generate refactoring suggestions Based on the architecture analysis results, refactoring suggestions are automatically generated, such as: Decompose circular dependencies into interfaces.

[0070] Merge redundant modules.

[0071] Code similarity detection AI detected a bug in the single-file hiding logic. Step 11: Manual intervention The system provides a graphical interface for programmers to confirm refactoring suggestions and supports manual adjustments before executing the refactoring.

[0072] like Figure 2 The diagram shown is a representation of the code file dependency architecture before refactoring. 1. The black modules in the diagram represent different code files.

[0073] 2. Originates from the Main entry file.

[0074] 3. Arrows indicate file dependencies. For example, FileA→FileD means that the file FileA contains the code #include "FileD.h". 4. Black arrows indicate normal dependencies, while red arrows indicate bad dependencies. Normal dependencies mean a hierarchical structure, similar to a tree. Bad dependencies mean jumps in content, such as branch A including files from branch B, making the overall project architecture complex. For example, FileMain including the underlying FileF file is a bad dependency. A good dependency is one where the reader of FileMain only needs to care about the interface of FileB, without needing to know the underlying implementation of FileB, FileF.

[0075] like Figure 3 As shown, this is a well-structured tree architecture diagram after reconstruction. Intuitive visualization enhances comprehension efficiency: Through graphical dependency trees, utilizing color, layout, and interactive elements, the information density is far higher than that of text. For example, in testing, the time it took a programmer to understand a 1000-file project was reduced from an average of 40 hours to 5 hours, an efficiency improvement of 87.5%. Reasoning: Graphics conform to human visual cognition, reducing mental burden; optimized layout algorithms avoid overlap and quickly reveal the structure.

[0076] Automation reduces labor costs: Dependency tree construction and AI annotation are fully automated, reducing manual code reading and manual submission for AI analysis.

[0077] Intelligent analysis improves refactoring quality: Circular dependency detection and AI suggestions are algorithm-based, avoiding subjective errors. Reasoning: Graph theory algorithms ensure the completeness of cycle detection; AI suggestions reference design patterns to reduce the probability of code smells. For example, in the case study project, circular dependencies were reduced by 70%.

[0078] Highly scalable: The system's modular design supports adaptation to other build systems. For example, the CMake parser can be replaced with a Makefile parser; the AI ​​model interface can be changed to improve comments. The UI-visualized mind map can be modified. Shorter overall refactoring cycle: From understanding to refactoring, the time is reduced by more than 50%.

[0079] Although embodiments of the present invention have been shown and described above, it is understood that the above embodiments are exemplary and should not be construed as limiting the present invention. Those skilled in the art can make changes, modifications, substitutions and variations to the above embodiments within the scope of the present invention.< / qdebug>

Claims

1. A semi-automated refactoring method for software projects based on dependency tree construction and AI assistance, characterized in that: Includes the following steps: S1. Receive the root directory path of the software project, automatically detect and determine the root file to build; S2. Parse the root file of the build, identify at least one executable file in the software project, and extract the corresponding source file list for each executable file; S3. For each executable file, determine its program entry file based on build information or file naming conventions; S4. Scan the software project directory, register project file information, and build an internal file tree data structure, where tree nodes represent files and tree edges represent the file's hierarchical relationship in the directory hierarchy; S5. Starting from the program entry file, parse the header file inclusion information, distinguish between user header files and system / third-party header files, and perform subsequent dependency analysis only on user header files; S6. Construct a dependency tree with the program entry file as the root node: Register the user header files contained in the program entry file as child nodes, and recursively parse the header file inclusion relationships of the corresponding files of each child node to add new child nodes; During the recursive process, duplicates are removed based on the analyzed set, and recursion stops when a preset recursion termination condition is met. S7. Interactively draw and display the dependency tree: Arrange the nodes according to the node hierarchy and the number of child nodes, color-code the nodes, and use arrowed edges to indicate the dependency direction; S8. Connect to the AI ​​model interface, automatically analyze the leaf node files of the dependency tree to generate summary annotations, and recursively aggregate the summary annotations from the leaf nodes upwards to the root node to form a project overview. S9. Perform architecture analysis: Detect circular dependencies and identify design smells; S10. Generate refactoring suggestions based on the architecture analysis results, present the refactoring suggestions in the graphical interface, receive user confirmation, filtering and / or manual adjustment instructions for the refactoring suggestions, and output the final refactoring suggestion results based on the instructions.

2. The method according to claim 1, characterized in that: Step S1 includes: detecting the CMakeLists.txt file in the root directory as the build root file, and adapting the parsing of the corresponding build file when the software project uses other build systems; Step S2 includes: matching and parsing the content in the build root file used to define executable files and their source file sets to obtain a list of source files corresponding to each executable file, and the matching and parsing includes using regular expressions to match key instructions in the build root file; Step S3 includes: determining the program entry file based on the parsing information of the build root file, and / or automatically identifying the entry file based on file naming conventions.

3. The method according to claim 1, characterized in that: In step S4, the node attributes of the internal file tree data structure include at least the file name, file path, and file type, and the file type includes at least the header file and the implementation file; and / or the internal file tree data structure is stored using an adjacency list or a tree object.

4. The method according to claim 1, characterized in that: The step S5, which distinguishes between user header files and system / third-party header files, includes: using regular expressions or equivalent matching rules to distinguish between double quote inclusion and angle bracket inclusion, skipping the angle bracket inclusion instructions corresponding to system / third-party header files, and retaining only the double quote inclusion instructions corresponding to user header files for dependency analysis.

5. The method according to claim 1, characterized in that: Step S6 includes: taking the program entry file as the root node, registering the user header files contained in the program entry file as child nodes; and during the recursive parsing process, when the file corresponding to the child node to be parsed is not in the analyzed set, parsing the user header file inclusion relationship of the file and adding a new child node, while adding the file to the analyzed set; when the file corresponding to the child node to be parsed is already in the analyzed set, stopping the recursive parsing of the child node; wherein the preset recursive termination condition includes: the file corresponding to the current node does not have a user header file inclusion relationship, and / or the file corresponding to the current node already exists in the analyzed set.

6. The method according to claim 1, characterized in that: The interactive graphics drawing and display in step S7 includes: presenting the dependency tree through a graphical interface and supporting interactive operations such as zooming, dragging, selection, and / or node positioning; initializing the graphics scene and setting the interaction mode; establishing a node data model and parsing the node hierarchy to determine the number of root nodes, leaf nodes, and child nodes; determining the initial position of nodes based on the tree layout and iteratively optimizing the node position through force-directed layout; rendering node graphics and dependency edges in real time and drawing arrows at the endpoints of dependency edges; distinguishing and displaying root nodes, intermediate nodes, and leaf nodes; and displaying statistical information related to the number of child nodes at the nodes.

7. The method according to claim 1, characterized in that: Step S8 includes: using the code text corresponding to the leaf node as input to call the AI ​​model interface and output a summary annotation in natural language form; summarizing and generalizing the annotations from the leaf node upwards to the parent node, aggregating level by level until the root node to form a project overview; wherein the automatic analysis through the AI ​​model interface includes: initializing the model call configuration and establishing logs; verifying and reading the input file; preprocessing the code text; extracting semantic and structural features; calling the core analysis interface to generate analysis results; generating a structured report; formatting the structured report and outputting it as readable text; and cleaning up resources and returning the results.

8. The method according to claim 1, characterized in that: The circular dependency detection in step S9 includes: treating the dependency relationship corresponding to the dependency tree as a directed graph and performing cycle detection to identify circular dependencies; wherein the cycle detection uses depth-first search to detect strongly connected components, and / or uses an equivalent cycle detection method to identify circular dependencies.

9. The method according to claim 1, characterized in that: The design odor identification in step S9 includes at least identifying excessively deep inheritance and God objects, and the identification method is heuristic rules and / or machine learning models.

10. The method according to claim 1, characterized in that: The refactoring suggestions in step S10 include at least: providing suggestions for interface extraction or dependency decoupling for circular dependencies, providing suggestions for module merging for redundant structures, providing code similarity analysis results to assist in refactoring decisions, and / or providing hints of potential logical problems based on AI analysis; and presenting the refactoring suggestions in a graphical interface, receiving user confirmation, filtering and / or manual adjustment of the refactoring suggestions, outputting the final refactoring suggestion results and / or performing refactoring processing based on the adjustment results.