General-purpose document automatic generation method based on structured code annotation

By collecting and parsing structured code comments, obtaining code context information, extracting semantic features, and dynamically adjusting, the problem of missing information and incoherent logic in code documentation generation in existing tools is solved, achieving high-quality, synchronous code documentation generation that is adaptable to diverse software development scenarios.

CN121433716BActive Publication Date: 2026-03-17国投人力资源服务有限公司
View PDF 1 Cites 0 Cited by

Patent Information

Application Number
CN202610000366.1
Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2026-01-04
Publication Date
2026-03-17
Estimated Expiration
2046-01-04

AI Technical Summary

Technical Problem

Existing automated tools lack in-depth analysis of structured code comments in code documentation generation, failing to fully explore the information related to code elements contained in the comments. As a result, the generated documentation cannot reflect the running logic of the code in specific scenarios, and lacks a dynamic evaluation and control mechanism for the quality of document generation, making it difficult to adapt to diverse software development scenarios.

Method used

By collecting structured code comments from source code, obtaining code context information in real time, performing compensatory parsing and semantic feature extraction, and adjusting the document generation process in conjunction with content update cycle and quality status level, dynamic documents are generated to make up for generation blind spots and adapt to code requirements of different complexity and types.

Benefits of technology

It achieves comprehensive and accurate generation of code documentation, ensuring that the documentation is synchronized with the code, reflecting the design and implementation details and dynamic logic of the code, improving the completeness and accuracy of the documentation, adapting to multiple programming languages ​​and project sizes, and reducing documentation defects.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121433716B_ABST
    Figure CN121433716B_ABST
Patent Text Reader

Abstract

This invention relates to the field of code documentation generation technology and discloses a general automatic documentation generation method based on structured code comments. The method collects structured code comments from source code files and acquires code context information in real time. In a document generation fusion mode, the structured code comments are compensated and parsed to obtain code element description indicators, thereby determining the document content update cycle. By acquiring logical path information during code execution and extracting semantic features, semantic node data is obtained, and the document generation quality status level is determined in combination with code context information. Finally, based on the content update cycle and quality status level, the dynamic document generation blind spots in the document generation process are regulated. This method achieves dynamic optimization of document generation through deep parsing of comments and integration of context and logical path information, enhancing the correlation and completeness between the document and the actual logic of the code.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of code documentation generation technology, specifically a general automatic documentation generation method based on structured code comments. Background Technology

[0002] In software development, code documentation serves as a crucial medium for understanding and maintaining code, and its quality directly impacts development efficiency and software maintainability. Currently, code documentation generation methods mainly fall into two categories: manual writing and automated tool generation. While manual writing ensures the relevance and accuracy of the documentation, it suffers from problems such as being time-consuming, labor-intensive, and prone to update delays. Especially in large projects, as code iteration speeds up, manual documentation often struggles to keep pace, leading to a disconnect between the documentation and the actual code.

[0003] While automated documentation generation tools can improve efficiency, existing tools have many limitations in practical applications. Most automated documentation generation tools rely excessively on simple comments in the code, lacking sufficient depth in analyzing structured code comments and failing to fully extract the interrelationships between code elements contained within them. For example, some tools only extract surface-level information such as function names and parameter lists, lacking effective analysis of deeper content such as the logical intent and design ideas involved in the comments. This results in generated documentation that is merely a formality and fails to meet developers' needs for understanding the code logic.

[0004] Existing tools have significant shortcomings in handling code context information. Code context contains crucial information such as variable scope, function call relationships, and module dependencies, all of which are essential for accurate documentation generation. However, current tools often neglect to acquire and integrate code context in real time, resulting in generated documentation that fails to reflect the code's execution logic in specific scenarios and thus reducing its reference value.

[0005] Existing methods lack dynamic tracing of code execution logic during document generation. The actual execution of code depends on the logical path, and the code behavior may differ under different paths. However, most existing tools generate documents based on static code analysis, failing to incorporate logical path information during code execution. As a result, the documents cannot accurately present the code's execution status in different scenarios.

[0006] Existing automated tools generally lack dynamic evaluation and control mechanisms for document generation quality. Information gaps and logical discontinuities—"generation blind spots"—that exist during document generation are difficult to identify and address in a timely manner, potentially resulting in incomplete information and logical inconsistencies in the generated documents. Furthermore, due to differences in syntax rules and commenting conventions among different programming languages, existing tools have poor universality, often requiring customized development for specific languages ​​and failing to adapt to diverse software development scenarios. These issues collectively lead to insufficient practicality and reliability of existing automated document generation methods, failing to meet the demands of software development for high-quality documentation. Summary of the Invention

[0007] The purpose of this invention is to provide a general method for automatic document generation based on structured code comments, so as to solve the problems mentioned in the background art.

[0008] To achieve the above objectives, this invention provides a general document automatic generation method based on structured code comments, the method comprising:

[0009] Collect structured code comments from source code files and obtain code context information in real time;

[0010] In the document generation fusion mode, the structured code comments are compensated and parsed to obtain code element description indicators. Based on the code element description indicators, the content update cycle of the document object is determined when content tracking is performed during the generation process.

[0011] Obtain logical path information during code execution, extract semantic features from the logical path information to obtain semantic node data of the document object during generation, and determine the quality status level of the document generation process based on the semantic node data and the code context information.

[0012] The dynamic document generation blind spot in the document generation process is regulated based on the content update cycle and the quality status level.

[0013] Preferably, the structured code comments include formatted data blocks that record function functionality, parameter definitions, and associated dependency information.

[0014] Preferably, the code context information includes variable scope, call stack, and code dependency information in the code execution environment.

