System, method and apparatus for generalized code element extraction for sv condition compilation

CN122963563APending Publication Date: 2026-10-23上海芯钛信息科技有限公司
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611404479.4
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-09-10
Publication Date
2026-10-23

AI Technical Summary

Technical Problem

现有工具通常使用简单的布尔标志位,无法正确处理嵌套场景下的状态恢复

Benefits of technology

上述面向SV条件编译的通用化代码元素提取系统、方法及设备,包括预编译正则表达式模式库、条件状态栈管理机制模块、回调式通用收集机制模块、注释感知的预处理机制模块和分段查找提取机制模块,通过条件状态栈逐层保存并恢复有效性状态,确保进入嵌套层级前的外部条件被记录、退出层级时被恢复,从而正确处理任意层级嵌套条件编译;通过回调解耦使同一解析框架可通用提取任意类型代码元素,新增元素类型仅需新增回调函数且无需修改解析器,具备可复用性与可扩展性;通过注释感知预处理避免注释中的条件编译指令被误识别,保证状态判断与收集结果准确;通过分段查找使同一文件不同段落独立解析且互不干扰;通过集中管理模式并延迟编译兼顾可维护性与解析效率。各模块紧密协同,共同实现通用、可复用且能正确处理任意层级嵌套条件编译的代码元素提取效果,从而提供了一个通用且可复用的SV条件编译解析框架,以正确处理任意层级的嵌套条件编译结构,并通过回调机制将解析逻辑与元素收集逻辑解耦,使得同一套解析框架可以适用于宏定义提取、Include文件提取、组件变量提取和配置变量提取等多种不同的代码分析场景。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122963563A_ABST
    Figure CN122963563A_ABST
Patent Text Reader

Abstract

The present application relates to the technical field of integrated circuit design automation, and provides a universal code element extraction system, method and equipment for SV conditional compilation, which comprises a pre-compiled regular expression pattern library, a conditional state stack management mechanism module, a callback universal collection mechanism module, an annotation-aware preprocessing mechanism module and a segmented lookup extraction mechanism module, provides a universal and reusable SV conditional compilation analysis framework to correctly process any level of nested conditional compilation structure, and decouples the analysis logic from the element collection logic through a callback mechanism, so that the same set of analysis framework can be applied to macro definition extraction, Include file extraction, component variable extraction and configuration variable extraction and various different code analysis scenarios.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention belongs to the field of integrated circuit design automation (EDA) technology, and relates to a generalized code element extraction system, method and device for SV (SystemVerilog) conditional compilation. Background Technology

[0002] In chip design and verification, the SV language widely uses conditional compilation directives (such as `ifdef, `ifndef, `else, and `endif)`) to manage code differences between different project configurations, IP versions, and process nodes. For example, in MCU chip verification, the same set of verification code can control whether to enable the verification logic of a certain IP or whether to include test cases for a certain function through different macro definitions. However, existing code analysis tools only support single-level conditional compilation when handling conditional compilation. Most tools can only handle simple `ifdef...endif` structures and cannot correctly handle nested conditional compilation (i.e., one `ifdef` block contains another `ifdef` block). There is a lack of a general extraction framework; existing tools typically perform hard-coded parsing for specific types of code elements (such as extracting only macro definitions or only including files), lacking a general and reusable conditional compilation parsing framework. When different types of code elements need to be extracted, the parsing logic needs to be rewritten. Inadequate state management is another key challenge when handling nested conditional compilation. Existing tools typically use simple Boolean flags, which cannot correctly handle state recovery in nested scenarios. The lack of a callback-based collection mechanism means that existing tools often couple parsing logic and collection logic together, resulting in poor code reusability. Adding a new element type extraction requirement would necessitate a large amount of repetitive code.

[0003] Therefore, how to provide a general and reusable SV conditional compilation parsing framework to correctly handle nested conditional compilation structures at any level, and to decouple the parsing logic from the element collection logic through a callback mechanism so that the same parsing framework can be applied to various code analysis scenarios such as macro definition extraction, include file extraction, component variable extraction, and configuration variable extraction has become one of the urgent technical problems to be solved in current chip design and verification. Summary of the Invention

[0004] To address the problems existing in the aforementioned traditional technologies, this invention proposes a generalized code element extraction system, method, and device for SV conditional compilation. It can provide a general and reusable SV conditional compilation parsing framework to correctly handle nested conditional compilation structures at any level. Furthermore, it decouples the parsing logic from the element collection logic through a callback mechanism, enabling the same parsing framework to be applied to various code analysis scenarios such as macro definition extraction, include file extraction, component variable extraction, and configuration variable extraction.

[0005] To achieve the above objectives, the embodiments of the present invention adopt the following technical solutions: On the one hand, a generalized code element extraction system for SV conditional compilation is provided, including: A pre-compiled regular expression pattern library is used to centrally manage all regular expression patterns in a pre-deployed configuration management module. It employs a lazy compilation strategy to compile regular expressions only when used for the first time. The conditional state stack management mechanism module is used to manage the validity states of nested conditional compilations in SV conditional compilation in the chip verification environment using a conditional state stack. The callback-based general collection mechanism module is used to completely decouple the parsing logic of SV conditional compilation from the element collection logic, and pass the callback function as a parameter to the parser. The annotation-aware preprocessing module is used to call the annotation removal function before parsing each line of code under the control of conditional compilation directives to handle the setting of annotations; the setting of annotations includes single-line comments, multi-line comments, and conditional compilation directives in comments; The segmented search and extraction mechanism module is used to provide segmented search functionality for structured files in the chip verification environment.

[0006] In one embodiment, the signature of the callback function is: def collect_func(line: str)->Optional[T].

[0007] In one embodiment, the application of callback functions includes macro definition extraction, include file extraction, component variable extraction, configuration variable extraction, and conditional compilation include extraction.

[0008] In one embodiment, the patterns of the precompiled regular expression pattern library include ifdef, ifndef, else, endif, define, include, and component patterns.

[0009] In one embodiment, each element in the condition state stack is a Boolean value, representing the external condition state prior to entering the current nested level.

[0010] In one embodiment, the algorithm flow of the condition state stack management mechanism module includes: Initialization operations include initializing the set of defined macros, the condition state stack, the current condition state, and the list of collected results. Remove inline comments, skip blank lines, and match conditional compilation directives for each line of code under the control of the parsing conditional compilation directives; If the current condition is true, then call the callback function to collect elements; if the return value is not empty, then add it to the collection result list.

[0011] In one embodiment, in the condition state stack management mechanism module, when a conditional compilation instruction `ifdef` or `ifndef` is encountered, the current condition state is first pushed onto the condition state stack for storage, and then the current condition state is updated according to the macro definition. The processing of the `else branch does not change the stack structure of the condition state stack, but only flips the current condition state.