[0015] Preferably, determining the content update cycle of a document object during content tracking based on the code element description metrics specifically includes:

[0016] The temporal constraint model of the document object in the generative network is determined based on the code element description metrics.

[0017] Output the tracking collaboration boundary for dynamic content tracking from the temporal constraint model;

[0018] The content update cycle of a document object during content tracking is determined by the tracking collaboration boundary.

[0019] Preferably, obtaining logical path information during code execution specifically includes:

[0020] Real-time acquisition of execution status information between function calls;

[0021] The core flow path in the code logic is determined based on the execution status information;

[0022] The logical path information during code execution is determined through the core flow path.

[0023] Preferably, the semantic feature extraction of the logical path information to obtain the semantic node data of the document object at the time of generation specifically includes:

[0024] Based on the logical path information, a correlation model between the dynamic behavior of semantic nodes and historical semantic events is constructed;

[0025] The semantic coupling strength of the document object during generation is output through the association model;

[0026] The semantic influence characteristics of each semantic node in the generative network are determined by the semantic coupling strength.

[0027] The semantic node data of the document object at the time of generation is determined based on the semantic influence features.

[0028] Preferably, determining the quality status level during the document generation process based on the semantic node data and the code context information specifically includes:

[0029] Based on the semantic node data, determine the document quality association constraints during the document generation process;

[0030] The abnormal coupling granularity of the document during the document generation process is determined by the code context information.

[0031] The quality status level during the document generation process is determined based on the quality correlation constraints and the abnormal coupling granularity.

[0032] Preferably, regulating the dynamic document generation blind spot in the document generation process based on the content update cycle and the quality status level specifically includes:

[0033] The amount of flexible adjustment during the document generation process is determined based on the content update cycle.

[0034] The blind spot exposure index in the dynamic document generation blind spot is determined based on the quality status level.

[0035] By performing rule matching between the elastic control amount and the blind spot exposure index, a dynamically adjustable document generation blind spot control map is generated.

[0036] Preferably, in the document generation fusion mode, the structured code comments are compensated and parsed to obtain code element description indicators, specifically including:

[0037] In the document generation fusion mode, the semantic transfer path of the document generation process is determined based on the structured code comments;

[0038] Probabilistic compensation is performed on missing semantic nodes in the structured code comments to generate a complete semantic event sequence;

[0039] Feature aggregation is performed on the semantic event sequence to obtain entropy information during the document generation process;

[0040] The entropy information is used to determine the code element description indicators in the document generation process.

[0041] Preferably, the present invention also includes a method for automatically generating general documents based on structured code annotations, the method further including: generating a blind zone control map based on the dynamic document to generate general document output.

[0042] Compared with the prior art, the beneficial effects of the present invention are:

[0043] This method provides comprehensive and accurate foundational data support for documentation generation by extracting structured code comments from the source code and acquiring code context information in real time. Structured code comments contain key information such as the definition, functional description, and relationships of code elements, while the real-time acquired code context covers dynamic content such as variable scope, function call chains, and module dependencies. The combination of these two elements enriches the initial information for document generation, enabling a more comprehensive reflection of the code's design and implementation details and avoiding the one-sidedness of documentation caused by missing information.

[0044] The document generation fusion mode performs compensatory parsing on structured code comments, effectively compensating for potential information omissions or misunderstandings during conventional parsing. This compensatory parsing mechanism can deeply mine and supplement ambiguous expressions and implicit logic in comments, resulting in more accurate code element description metrics. Based on the content update cycle determined by these metrics, the document generation process can be matched with the code iteration rhythm, ensuring that the document content reflects the latest code changes in a timely manner, reducing the time lag between document and code, and keeping the document synchronized with the code at all times.

[0045] By acquiring logical path information during code execution and extracting semantic features, the document is infused with the dynamic logical meaning of code runtime. The actual functionality of the code depends on the logical path, and code behavior may differ significantly under different paths. Semantic feature extraction can transform this dynamic logic into quantifiable semantic node data. Combined with the quality status level determined by code context information, key indicators such as information completeness and logical coherence in the current document generation process can be objectively evaluated. This provides an effective basis for dynamic control of document quality, ensuring that the generated document not only contains static code structure information but also reflects dynamic code execution logic.

[0046] By adjusting the blind spots in dynamic document generation based on content update cycles and quality status levels, the completeness and accuracy of the documents are further improved. Blind spots in dynamic document generation typically stem from the complexity of code logic, incomplete comments, or limitations in the parsing process. The adjustment mechanism can target these blind spots with optimizations, such as supplementing missing logical explanations, refining vague functional descriptions, and strengthening the connection between related elements. This dynamic adjustment capability makes the document generation process more adaptable, capable of handling document requirements with varying complexity and code types, and reducing document defects caused by fixed generation patterns.

[0047] Furthermore, the method's versatility allows it to adapt to various programming languages ​​and project scenarios of different sizes. Whether it's object-oriented programming or structured programming, whether it's a small utility project or a large system-level project, the method can achieve stable and efficient document generation through flexible adaptation to structured annotation parsing rules, context information extraction methods, and semantic feature extraction models. This eliminates the need for extensive custom development for specific scenarios, thus broadening the method's application scope. Attached Figure Description

[0048] Figure 1 This is a sequence diagram of the general document automatic generation method based on structured code comments described in this invention;

[0049] Figure 2 A flowchart for extracting semantic features of logical path information and determining semantic node data;

[0050] Figure 3 A flowchart for determining the content update cycle;

[0051] Figure 4 A flowchart for determining the quality status level. Detailed Implementation

[0052] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.

[0053] Please see Figure 1 This invention provides a general method for automatic document generation based on structured code comments, the method comprising:

[0054] The system extracts structured code comments in a pre-formatted format from source code files, while simultaneously capturing the code context information associated with the current comment in real time. Subsequently, the system enters a document generation fusion mode. In this mode, a compensation parsing operation is performed on the collected structured code comments. This operation aims to handle potential missing or incomplete comment information, inferring and supplementing necessary information through an algorithmic model, ultimately outputting a set of code element description metrics reflecting the characteristics of code elements. Based on these metrics, the system further calculates the content update cycle that the document object must follow when performing content tracking operations during the generation process. This cycle determines the frequency and timing of document content updates as code changes occur.

[0055] In another parallel path, the system acquires logical path information generated during code execution or simulation. This involves tracing the flow and branches of code execution. Deep semantic feature extraction is performed on this logical path information to identify and abstract key semantic features, forming semantic node data that the document object needs to embody during generation. Combined with previously acquired code context information, the system analyzes and evaluates this semantic node data to determine the quality status level of the document content during document generation. This level reflects the potential quality level of document fragments in terms of semantic accuracy, contextual consistency, etc.

[0056] Based on the content update cycle and quality status level determined in the preceding steps, the system proactively adjusts for potential dynamic document generation blind spots during the document generation process. Dynamic document generation blind spots refer to areas of document content that the document generation system struggles to accurately and promptly cover or update due to reasons such as code changes, complex contextual dependencies, or semantic misunderstandings. The goal of this adjustment is to optimize the coverage, accuracy, and timeliness of document generation.

[0057] Example 1: See Figure 2The collection and parsing of structured code comments is a fundamental step in the automatic documentation generation method. The system extracts predefined formatted comment blocks from source code files. These comment blocks are not free text, but rather structured data organized using specific markup languages ​​or syntax rules. For example, before defining a function or method, developers must insert comment blocks according to specifications, including fields such as function description, parameter list, return value description, and dependency relationships. The function description field should concisely summarize the core function of the function, avoiding vague or redundant descriptions. The parameter list should list the name, data type, value range, and business meaning of each input parameter, ensuring that each parameter has a clear semantic definition. The return value description should clearly describe the output result after the function is executed, including possible error codes or exceptions. The dependency relationship field should specify the external modules, library functions, or data sources called by the function, as well as the global state or persistent data that may be affected.

[0058] When parsing these structured comments, the system needs to identify and verify the completeness and consistency of the fields. For example, if a parameter lacks a data type description or a dependency is not explicitly marked, the system needs to record this missing information for subsequent compensation processing. During parsing, the system uses syntax analysis technology to decompose comment blocks into structured data objects, such as dictionaries, tree structures, or relational data tables, facilitating subsequent use by the document generation engine. Simultaneously, the system checks whether the comment content conforms to a predefined glossary or business terminology specification to avoid terminological confusion or ambiguity.

[0059] Obtaining code context information is another crucial step, aiming to ensure that the generated documentation accurately reflects the actual runtime environment of the code. The system collects information such as variable scope, call stack, and code dependencies through a combination of static analysis and dynamic monitoring. Variable scope information includes the visibility range of global variables, local variables, class member variables, and closure variables. The system needs to track the declaration, assignment, and reference relationships of these variables to determine their descriptive granularity in the documentation. For example, global variables typically require detailed explanations of their purpose and lifecycle in system-level documentation, while local variables may only be briefly mentioned in the documentation within a function.

[0060] Call stack information records the execution path of a function or method, including nested call relationships, recursion depth, and exception handling procedures. The system captures this information through instrumentation techniques or runtime monitoring tools and analyzes high-frequency call paths or key execution branches. For example, a core business function may be called by multiple upper-level modules; the system needs to identify these call points and clearly label their use cases and constraints in the documentation. Furthermore, the system also needs to monitor exception handling logic to ensure that the documentation covers possible error recovery strategies or fault tolerance mechanisms.

[0061] Code dependency information describes the references and calls between modules, classes, or functions. The system visualizes these relationships by building a dependency graph. For example, a utility class may be referenced by multiple business modules. The system needs to analyze its interface stability and change frequency to determine the documentation update strategy. Simultaneously, the system identifies circular dependencies or overly coupled code structures and marks potential design risks or refactoring suggestions in the documentation. Dependency analysis is not limited to the source code level; it may also involve external services, database tables, or configuration files. The system must ensure that these external dependencies are accurately described in the documentation.

[0062] The combined use of structured code comments and code context information allows the documentation generation process to consider both static descriptions and dynamic behavior. When parsing comments, the system performs semantic validation by referring to context information. For example, if a comment describes a parameter's value range as 0 to 100, but the code actually contains out-of-bounds checking logic for that parameter, the system must ensure that the description in the documentation is consistent with the code behavior. If a contradiction or omission is found, the system will trigger a compensation mechanism, such as inferring missing information based on historical data or patterns in similar code, or prompting the developer to supplement the comment content.

[0063] The system maintains a synchronization mechanism between comments and code to ensure timely documentation. When code changes, the system checks if comments are updated synchronously. If outdated or invalid comments are found, the system automatically marks the documentation segments requiring updates through version comparison or change impact analysis. For example, if the parameter list of a function changes but the comments are not adjusted accordingly, the system will mark that part as content to be verified during the documentation generation process, or infer possible comment update suggestions based on the code change history.