[0012] On the other hand, a generalized code element extraction method for SV conditional compilation is also provided, including the following steps: All regular expression patterns are centrally managed in a pre-deployed configuration management module using a pre-compiled regular expression pattern library, and a lazy compilation strategy is adopted to compile the regular expression on the first use. The conditional state stack management mechanism module is used to manage the validity states of nested conditional compilations in SV conditional compilation in the chip verification environment. The callback-based general collection mechanism module completely decouples the parsing logic of SV conditional compilation from the element collection logic, and passes the callback function as a parameter to the parser. The annotation-aware preprocessing module calls the annotation removal function before parsing each line of code under the control of conditional compilation directives to handle the setting of annotations; the setting of annotations includes single-line comments, multi-line comments, and conditional compilation directives in comments; The segmented search extraction mechanism module provides segmented search functionality for structured files in the chip verification environment.

[0013] On the other hand, a computer device is also provided, including a memory and a processor, wherein a computer program is stored in the memory, and the processor executes the computer program to implement the steps of the generalized code element extraction method for SV conditional compilation as described above.

[0014] One of the above technical solutions has the following advantages and beneficial effects: The aforementioned generalized code element extraction system, method, and device for SV conditional compilation includes a pre-compiled regular expression pattern library, a conditional state stack management mechanism module, a callback-based general collection mechanism module, an annotation-aware preprocessing mechanism module, and a segmented search extraction mechanism module. It saves and restores validity states layer by layer through the conditional state stack, ensuring that external conditions before entering a nested level are recorded and restored upon exiting the level, thus correctly handling nested conditional compilation at any level. Through callback decoupling, the same parsing framework can universally extract code elements of any type; adding new element types only requires adding callback functions without modifying the parser, demonstrating reusability and scalability. Annotation-aware preprocessing prevents misidentification of conditional compilation instructions in comments, ensuring accurate state judgment and collection results. Segmented search allows for independent parsing of different sections of the same file without interference. A centralized management mode and delayed compilation balance maintainability and parsing efficiency. The modules work closely together to achieve a general, reusable code element extraction effect that can correctly handle nested conditional compilation at any level. This provides a general and reusable SV conditional compilation parsing framework to correctly handle nested conditional compilation structures at any level. The parsing logic is decoupled from the element collection logic through a callback mechanism, so that the same parsing framework can be applied to a variety of different code analysis scenarios, such as macro definition extraction, include file extraction, component variable extraction, and configuration variable extraction. Attached Figure Description

[0015] To more clearly illustrate the technical solutions in the embodiments of the present invention or the conventional technology, the drawings used in the description of the embodiments or the conventional technology 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.

[0016] Figure 1 This is a block diagram of the module architecture of a general code element extraction system for SV conditional compilation in one embodiment; Figure 2 This is a schematic diagram of the overall architecture of the conditional compilation parsing framework in one embodiment; Figure 3 This is a schematic diagram illustrating the application of callback function polymorphism in one embodiment; Figure 4 This is a flowchart illustrating a generalized code element extraction method for SV conditional compilation in one embodiment. Detailed Implementation

[0017] To make the objectives, technical solutions, and advantages of this invention clearer, the invention will be further described in detail below with reference to the accompanying drawings and embodiments. It should be understood that the specific embodiments described herein are merely illustrative and not intended to limit the invention. Unless otherwise defined, all technical and scientific terms used herein have the same meaning as commonly understood by one of ordinary skill in the art to which this invention pertains. The terminology used in this specification is for the purpose of describing particular embodiments only and is not intended to limit the invention.