[0064] In the integrated documentation generation mode, the system combines structured comments and contextual information to construct descriptive metrics for code elements. These metrics include dimensions such as functional completeness, parameter accuracy, and dependency clarity, which guide subsequent documentation generation strategies. For example, if a function has complete comments and clear contextual dependencies, the system will use a standard template to generate detailed documentation; if many comments are missing or the context is complex, the system may choose to generate a summary description and mark the parts that require manual review.

[0065] Example 2: See Figure 3The process of determining the content update cycle is based on in-depth analysis of code element descriptive metrics. These metrics are a set of quantitative features obtained through compensated parsing of structured code comments. These features reflect multiple dimensions of code elements, including complexity, change frequency, external dependency strength, and internal logical coherence. The system first normalizes these metrics to eliminate analytical biases caused by different units of measurement. Then, it uses clustering or classification algorithms to divide code elements into several groups with similar characteristics. Each group corresponds to a different document maintenance priority and update sensitivity. For example, core algorithm modules that change frequently typically require shorter update cycles, while stable utility functions may adopt a more lenient update strategy.

[0066] The construction of the temporal constraint model is a core step in determining the content update cycle. This model uses a directed graph structure to represent the generation dependencies between document objects. Nodes represent specific document fragments, and edges represent temporal constraints between fragments. Constraint types include strong and weak orders: strong orders require the source node document to be generated before the target node, commonly seen between basic module documents and upper-level application documents; weak orders only suggest but do not enforce the generation order, suitable for independent functional modules with high parallelism. The system automatically derives these constraints by analyzing the call chains and data flows between code elements and constructs a complete temporal dependency network. During model execution, the system continuously monitors the code repository's commit history and dynamically adjusts the weight coefficients of the constraints, enabling the model to adapt to the evolution of the code repository.

[0067] The calculation of the tracking collaboration boundary needs to comprehensively consider the semantic correlation between document fragments and the risk of change propagation. The system first establishes vector representations of document fragments, extracts their core semantic features using natural language processing techniques, and then calculates the cosine similarity or semantic distance between different fragments. For document fragments with similarity exceeding a threshold, the system will group them into the same tracking collaboration region. Simultaneously, the system analyzes historical change data, statistically analyzing the covariance probability between different code elements—that is, the likelihood that other elements will change when one element is modified. Based on these analysis results, the system will draw an impact map of document updates, clearly marking the set of document fragments requiring collaborative updates and their correlation strength.

[0068] The final determination of the content update cycle employs a multi-factor decision-making mechanism. The system uses the generation order suggestions output by the time-constrained model, the update range defined by the tracking collaboration boundary, and the stability rating of the code elements themselves as input parameters. A weighted scoring algorithm is then used to calculate the basic update interval for each document segment. This interval can be dynamically adjusted according to the actual development scenario. For example, a shorter default cycle can be set in agile development mode, while a more lenient update strategy can be adopted during the maintenance phase. The system also introduces a random disturbance factor to avoid uneven system load caused by a large number of documents being updated simultaneously. The unit of measurement for the update cycle can be either time-based or event-based, depending on the actual needs of the project development.

[0069] The collection of logical path information employs a combination of static analysis and dynamic tracing. In the static analysis phase, the system constructs a complete control flow graph by parsing the source code, identifying all possible execution paths. This process pays particular attention to conditional branch statements, loop structures, and exception handling blocks, as these code structures typically correspond to important business logic branches. The system annotates each path with features, including path length, node complexity, and the number of external dependencies, providing data support for subsequent core path selection. In the dynamic tracing phase, the system deploys a lightweight monitoring agent in the test or production environment to record the actual execution sequence and frequency of function calls. The monitoring data undergoes anonymization and aggregation to eliminate biases caused by test cases and retain typical execution patterns from real business scenarios.

[0070] The algorithm for identifying core workflow paths needs to balance path coverage and execution frequency. The system first deduplicates and categorizes all collected execution paths, merging variations with high similarity. Then, a frequent pattern mining algorithm identifies common path segments that repeatedly appear in multiple test cases or business scenarios. These segments often correspond to the system's most critical business logic backbone. The system calculates an importance score for each candidate path, considering factors such as historical execution frequency, the criticality of the involved code, and associated business value. Finally, the paths with the highest scores are selected as core workflow paths; these paths will be the execution logic that needs to be highlighted during document generation.

[0071] The structured storage of logical path information is organized in the form of an execution tree. The root node of the tree represents the program entry point, each branch corresponds to a complete execution sequence, and the leaf nodes mark the execution termination status. Each node in the tree contains rich metadata, such as the corresponding code location, the parameter values ​​during execution, and the system resources consumed. This organization not only preserves the temporal characteristics of the path but also facilitates statistical analysis from various dimensions. The system periodically prunes and optimizes the execution tree, removing outdated test paths and merging redundant branch nodes to ensure that the stored path information always reflects the true behavioral characteristics of the current version of the code.

[0072] During the documentation generation process, logical path information is primarily used to supplement the missing dynamic behavior descriptions in the structured comments. The system analyzes the correspondence between core flow paths and code elements, automatically generating contextual descriptions such as "This function is typically called in the third stage of business process A, and the input parameters mainly come from the calculation results of module B." For complex functions with multiple important execution paths, the documentation explicitly lists the triggering conditions and expected behaviors of each path, helping developers fully understand the code's operating mechanism. Path information is also used to verify the accuracy of comment content; when a significant deviation is found between the documentation description and the actual execution logic, the system generates corresponding revision suggestions or risk warnings.