[0018] It should be noted that, in this document, the reference to "embodiment" means that a particular feature, structure, or characteristic described in connection with an embodiment may be included in at least one embodiment of the invention. The presentation of this phrase in various places throughout the specification does not necessarily refer to the same embodiment, nor is it a separate or alternative embodiment mutually exclusive with other embodiments. Those skilled in the art will understand that the embodiments described herein can be combined with other embodiments. The term "and / or" as used herein refers to any combination of one or more of the associated listed items, and all possible combinations, including such combinations.

[0019] The embodiments of the present invention will now be described in detail with reference to the accompanying drawings.

[0020] In one embodiment, such as Figure 1 As shown, a generalized code element extraction system 100 for SV conditional compilation is provided, which may include: The pre-compiled regular expression pattern library 11 is used to centrally manage all regular expression patterns in a pre-deployed configuration management module. It employs a lazy compilation strategy, compiling the regular expression only upon first use. The configuration management module, an internal component of the generalized code element extraction system 100 for SV conditional compilation, is responsible for centrally storing regular expression matching rules (acting as a rule repository, also called a regular expression pattern library). All regular expressions used in parsing (such as, but not limited to, ifdef, define, and include patterns) can be uniformly registered in the configuration management module. Each module can directly retrieve these patterns during parsing, avoiding rules scattered throughout the code. A regular expression is a pattern description used to match and extract text content. The lazy compilation strategy means that regular expression patterns are stored only as pattern strings during system initialization, and compilation only occurs when the pattern is first actually used for matching, thus avoiding unnecessary compilation overhead and improving parsing efficiency.

[0021] The condition state stack management mechanism module 13 is used in the chip verification environment to manage the validity states of nested conditional compilations in SV conditional compilation using a condition state stack (condition_stack). The condition state stack is a last-in-first-out stack data structure used to record the validity states of each nested level during the parsing process, thereby ensuring that the state before exiting a certain nested level can be correctly restored.

[0022] The callback-based general collection mechanism module 15 completely decouples the parsing logic of SV conditional compilation from the element collection logic, and passes a callback function (collect_func) as a parameter to the parser. A callback function is a function passed as a parameter to another program and called by that program at an appropriate time. The parsing logic is responsible for identifying conditional compilation directives and maintaining their validity, while the element collection logic is implemented by the callback function; the two are independent and do not depend on each other.

[0023] The comment-aware preprocessing module 17 calls the comment removal function (i.e., remove_comment(line, in_multi_comment)) before parsing each line of code controlled by conditional compilation directives to handle the setting of comments. The setting of comments includes single-line comments, multi-line comments, and conditional compilation directives in comments. By removing comments before parsing, it is possible to avoid the content in comments being misidentified as actual instructions.

[0024] The segmented search and extraction mechanism module 19 provides segmented search functionality for structured files in the chip verification environment. A structured file refers to a file containing multiple segments divided by markers, such as a definition file containing multiple variable sections. The segmented search function searches for a specific marker (e.g., / / Variable:module defines) as the start position of a segment and the next / / Variable: marker as the end position of the segment; it only performs conditional compilation parsing and element extraction on the code within the segment. This segmentation mechanism allows different segments of the same file to be parsed independently without interference.

[0025] It can be understood that this system belongs to the parsing technology of conditional compilation instructions in the SV hardware description and verification language. It is more suitable for the automated extraction and analysis of code elements controlled by conditional compilation instructions such as `ifdef`, `ifndef`, `else`, and `endif` in a chip verification environment. The overall architecture of the conditional compilation parsing framework is as follows: Figure 2 As shown, its top three main modules are the regular expression pattern library, the conditional state stack, and the comment remover. Other components include the core parsing engine (such as parsing logic), callback functions, and result lists. These components will be implemented / applied by the above modules respectively.

[0026] The pre-compiled regular expression pattern library 11 provides a unified pattern source for the conditional state stack management mechanism module 13, the comment-aware preprocessing mechanism module 17, and the segmented search and extraction mechanism module 19. The conditional state stack management mechanism module 13 is responsible for correctly maintaining the validity state under nested conditions, providing the correct judgment basis for subsequent element collection. The callback-based general collection mechanism module 15 calls a callback function to complete element collection when the validity state is true. The comment-aware preprocessing mechanism module 17 cleans up comments before entering parsing, ensuring the accuracy of the pattern matching results relied upon by the conditional state stack management mechanism module. The segmented search and extraction mechanism module 19 limits the parsing scope, ensuring that each segment's parsing does not interfere with each other. It is precisely because of the close collaboration between these modules that a general, reusable code element extraction effect capable of correctly handling arbitrary levels of nested conditional compilation is achieved.

[0027] The aforementioned generalized code element extraction system 100 for SV conditional compilation includes a pre-compiled regular expression pattern library 11, a conditional state stack management mechanism module 13, a callback-based general collection mechanism module 15, an annotation-aware preprocessing mechanism module 17, and a segmented search extraction mechanism module 19. It saves and restores validity states layer by layer through the conditional state stack, ensuring that external conditions before entering a nested level are recorded and restored upon exiting the level, thus correctly handling nested conditional compilation at any level. Through callback decoupling, the same parsing framework can universally extract code elements of any type; adding new element types only requires adding callback functions without modifying the parser, demonstrating reusability and scalability. Annotation-aware preprocessing prevents misidentification of conditional compilation instructions in comments, ensuring accurate state judgment and collection results. Segmented search allows different segments of the same file to be parsed independently without interference. A centralized management mode and delayed compilation balance maintainability and parsing efficiency. The modules work closely together to achieve a general, reusable code element extraction effect that can correctly handle nested conditional compilation at any level. This provides a general and reusable SV conditional compilation parsing framework to correctly handle nested conditional compilation structures at any level. The parsing logic is decoupled from the element collection logic through a callback mechanism, so that the same parsing framework can be applied to a variety of different code analysis scenarios, such as macro definition extraction, include file extraction, component variable extraction, and configuration variable extraction.

[0028] In one embodiment, the signature of the callback function is: def collect_func(line: str)->Optional[T], which defines a callback function named collect_func that takes a string parameter line (line represents the line of code currently being processed during the parsing process) and returns a value of type Optional[T], which is either "an instance of the generic parameter T" or "None". Furthermore, in the above signature, Optional[T] represents the return value as an instance of the generic parameter T or the null value None, that is, the union type of the generic parameter T and the null value None (equivalent to T|None). Here, the generic parameter T is used to indicate the specific type of the actual element to be extracted, such as a macro name string, a file name string, or a component variable name string, etc. The judgment logic is as follows: when the target element is successfully extracted from the row, the callback function returns the target element; when the row does not contain the target element, the callback function returns None to indicate that it does not participate in the collection. In this way, the parser is only responsible for calling the callback function row by row and judging whether the return value is null. The specific element to be extracted is determined by the callback function. That is, the same parsing logic can be adapted to callback functions that return different types of elements, achieving type safety, while ensuring the decoupling and reuse of parsing logic and element collection logic.

[0029] It is understandable that existing technologies lack a unified function interface convention for element collection, leading to unclear calling relationships between the parser and the collection function, making true decoupling and reuse difficult. In this embodiment, the signature of the callback function specifies that the callback function receives a string parameter `line`, which represents the current line of code to be parsed; the function's return type is `Optional[T]`, where `T` is a generic parameter. `Optional[T]` indicates that the function's return value can be either an instance of the type corresponding to the generic parameter `T` or a null value `None`. When the return value is not null, it indicates that a target element has been successfully extracted from the current line; when the return value is null, it indicates that the current line does not contain the target element and is not included in the collection.

[0030] This design offers the following advantages: Universality: The same set of conditional compilation parsing logic can be used to extract code elements of any type; Scalability: When adding a new element type, only a new callback function needs to be defined, without modifying the parser code; Type safety: Supports element extraction with different return types through the generic parameter T.

[0031] Through the above signature design, the callback function returns the extracted element object when a match is successful and an empty value when a match fails, thus establishing a one-to-one correspondence with the collection judgment conditions in the parsing logic. Because a generic parameter T is used, the same parsing logic can adapt to callback functions that return different element types, achieving the goal of type safety and avoiding errors that may be introduced due to inconsistent return types. This signature works closely with the conditional state judgment and result collection steps in Example 1, ensuring the standardization and consistency of the entire collection process.

[0032] In one embodiment, the application of callback functions includes macro definition extraction, include file extraction, component variable extraction, configuration variable extraction, and conditional compilation include extraction.

[0033] It is understandable that the types of elements to be extracted vary depending on the code analysis scenario. Writing separate parsing processes for each type would result in a large amount of repetitive code and high maintenance costs. In this embodiment, only different callback functions need to be defined for different extraction scenarios, while the parsing process remains unchanged.

[0034] Specifically, macro definition extraction uses callback functions that match the `define` pattern to extract the macro name; include file extraction uses callback functions that match the `include` pattern to extract the included file name; component variable extraction uses callback functions that match the `component` pattern to extract the component variable name; configuration variable extraction uses callback functions that parse the variable declaration line to extract the variable name; and conditional compilation include extraction uses callback functions that match the `include` pattern and filter file names by file extension. Specific application examples are shown in Table 1. Table 1 Application Examples

[0035] Callback function polymorphism application, such as Figure 3 As shown, the macro definition collection elements include A, B, and C; the include file collection elements include a.sv and b.sv; the compilation component collection elements include comp1 and comp2; collect_macro is the macro collection function; the header file collection function uses the callback function collect_Include; and the component variable collection function uses the callback function collect_var.

[0036] In this way, the same parsing framework can extract multiple element types by passing in different callback functions, which greatly improves code reusability. At the same time, adding a new extraction scenario only requires adding a new callback function, which demonstrates good scalability. Together with the generic signature design mentioned earlier, it further highlights the generalization value brought by the decoupling of parsing logic and collection logic.