[0073] The combined use of content update cycles and logical path information allows the documentation maintenance strategy to consider both the structural characteristics and runtime behavior of the code. The system monitors the stability of the core workflow path and automatically shortens the documentation update cycle for code areas where execution modes have changed significantly. Simultaneously, frequently modified execution paths are marked as high-risk areas, and their corresponding documentation snippets are appended with additional change history descriptions and compatibility hints during generation. This dynamic adjustment mechanism ensures that the documentation content reflects the code's performance in the real runtime environment in a timely manner, rather than merely remaining at the level of static declarations.

[0074] Example 3: See Figure 4 The extraction of semantic node data is based on in-depth analysis of logical path information. The system first preprocesses the collected logical path information, removing noisy data and irrelevant branches, and retaining the execution sequences that reflect the core business logic. These sequences are converted into a weighted directed graph structure, where nodes represent key execution points in the code, edges represent control flow transitions, and the weight of an edge is determined by the frequency of that transition in actual operation. The system uses an information entropy-based method to evaluate the importance of each node and marks key decision points and state transition points in the execution path. These marked points constitute a preliminary set of semantic node candidates, serving as input for subsequent association model construction.

[0075] The association model is constructed using a dynamic time warping algorithm to align historical semantic events with current code behavior. Historical semantic events are derived from existing document fragments, comments, and knowledge base entries maintained by the development team in the codebase. The system establishes a feature vector for each semantic node candidate, containing the node's corresponding code structure features, runtime context features, and textual description features. Structural features refer to the type, complexity, and dependencies of code elements; runtime context features include variable states, call stack depth, and exception handling; and textual description features come from existing comments or document fragments. These feature vectors are projected onto a unified semantic space, and the association between the current node and historical events is established through similarity calculation.

[0076] The semantic coupling strength is calculated using the following formula:

[0077]

[0078] in: This indicates the semantic coupling strength between node i and historical event j. It is the weight coefficient of the k-th feature. This is a similarity measure between node i and historical event j on the k-th feature dimension, where n is the total number of features. The weight coefficients are trained using machine learning methods and reflect the contribution of different features to semantic association. The appropriate calculation method is selected based on the feature type; for example, cosine similarity is used for text features, and Euclidean distance is used for numerical features. The output of this formula is normalized and falls within the range of 0 to 1; a larger value indicates a stronger semantic association.

[0079] The derivation of semantic influence features employs a graph propagation algorithm. The system constructs a semantic association network, connecting nodes with high coupling strength and historical events to form a weighted semantic graph. In this graph, a node's influence is reflected by its connectivity and connection weight. The system calculates the centrality indices for each node, including degree centrality, proximity centrality, and betweenness centrality. These indices reflect the node's importance in the semantic network from different perspectives. Degree centrality measures the number and strength of direct connections between nodes; proximity centrality reflects the ease with which a node reaches other nodes in the network; and betweenness centrality represents a node's ability to act as a bridge connecting different semantic communities. These centrality indices are weighted and combined to form the final semantic influence feature vector.

[0080] The process of extracting quality-related constraints analyzes consistency patterns in semantic node data. The system checks for conflicts or ambiguities in terminology, logical expression, and interface conventions among relevant semantic nodes. Terminology checks ensure consistent representation of the same concept across different nodes; logical expression verification focuses on the completeness of descriptions of logical structures such as conditional statements, loop control, and exception handling; and interface convention review verifies the documentation level of interface elements such as parameter passing, return value handling, and error code definitions. The system establishes a constraint rule base, including quality requirements from industry standards, project specifications, and enterprise best practices. Semantic node data is matched against these rules to identify hard constraints that need to be met and flexible guidelines that are recommended to be followed.

[0081] Anomaly coupling granularity detection is based on dependency analysis using code context information. The system constructs a fine-grained dependency matrix, recording the call relationships, data flow relationships, and concurrent interaction relationships between various code elements. Anomalies mainly manifest as circular dependencies, cross-layer references, and implicit conventions. Circular dependencies refer to closed loops formed by two or more modules directly or indirectly referencing each other; cross-layer references violate the layering principles in architectural design, such as the presentation layer directly accessing the data access layer; implicit conventions involve passing information through global variables or environment configurations instead of explicit interfaces. The system quantifies the severity of these anomalies, calculates their impact scope and modification costs, and uses this as the basis for evaluating the granularity of anomalies.

[0082] The determination of quality status level adopts a multi-dimensional comprehensive evaluation framework. This framework maps the satisfaction degree of quality-related constraints and the severity of abnormal coupling granularity to orthogonal evaluation coordinates. Constraint satisfaction is divided into three levels: fully compliant, partially compliant, and non-compliant, calculated by weighting the number and importance of missing or conflicting constraints. Abnormal coupling granularity is divided into module-level, component-level, and system-level according to its impact scope, and into three levels: low, medium, and high according to modification cost. The system maintains a decision matrix, defining the quality level judgment rules for different combinations of conditions. For example, document areas that fully comply with constraints and have no system-level abnormal coupling are rated as the best level; document areas that partially comply with constraints but have high modification cost component-level anomalies may be rated as needing improvement.

[0083] The collaborative analysis of semantic node data and code context information employs a cross-validation mechanism. The system compares the semantic relationships obtained from static analysis with the call patterns captured at runtime to identify potential descriptive discrepancies. Static semantic relationships primarily derive from code structure and comments, reflecting the developer's design intent; runtime call patterns embody the actual behavioral characteristics of the code. When significant differences arise, the system generates a verification flag, indicating potential issues requiring manual review. This mechanism can detect outdated comments, interface misuse, or design deviations, ensuring that the generated documentation accurately expresses the design philosophy while truthfully reflecting runtime behavior.