[0037] In one embodiment, the patterns of the precompiled regular expression pattern library 11 include ifdef, ifndef, else, endif, define, include, and component patterns.

[0038] It is understandable that conditional compilation directives and various code elements have diverse syntax forms. If the pattern definitions are inconsistent or incomplete, it will lead to incomplete instruction recognition or incorrect matching. In this embodiment, the patterns of the pre-compiled regular expression pattern library 11 may specifically include: ifdef pattern: ^\s ifdef\s+(\w+)` — Matches the conditional compilation start instruction and extracts the macro name; ifndef pattern: ^\s ifndef\s+(\w+)` — This conditional compiler negates the start instruction of the compilation process and extracts the macro name. else pattern: ^\s else` — a conditional compiler branch switching instruction; endif pattern: ^\s `endif` is the directive that ends compilation when a matching condition is met. Define pattern: ^\s `define\s+(\w+)` — matches macro definition directives; include mode: ^\s include\s "["']" — Matches file inclusion instructions; Component pattern: ^\s ([\w_]+)\s+([\w_\[\]\$]+)\s ;—— Matches component variable declarations.

[0039] By defining the above patterns centrally and completely, the parser can accurately identify various conditional compilation directives and code elements, providing a reliable foundation for subsequent state maintenance and element collection. These patterns are centrally stored in the configuration management module and work in conjunction with the lazy compilation strategy, ensuring both accuracy and performance.

[0040] In one embodiment, each element in the condition state stack is a boolean value, representing the external condition state prior to entering the current nested level.

[0041] It is understandable that in nested conditional compilation scenarios, the validity of the current level depends on the validity of the outer level. If only a single Boolean flag is used to record the state, the correct historical state cannot be restored when exiting the nested level. In this embodiment, the conditional state stack uses Boolean values ​​as the element type, and each Boolean value records the external conditional state before entering the current nested level. When the external condition is true, the Boolean value pushed onto the stack is true; when the external condition is false, the Boolean value pushed onto the stack is false. By saving the external conditional state layer by layer in the form of a stack, the state before each level can be accurately restored when exiting each nested level.

[0042] In this way, the validity context of each level in nested conditional compilation can be fully expressed using simple Boolean values, which ensures the accuracy of state recording while maintaining low space overhead. This design is the direct basis for the correct state management of the conditional state stack management mechanism module 13.

[0043] In one embodiment, the algorithm flow of the condition state stack management mechanism module 13 includes: Initialization operations include initializing the set of defined macros, the condition state stack, the current condition state, and the list of collected results. Remove inline comments, skip blank lines, and match conditional compilation directives for each line of code under the control of the parsing conditional compilation directives; If the current condition is true, then call the callback function to collect elements; if the return value is not empty, then add it to the collection result list.

[0044] It is understandable that existing technologies lack a clear, complete, and reproducible parsing process to coordinate the relationship between conditional compilation instruction identification, validity state maintenance, and element collection. In this embodiment, the algorithm first performs initialization, including initializing the set of defined macros, the conditional state stack, the current conditional state, and the collection result list. Then, for each line of code controlled by the parsing conditional compilation instructions, inline comments are removed, blank lines are skipped, and then the conditional compilation instructions are matched. Finally, a judgment is made based on the current conditional state. If the current conditional state is true, a callback function is called to collect elements. If the callback function returns a non-empty value, the return value is added to the collection result list.

[0045] Specifically, the core algorithm flow of this conditional state stack management mechanism module 13 can be as follows: (1) Initialization operation: defined_set = set(defined_macros) / / A collection of defined macros condition_stack = [] / / Condition state stack current_condition = True / / Current condition status result = [] / / List of collected results.

[0046] (2) Then, for each line of code: 1. Remove inline comments (handle cross-line comment status); 2. Skip blank lines; 3. Matching conditional compilation directives: Matched `ifdef MACRO:` condition_stack.push(current_condition) / / Save external state current_condition = (MACRO in defined_set) / / Determine the current branch based on the macro definition Matched `ifndef MACRO:` condition_stack.push(current_condition) / / Save external state current_condition = (MACRO not in defined_set) / / Negative judgment Matched `else: current_condition = not current_condition / / Toggle the current state Matched `endif: current_condition = condition_stack.pop() / / Restore external state; 4. If current_condition == True: Call the callback function collect_func(line) to collect elements; If the return value is not None, add it to the results list.

[0047] By dividing the parsing process into three clear stages—initialization, line-by-line processing, and result collection—the entire extraction process becomes predictable, reproducible, and each stage has a single responsibility, making it easy to maintain and expand. Specifically, the processing order of removing comments before matching instructions, in conjunction with the comment-aware preprocessing mechanism module 17 mentioned above, ensures the accuracy of instruction matching; the callback function is only invoked when the current condition is true, guaranteeing the correctness of the collected results.

[0048] In one embodiment, in the condition state stack management mechanism module, when a conditional compilation instruction `ifdef` or `ifndef` is encountered, the current condition state is first pushed onto the condition state stack for storage, and then the current condition state is updated according to the macro definition. The processing of the `else branch does not change the stack structure of the condition state stack, but only flips the current condition state.

[0049] Understandably, in order to address the issues of correctly handling the three types of operations—entering a new level, switching branches, and exiting a level—under nested conditional compilation, and to avoid state overwriting and recovery errors, this embodiment also employs two key designs: nested state saving and restoration, and lazy handling of the else branch.

[0050] The nested state saving and restoration process works as follows: When encountering `ifdef` or `ifndef`, the current condition state `current_condition` is first pushed onto the condition state stack for storage. Then, the current condition state `current_condition` is updated according to the macro definition. This design is based on the fact that the current condition may already be within an outer conditional compilation block. If the outer condition is false, then regardless of the inner condition, the actual valid state should be false. Therefore, directly overwriting the current condition state `current_condition` without saving the outer state would prevent the outer condition from being restored in `endif`. Saving the outer state through the condition state stack and restoring it by popping it from the stack in `endif` ensures correctness in nested scenarios.

[0051] The lazy handling of the `else` branch means that the processing of the `else` branch adopts a lazy strategy: it does not change the stack structure, but only reverses the current condition state `current_condition`. This is because the hierarchical relationship between `else` and `endif` remains unchanged; only the validity of the current level is inverted. If the stack were manipulated at the `else` point, it would cause the subsequent `endif` to pop the wrong level.

[0052] By employing three mechanisms—pushing the stack to save the external state, popping the stack to restore the external state, and lazy flipping of the else branch—the correct maintenance of the validity state under conditional compilation at any level of nesting is ensured, fundamentally solving the problem of incorrect state restoration in nested scenarios in existing technologies.

[0053] Through the design of the above system, the following can be achieved: Hierarchical Documentation Generation: Automatically constructs a multi-level nested tree structure from class to phase to task / function, generating documentation that reflects the true hierarchical relationship of the code, facilitating code review and maintenance. Precise UVM (Universal Validation Methodology) Semantic Recognition: Accurately distinguishes UVM phases from ordinary tasks / functions using a dedicated uvm_phase regular expression (with the _phase suffix as a key feature), avoiding semantic confusion. Complete Multi-Line Declaration Parsing: Utilizes a bracket counter algorithm to correctly handle multi-line task / function declarations, including complex parameter lists and return types. Automatic Code Quality Check: Automatically detects modules lacking descriptive comments, generating warning reports, serving as an automated tool for code review. Cross-File Dependency Tracking: Automatically collects include file dependencies, recursively parses all related files, and builds a complete project documentation view.

[0054] In some implementations, application examples of the above system are also provided: Application Example 1: Macro definition extraction under nested conditional compilation. Assume the following SV code: / / Variable: module defines `define CHIP_A / / Define macro CHIP_A` `ifdef IP_X / / If the macro IP_X is defined, this branch will be entered` `define IP_X_V1 / / Define the macro IP_X_V1` `ifdef SUBSYS_Y / / If the macro SUBSYS_Y is defined, this branch will be entered.` `define SUBSYS_Y_EN / / Define the macro SUBSYS_Y_EN` `else / / Otherwise (if SUBSYS_Y is not defined) enter this branch` `define SUBSYS_Y_DIS / / Define the macro SUBSYS_Y_DIS` `endif / / End the SUBSYS_Y conditional compilation branch` `define IP_X_COMMON / / Define the macro IP_X_COMMON` `else / / Otherwise (if IP_X is undefined) enter this branch` `define IP_X_ABSENT / / Define the macro IP_X_ABSENT` `endif / / End the IP_X conditional compilation branch` `define CHIP_B / / Define the macro CHIP_B.

[0055] Input the list of defined macros: ["CHIP_A", "IP_X", "CHIP_B"] (where SUBSYS_Y is undefined), where "CHIP_A", "IP_X_V1", "SUBSYS_Y_DIS", "IP_X_COMMON", and "CHIP_B" are the names of each macro. The line-by-line parsing process is shown in Table 2. Table 2: Row-by-row parsing process

[0056] Final collection results: ["CHIP_A","IP_X_V1","SUBSYS_Y_DIS","IP_X_COMMON","CHIP_B"].

[0057] Application Example 2: Using the same parser for multiple element extraction tasks. Scenario A: Extracting Include files: def collect_include(line) / / Defines the callback function collect_include, where line is the line of code to be parsed. match = re.match(r'^\s `include\s ["\']([^"\']+)["\']', line) / / Use the include pattern to match the current line and extract the included filenames. return match.group(1) if match else None. / / Returns the filename of the included file if a match is successful, otherwise returns an empty value. Scenario B: Extracting component variables def collect_var(line): / / Defines the callback function collect_var, where line is the line of code to be parsed. match = re.match(r'^\s ([\w_]+)\s+([\w_\[\]\$]+)\s ;', line) / / Use the component pattern to match the current line and extract the component variable name return match.group(2) if match else None / / If the match is successful, return the component variable name; otherwise, return an empty value.