[0084] The quality risk control during document generation employs a tiered approach. Based on the quality status level, the system uses differentiated generation methods for different document areas. High-level areas use a standard template to generate a complete document; medium-level areas generate a summary description with warning labels; and low-level areas only output basic information and indicate the need for manual intervention. The system records detailed evidence for quality assessments, including specific missing constraints and abnormal coupling points. This information is output along with the document for subsequent targeted improvements. Simultaneously, the system maintains a quality trend tracking mechanism, recording the historical changes in the quality level of each document area to help identify continuously deteriorating risk points.

[0085] The entire process of semantic feature extraction and quality assessment emphasizes interpretability and traceability. The system records intermediate results and decision-making basis for each analysis step, forming a complete processing chain log. These logs are stored in a structured format, supporting on-demand querying and review. When code or comments change, the system can quickly locate the affected semantic nodes and quality assessment items, enabling incremental update calculations. This design allows the documentation generation system to not only output the final results but also provide clear descriptions of the analysis process, enhancing the development team's trust in the automatically generated documentation.

[0086] Example 4: The process of controlling blind spots in dynamic document generation can be clearly demonstrated through a specific example. Taking an e-commerce platform's order processing system as an example, this system includes four core modules: order creation, payment verification, inventory deduction, and logistics scheduling. During document generation, the system detected a high blind spot exposure index in the inventory deduction module, mainly because this module has recently undergone several business logic adjustments, but the relevant annotations have not been fully updated in sync.

[0087] The calculation of the elasticity adjustment amount is based on the frequency and scope of code changes to this module. The system analyzes the commit records in the version control system, and counts the number of modifications to the inventory deduction module, the number of functions involved, and the number of other modules that depend on these functions within the past month. Based on preset evaluation criteria, the system determines that this module requires a high elasticity adjustment amount to adapt to frequent changes in business needs. Specific evaluation data can be found in Table 1.

[0088] Table 1: System evaluation data.

[0089] Evaluation Dimensions Statistical value Weighting coefficient Standardized score Weekly submissions 6 0.3 0.85 Proportion of affected functions 45% 0.4 0.72 Cross-module dependency count 8 0.3 0.91 Comprehensive elastic control quantity - - 0.81

[0090] The blind spot exposure index assessment focused on the documentation deficiencies in the inventory deduction module. The system detected that the comments for three key functions in this module were not updated with the code: the asynchronous inventory pre-allocation function lacked a description of a retry mechanism, the batch deduction interface lacked a recorded concurrency control strategy, and the inventory rollback operation lacked descriptions of abnormal scenarios. Based on the importance and scope of the missing content, the system calculated the blind spot exposure index for this module to be 0.68 (range 0-1, with higher values ​​indicating greater risk).

[0091] The rule matching engine combines the elastic control amount of 0.81 with the blind spot exposure index of 0.68 for analysis. Referring to the preset control strategy matrix, it determines to adopt a composite strategy of "deep generation + monitoring and marking" for this module. The deep generation strategy requires the documentation generation engine to call more complex parsing algorithms, including: inferring the triggering conditions of retry logic through code context, analyzing the usage patterns of locking mechanisms to supplement concurrency control descriptions, and checking exception handling branches to improve the description of rollback scenarios. The monitoring and marking strategy adds special markers to the generated documentation, reminding developers to focus on confirming these automatically inferred contents during the next code review.

[0092] The document generation blind spot control map is constructed using a hierarchical representation method. The top layer displays the overall control strategy at the module level, the middle layer lists the detailed processing schemes of each function, and the bottom layer marks the specific code locations that require manual review. Taking the inventory deduction module as an example, its control map includes the following key information: the main entry function adopts the standard generation mode because its comments are complete and it has not been modified recently; the asynchronous pre-occupancy function enables deep generation and adds the "inferred content" mark; the batch deduction interface generates a summary description and adds the "concurrency risk" warning; the rollback operation function generates a basic framework but leaves blank areas for manual supplementation.

[0093] The compensation parsing process is adjusted to meet the specific needs of the inventory deduction module within the document generation fusion mode. The system first establishes the semantic transition path for this module, analyzing the state transition sequence from order creation to inventory change. For the missing retry mechanism description in the asynchronous preemptive function, the system compensates through the following steps: checking the loop structure and exception handling block inside the function to identify retry logic with a maximum of 3 attempts; analyzing log output statements to determine the retry interval is 2 seconds; and examining the caller code to find that a compensation order is triggered after a retry failure. These inferences, after confidence evaluation, are integrated into the generated document.

[0094] The construction of the semantic event sequence takes into account the business characteristics of inventory management. The system identifies the basic event flow of "inventory query → pre-position locking → actual deduction → status synchronization" and adds associated attributes to each event node. For example, in the pre-position locking node, the system adds details such as "lock timeout 300 seconds" and "supports partial pre-positioning" by analyzing the code. These additions are derived from the analysis of the call parameters of the distributed lock utility class and the derivation of the logic for processing inventory pre-positioning results.

[0095] The feature aggregation phase employs a business scenario-oriented analysis approach. The system identifies three typical inventory deduction scenarios: regular retail orders, flash sales, and wholesale purchases, and calculates the execution path characteristics for each scenario. Regular order scenarios exhibit a simple linear processing flow; flash sale scenarios demonstrate high-frequency concurrent conflict handling; and wholesale purchase scenarios involve complex batch deduction logic. The system maps these scenario characteristics to corresponding code implementations, creating scenario-based usage instructions in the documentation.