[0058] Scenario C: Extract include files with suffix filtering: def collect_filtered(line) / / Defines the callback function collect_filtered, where line is the line of code to be parsed. match = re.match(r'^\s `include\s ["\']([^"\']+)["\']', line) / / Use the include pattern to match the current line and extract the included filenames. if match: / / If a match is successful filename=os.path.basename(match.group(1)) / / Get the filename from the path of the included file. if filename.endswith(("_connect.sv", "_sw.sv")): / / If the filename ends with the specified suffix. return filename / / Returns the filename that matches the file extension. return None. / / Returns an empty value if the match fails or no file matches the condition.

[0059] The three scenarios above use the exact same conditional compilation parsing framework (ConditionalParser.parse_conditional() method), and only different callback functions are passed in to implement different extraction logic; where ConditionalParser represents the parser and parse_conditional() represents the entry function.

[0060] In summary, compared with existing technologies, the overall technical effects of the above technical solution can be summarized as follows: It can correctly handle nested conditional compilation at any level: Through a conditional state stack management mechanism, the external conditional state is saved when entering each nested level and restored when exiting the nested level. This ensures that when the external condition is false, the actual valid state is correctly determined to be false regardless of the internal condition, avoiding state management errors in nested scenarios. It possesses versatility and reusability: Through a callback-based universal collection mechanism, the parsing logic and element collection logic are completely decoupled. The same set of conditional compilation parsing logic can be used to extract code elements of any type, without needing to repeatedly write parsing logic for different element types. It has good scalability: When adding element types, only a new callback function needs to be defined, without modifying the parser code, significantly reducing the cost of expansion.

[0061] Type safety: Generic parameters support element extraction with different return types, improving code robustness and maintainability. Comment awareness: By calling a comment removal function before parsing each line of code, it correctly handles single-line comments, multi-line comments, and conditional compilation directives within comments, preventing keywords like `ifdef` in comments from being misinterpreted as actual instructions. Segmented search capability: It can segment structured files according to specific markers, performing conditional compilation parsing and element extraction only on the code within each segment, allowing different sections of the same file to be parsed independently without interference; it can extract include file information, providing basic data support for cross-file dependency tracking.

[0062] Each module in the aforementioned generalized code element extraction system 100 for SV conditional compilation can be implemented entirely or partially through software, hardware, or a combination thereof. These modules can be embedded in hardware or independently of a device with data processing capabilities, or stored in software within the memory of the aforementioned device, so that the processor can call and execute the operations corresponding to each module. The aforementioned device can be, but is not limited to, various types of computer devices already existing in the art.

[0063] In one embodiment, such as Figure 4 As shown, a generalized code element extraction method for SV conditional compilation is also provided, which may include the following processing steps S10 to S18: S10 uses a pre-compiled regular expression pattern library to centrally manage all regular expression patterns in a pre-deployed configuration management module, and adopts a lazy compilation strategy to compile regular expressions on the first use. S12, The conditional state stack management mechanism module is used to manage the validity state of nested conditional compilation in SV conditional compilation in the chip verification environment. S14 uses a callback-based general collection mechanism module to completely decouple the parsing logic of SV conditional compilation from the element collection logic, and passes the callback function as a parameter to the parser. S16, the annotation-aware preprocessing module calls the annotation removal function before parsing each line of code under the control of conditional compilation directives to handle the setting of annotations; the setting of annotations includes single-line comments, multi-line comments and conditional compilation directives in comments; S18, using the segmented search extraction mechanism module to provide segmented search functionality for structured files in the chip verification environment.

[0064] The aforementioned generalized code element extraction method for SV conditional compilation includes a pre-compiled regular expression pattern library, a conditional state stack management mechanism module, a callback-based general collection mechanism module, an annotation-aware preprocessing mechanism module, and a segmented search extraction mechanism module. It saves and restores validity states layer by layer through the conditional state stack, ensuring that external conditions before entering a nested level are recorded and restored upon exiting the level, thus correctly handling nested conditional compilation at any level. The callback decoupling allows the same parsing framework to extract code elements of any type; adding new element types only requires adding callback functions without modifying the parser, demonstrating reusability and scalability. Annotation-aware preprocessing prevents misidentification of conditional compilation instructions in comments, ensuring accurate state judgment and collection results. Segmented search allows different segments of the same file to be parsed independently without interference. A centralized management mode and delayed compilation balance maintainability and parsing efficiency. The modules work closely together to achieve a general, reusable code element extraction effect that can correctly handle nested conditional compilation at any level. This provides a general and reusable SystemVerilog conditional compilation parsing framework to correctly handle nested conditional compilation structures at any level. Through a callback mechanism, the parsing logic is decoupled from the element collection logic, so that the same parsing framework can be applied to a variety of different code analysis scenarios, such as macro definition extraction, include file extraction, component variable extraction, and configuration variable extraction.

[0065] In one embodiment, the application of callback functions includes macro definition extraction, include file extraction, component variable extraction, configuration variable extraction, and conditional compilation include extraction.

[0066] It is understood that the specific implementation of the above steps in this embodiment can be understood by referring to the corresponding explanations in the embodiments of the generalized code element extraction system 100 for SV conditional compilation, and will not be repeated here.

[0067] It should be understood that, although Figure 4 The steps are shown sequentially as indicated by the arrows, but these steps are not necessarily executed in the order indicated by the arrows. Unless otherwise specified in this document, there is no strict order in which these steps are executed; they can be performed in other orders. Figure 4 At least some of the steps may include multiple sub-steps or multiple stages. These sub-steps or stages are not necessarily executed at the same time, but can be executed at different times. The execution order of these sub-steps or stages is not necessarily sequential, but can be executed in turn or alternately with other steps or at least some of the sub-steps or stages of other steps.

[0068] In one embodiment, a computer device is also provided, including a memory and a processor, wherein a computer program is stored in the memory, and the processor executes the computer program to implement the steps of the generalized code element extraction method for SV conditional compilation as described above.

[0069] The technical features of the above embodiments can be combined in any way. For the sake of brevity, not all possible combinations of the technical features in the above embodiments are described. However, as long as there is no contradiction in the combination of these technical features, they should be considered to be within the scope of this specification.

[0070] The above embodiments merely illustrate several implementation methods of the present invention, and their descriptions are relatively specific and detailed, but they should not be construed as limiting the scope of protection of the invention. It should be noted that those skilled in the art can make various modifications and improvements without departing from the concept of the present invention, and all such modifications and improvements fall within the scope of protection of the present invention.

Claims

1. A generalized code element extraction system for SV conditional compilation, characterized in that, include: A pre-compiled regular expression pattern library is used to centrally manage all regular expression patterns in a pre-deployed configuration management module. It employs a lazy compilation strategy to compile regular expressions only when used for the first time. The conditional state stack management mechanism module is used to manage the validity states of nested conditional compilations in SV conditional compilation in the chip verification environment using a conditional state stack. The callback-based general collection mechanism module is used to completely decouple the parsing logic of SV conditional compilation from the element collection logic, and pass the callback function as a parameter to the parser. The annotation-aware preprocessing module is used to call the annotation removal function before parsing each line of code under the control of conditional compilation directives to handle the setting of annotations; the setting of annotations includes single-line comments, multi-line comments, and conditional compilation directives in comments; The segmented search and extraction mechanism module is used to provide segmented search functionality for structured files in the chip verification environment.

2. The generalized code element extraction system for SV conditional compilation according to claim 1, characterized in that, The signature of the callback function is: def collect_func(line: str)->Optional[T].

3. The generalized code element extraction system for SV conditional compilation according to claim 1 or 2, characterized in that, Callback functions are used for macro definition extraction, include file extraction, component variable extraction, configuration variable extraction, and conditional compilation include extraction.

4. The generalized code element extraction system for SV conditional compilation according to claim 3, characterized in that, The precompiled regular expression pattern library includes ifdef, ifndef, else, endif, define, include, and component patterns.

5. The generalized code element extraction system for SV conditional compilation according to claim 1, characterized in that, Each element in the condition state stack is a boolean value, representing the external condition state before entering the current nested level.

6. The generalized code element extraction system for SV conditional compilation according to claim 5, characterized in that, The algorithm flow of the condition state stack management mechanism module includes: Initialization operations include initializing the set of defined macros, the condition state stack, the current condition state, and the list of collected results. Remove inline comments, skip blank lines, and match conditional compilation directives for each line of code under the control of the parsing conditional compilation directives; If the current condition is true, then call the callback function to collect elements; if the return value is not empty, then add it to the collection result list.

7. The generalized code element extraction system for SV conditional compilation according to claim 6, characterized in that, In the condition state stack management mechanism module, when encountering the condition compilation directive `ifdef` or `ifndef`, the current condition state is first pushed onto the condition state stack for storage, and then the current condition state is updated according to the macro definition. The processing of the `else branch does not change the stack structure of the condition state stack, but only flips the current condition state.

8. A generalized code element extraction method for SV conditional compilation, characterized in that, Including the following steps: All regular expression patterns are centrally managed in a pre-deployed configuration management module using a pre-compiled regular expression pattern library, and a lazy compilation strategy is adopted to compile the regular expression on the first use. The conditional state stack management mechanism module is used to manage the validity states of nested conditional compilations in SV conditional compilation in the chip verification environment. The callback-based general collection mechanism module completely decouples the parsing logic of SV conditional compilation from the element collection logic, and passes the callback function as a parameter to the parser. The annotation-aware preprocessing module calls the annotation removal function before parsing each line of code under the control of conditional compilation directives to handle the setting of annotations; the setting of annotations includes single-line comments, multi-line comments, and conditional compilation directives in comments; The segmented search extraction mechanism module provides segmented search functionality for structured files in the chip verification environment.

9. The generalized code element extraction method for SV conditional compilation according to claim 8, characterized in that, Callback functions are used for macro definition extraction, include file extraction, component variable extraction, configuration variable extraction, and conditional compilation include extraction.

10. A computer device, comprising a memory and a processor, wherein the memory stores a computer program, characterized in that, When the processor executes the computer program, it implements the steps of the generalized code element extraction method for SV-oriented conditional compilation as described in claim 8 or 9.