[0096] The calculation of entropy values ​​reflects the degree of uncertainty in the document generation process. The inventory deduction module, due to its numerous automatically inferred entries, has a significantly higher entropy value than the fully annotated order creation module. The system uses this entropy difference to adjust the document's presentation: high-entropy areas are formatted more prominently, include confidence level indicators, and are accompanied by detailed explanations of the inference basis; low-entropy areas are generated with concise descriptions using a standard template. This differentiated approach helps readers quickly identify parts of the document that require special attention.

[0097] The dynamic adjustment mechanism demonstrated adaptability in actual operation. When the system detected that the development team began to centrally update the comments of the inventory deduction module, it automatically reduced the blind spot exposure index assessment of that module and adjusted the generation strategy accordingly. The new comment content was identified through version comparison, and the system gradually reduced the proportion of automatic inference, shifting to a comment-based generation mode. At the same time, the system recorded the experience data during this adjustment process, optimized the parameter settings of the rule matching engine, and improved the accuracy of handling similar situations in the future.

[0098] Example 5: The generation process of general document output is based on a dynamic document generation blind spot control map. This map serves as the control center of the entire document generation system, containing the comprehensive analysis results processed by the aforementioned examples, guiding the final document generation strategy and content organization. The system first analyzes the control map to identify document regions at different levels and their corresponding processing requirements. Each node in the map represents a document generation unit, and node attributes include the unit's content source, quality rating, generation priority, and special processing flags. The system sorts these nodes according to priority, constructing an execution queue for document generation.

[0099] The document generation engine employs a modular processing architecture, invoking corresponding generator components for different types of document units. For areas marked as standard generation, the engine uses basic templates to populate content. These templates are predefined based on the type of code element, such as class description templates, function description templates, and interface specification templates. The variable sections in the templates are filled with structured code comments and code context information, maintaining format consistency while ensuring content accuracy. Deep generation areas trigger enhanced generators, which combine semantic node data and logical path analysis results to generate detailed documents including execution flowcharts, state transition descriptions, and typical call examples. Summary generation areas use simplified descriptions, listing only key functions and main parameters, and adding content expansion hints.

[0100] The content integration phase addresses the relationships between document units. The system analyzes the dependencies and references recorded in the control graph and inserts appropriate cross-references into the generated documents. For example, when the documentation for function A mentions that it calls function B, the system automatically adds a hyperlink to the documentation for function B at the appropriate location. For complex call chains or data flows, the system generates visual relationship diagrams to help readers understand the interaction between modules. Content integration also includes terminology consistency checks to ensure that the same concepts are expressed consistently throughout the document, adding glossaries or indexes where necessary.

[0101] A risk labeling mechanism is implemented throughout the entire document generation process. Based on the assessment results of the quality status level and blind spot exposure index, the system inserts visual risk labels at appropriate locations in the document. Low-risk areas may be marked with only a light-colored border, medium-risk areas are marked with an exclamation mark icon and a brief explanation, and high-risk areas are marked with a column-style warning box, detailing potential problems and suggested verification methods. These risk labels not only draw the reader's attention to specific content but also provide key references for subsequent document maintenance. The system records the decision-making basis for each risk label, forming a traceable quality assessment chain.

[0102] Version adaptation ensures a clear correspondence between documentation and code versions. The system embeds a version identifier in the header or footer of the document, which is associated with a commit hash or tag in the source code version control system. When the documentation covers features that may change with version changes, the system automatically adds version applicability information, such as "This parameter is supported starting with v2.1.0". For deprecated but still retained interfaces or features, the documentation clearly indicates their deprecation status and suggests alternatives to help users transition smoothly.

[0103] The output format conversion supports various common document formats. The system's built-in converter can convert structured document content into Markdown, HTML, PDF, and other formats to meet the needs of different scenarios. The format conversion process preserves the original document's logical structure and visual elements, such as heading levels, code block highlighting, and chart placement. For team collaboration scenarios, the system can generate interactive documents with annotation capabilities, allowing developers to add supplementary explanations or correction suggestions directly while reading. The format conversion also includes responsive design processing to ensure a good reading experience on different devices.

[0104] The document release process includes an automated verification step. Before the final output, the system performs a series of checks to ensure the document's integrity and consistency. Basic verification includes dead link detection, format compliance checks, and content duplication analysis. Advanced verification involves semantic consistency assessment, such as checking whether parameter descriptions match actual types and verifying whether sample code matches actual call methods. Issues are categorized and handled according to their severity. Critical issues interrupt the release process and notify maintenance personnel, while general issues are recorded in the release notes for future reference. Verified documents are pushed to designated release channels, such as internal document management systems, team collaboration platforms, or public API documentation sites.

[0105] The feedback mechanism enables continuous improvement of the document system. Generated documents include embedded feedback components, allowing readers to rate specific content or submit comments. The system collects this feedback data and performs correlation analysis with code change history and document generation logs to identify areas for optimization. For frequently raised feedback points, such as unclear concept descriptions or insufficient examples, the system adjusts the generation strategy for the corresponding areas, improving document quality in subsequent versions. Feedback data is also used to train the parameters of the generation model, gradually improving the accuracy and readability of automatically generated content.

[0106] The maintenance mode document updates employ an incremental generation strategy. When a source code change is detected, the system analyzes the scope of the change and regenerates only the affected document portions, rather than rebuilding the entire document. This strategy significantly improves the efficiency of document updates, making it particularly suitable for development projects with frequent iterations. During incremental updates, the system compares the differences between the old and new versions, adding change markers or revision history to the document to help readers quickly identify the latest modifications. For major changes, the system can generate dedicated migration guides or compatibility notes, reducing the adaptation costs during the upgrade process.

[0107] The knowledge inheritance process preserves valuable information from historical documentation. When code refactoring leads to fundamental changes to certain interfaces or modules, the system analyzes the descriptions in the old documentation, extracts still-applicable conceptual explanations and design principles, and integrates them into the corresponding sections of the new documentation. This process avoids knowledge gaps, ensuring that even after multiple iterations, the documentation still reflects the system's core design philosophy and evolution. The knowledge inheritance process includes a manual review stage, where developers confirm whether the automatically extracted content is indeed applicable to the new version.

[0108] The final form of the general documentation output is a complete technical documentation system, containing multi-layered content from API references to an architecture overview. The top-level documentation provides a comprehensive overview of the system and the relationships between major modules; the middle-level documentation details the functions and interfaces of each module; and the bottom-level documentation focuses on specific implementation details and internal processing mechanisms. This hierarchical structure allows different types of readers to quickly locate the information they need. Beginners can start with the overview and gradually delve deeper, while experienced developers can directly consult the specific interface specifications. The documentation system also includes supplementary usage examples, frequently asked questions, and performance considerations, forming a comprehensive technical reference resource.

[0109] The entire implementation process demonstrated the complete workflow of the automated document generation system. From the analysis of the control graph to the final document release, each step revolved around improving document quality and usability. Through methods such as dynamically adapting to code changes, intelligently compensating for missing content, and accurately marking risk areas, the generated documents maintained synchronization with the source code while providing rich technical information beyond simple comments. The introduction of multi-format output and feedback mechanisms further enhanced the usability and sustainability of the documents in real-world development environments, making them an indispensable part of the software development process.

[0110] It should be noted that, in this document, relational terms such as "first" and "second" are used only to distinguish one entity or operation from another, and do not necessarily require or imply any such actual relationship or order between these entities or operations. Furthermore, the terms "comprising," "including," or any other variations thereof are intended to cover non-exclusive inclusion, such that a process, method, article, or apparatus that comprises a list of elements includes not only those elements but also other elements not expressly listed, or elements inherent to such process, method, article, or apparatus.

[0111] Although embodiments of the invention have been shown and described, it will be understood by those skilled in the art that various changes, modifications, substitutions and alterations can be made to these embodiments without departing from the principles and spirit of the invention, the scope of which is defined by the appended claims and their equivalents.

Claims

1. A general-purpose document automatic generation method based on structured code annotations, characterized in that, The method comprises the following steps: Collecting structured code annotations from source code files and obtaining code context information in real time; In a document generation fusion mode, the structured code annotations are compensated and parsed to obtain code element description indicators, and the content update period of the document object during content tracking in the generation process is determined according to the code element description indicators; Logical path information in the code execution process is obtained, semantic feature extraction is performed on the logical path information, semantic node data of the document object during generation is obtained, and the quality situation level in the document generation process is determined according to the semantic node data and the code context information; The dynamic document generation blind area in the document generation process is regulated according to the content update period and the quality situation level; The content update period of the document object during content tracking in the generation process is determined according to the code element description indicators, specifically including: The timing constraint model of the document object in the generation network is determined according to the code element description indicators; The tracking coordination boundary of dynamic content tracking is output from the timing constraint model; The content update period of the document object during content tracking in the generation process is determined by the tracking coordination boundary; The quality situation level in the document generation process is determined according to the semantic node data and the code context information, specifically including: The quality association constraint of the document in the document generation process is determined according to the semantic node data; The abnormal coupling granularity of the document in the document generation process is determined through the code context information; The quality situation level in the document generation process is determined according to the quality association constraint and the abnormal coupling granularity; The dynamic document generation blind area in the document generation process is regulated according to the content update period and the quality situation level, specifically including: The elastic regulation amount in the document generation process is determined according to the content update period; The blind area exposure index in the dynamic document generation blind area is determined according to the quality situation level; The elastic regulation amount and the blind area exposure index are matched to generate a dynamically adjustable document generation blind area regulation map; Based on the dynamic document generation blind area regulation map, a general document output is generated.

2. The method for automatic generation of general documents based on structured code annotations according to claim 1, characterized in that, The structured code annotations include formatted data blocks recording function functions, parameter definitions and associated dependency information.

3. The method of claim 1, wherein the method is based on structured code annotations. The code context information includes variable scope, call stack and code dependency relationship information in the code execution environment.

4. The method of claim 1, wherein the method is based on structured code annotations. The logical path information in the code execution process is obtained, specifically including: Real-time collection of execution state information between function calls; The core flow path in the code logic is determined according to the execution state information; The logical path information in the code execution process is determined through the core flow path.

5. The method of claim 1, wherein the method is based on structured code annotations. The semantic feature extraction of the logical path information to obtain the semantic node data of the document object during generation specifically includes: Based on the logical path information, an association model of semantic node dynamic behavior and historical semantic events is constructed; The semantic coupling strength of the document object during generation is output through the association model; The semantic influence characteristics of each semantic node in the generation network are determined through the semantic coupling strength; According to the semantic influence feature, semantic node data of the document object at the time of generation is determined.

6. The method for automatic generation of general documents based on structured code annotations according to claim 1, characterized in that, In the document generation fusion mode, the structured code annotation is compensated and parsed to obtain code element description indicators, specifically including: In the document generation fusion mode, according to the structured code annotation, a semantic transfer path of a document generation link is determined. The missing semantic nodes in the structured code annotation are compensated for probability to generate a complete semantic event sequence. The semantic event sequence is aggregated for features to obtain entropy value information in the document generation process; and the code element description indicators in the document generation process are determined from the entropy value information.

Citation Information

Patent Citations

  • Large model-based standard document automatic generation and multi-dimensional auditing method and system

    CN120597846A