A method and apparatus for generating code from a sysml model
By extending the semantics and hierarchical converter technology of SysML models, the problems of lack of architecture and dynamic behavior support in the conversion of SysML models to code are solved, realizing high-quality and reliable code generation and error tracing, and improving the development efficiency and quality of complex system software.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- ZHEJIANG UNIV
- Filing Date
- 2026-03-19
- Publication Date
- 2026-07-03
Smart Images

Figure CN121879754B_ABST
Abstract
Description
Technical Field
[0001] This invention belongs to the field of model-driven development technology, specifically relating to a method and apparatus for generating SysML models into code. Background Technology
[0002] Modern systems (such as aerospace systems, intelligent vehicles, and medical devices) are typically complex organic wholes integrating mechanics, electronics, software, information, and control. These systems consist of multiple highly coupled subsystems, which are themselves components of a larger system. To address this complexity, systems engineering, as a comprehensive discipline, provides a scientific methodology to guide the design, analysis, management, and verification of systems. However, in traditional document-based systems engineering, system requirements, design, analysis, and verification information are scattered across numerous text reports, drawings, and tables, resulting in inconsistencies, difficulties in traceability, and many other drawbacks. Therefore, Model-Based Systems Engineering (MBSE) has emerged, offering advantages such as unambiguous knowledge representation, ease of communication and dissemination, support for information transformation, and support for model integration.
[0003] In MBSE (System Modeling Society), all information during the system design and development process is represented by models, making system-level modeling a major research issue. To this end, the Society for Systems Engineering and the Object Management Group jointly developed the Systems Modeling Language (SysML). SysML is a general-purpose, graphical modeling language that extends from the Unified Modeling Language and has been customized and simplified for the needs of systems engineering. Through its nine main graphical primitives—module definition diagrams, internal module block diagrams, activity diagrams, state machine diagrams, sequence diagrams, etc.—SysML provides powerful and comprehensive support for describing the structure, behavior, requirements, and parameters of complex systems.
[0004] While SysML models provide precise and unambiguous design blueprints at the system level, their true engineering value must ultimately be realized through conversion into executable software code. However, current practices for converting SysML models to code suffer from significant bottlenecks, severely hindering the full realization of MBSE's effectiveness. Existing conversion processes often lack rigorous, layered architectural design. This leads to insufficient model validation, unreliable conversion processes, and difficulty in guaranteeing the quality of generated code. Furthermore, when conversion errors occur, it is impossible to effectively pinpoint the problem back to the corresponding element in the source model, increasing the difficulty of debugging and maintenance. Moreover, existing methods often rely on simple structural mapping rules (such as mapping modules to classes), resulting in generated code that is mostly "skeleton" code lacking business logic. These methods struggle to handle deep semantic mismatches between SysML models and target programming languages (such as C++), such as the lack of support for key language features like concurrency, memory management, virtual functions, friend relationships, and type modifiers, resulting in low usability of the generated code and requiring significant manual coding. Furthermore, existing code generation provides very weak or no support for key views that define the dynamic behavior of a system, such as state machines and activity diagrams, making it difficult to automatically convert complex control flows and state transition logic into equivalent, executable program logic.
[0005] Therefore, researching and developing a transformation framework that can deeply understand the semantics of SysML models, support layered architecture design, and automatically generate high-quality executable code has become the key to breaking through the bottleneck of MBSE application and realizing the full-process digitalization of systems engineering. Summary of the Invention
[0006] In view of the above, the purpose of this invention is to provide a method and apparatus for generating SysML model to code. Through model semantic expansion, instantiation verification based on unique identifier, syntax tree mapping and verification, and code filling process, it realizes the automated generation of high-quality, executable code from SysML design model and accurate traceability of errors throughout the process. It is suitable for complex engineering application scenarios with stringent requirements for system reliability and development consistency, such as aerospace and intelligent vehicles.
[0007] To achieve the above-mentioned objectives, the present invention provides the following technical solution:
[0008] In a first aspect, the present invention provides a SysML model-to-code generation method, comprising the following steps:
[0009] Extend the SysML model by adding the target code generation configuration parameters and the semantic structure of the target programming language to the model semantics;
[0010] The extended SysML model is parsed, a repository of model element instances containing model element instances and their relationships is constructed, and the validity of the model element instances is validated according to the SysML specification.
[0011] The converter executes conversion rules based on the type of the model element instance, converting the validated model element instance into a code syntax tree node, thus obtaining the abstract syntax tree of the target programming language;
[0012] The abstract syntax tree is semantically and syntactically validated. Once validated, the node information is extracted and used as context data to input into the template engine. The final executable code is generated by filling in the preset code template.
[0013] Preferably, the target code generation configuration parameters and the semantic structure of the target programming language are supplemented into the model semantics, including:
[0014] The SysML model is extended by defining the target code generation configuration parameters and the semantic structure of the target programming language through SysML stereotypes. The target code generation configuration parameters include at least one or more of the following: target code type, code file storage location, conversion of target model element instances, and whether to automatically generate property accessors. The semantic structure of the target programming language includes at least one or more of the following model elements that cover code semantics: friend functions, virtual functions, and type modifiers of the target programming language.
[0015] Preferably, the validation of model element instances according to the SysML specification includes:
[0016] Based on the model element instance repository, and in accordance with the model attribute constraints and model relationship constraints defined in the SysML specification, the static semantic integrity of the model element instances is verified, and in accordance with the executable unified modeling language constraints defined in the SysML specification, the behavioral semantic executability of the model element instances is verified.
[0017] During the verification process, each model element instance is assigned a unique identifier, InstanceID, to enable precise location of the verification results and backtracking to the specific element instance in the source SysML model.
[0018] Preferably, the step of converting validated model element instances into code syntax tree nodes by executing conversion rules based on the type of the model element instance through the converter includes:
[0019] Set up a converter factory to create and call the corresponding converter according to the type of the model element instance. The converter includes at least a structural model converter, a behavioral model converter and its sub-converters.
[0020] The structure model converter is used to map the structure element instances in the model to the syntax tree nodes corresponding to the structure types in the target programming language, so as to generate code skeletons;
[0021] The behavior model converter is used to map the behavioral logic element instances in the model to the syntax tree nodes corresponding to the function execution flow in the target programming language, so as to generate executable business logic code syntax tree nodes.
[0022] The sub-converter is used to perform fine-grained, type-based, and precise conversion of model element instances under the structural model converter and the behavioral model converter.
[0023] Preferably, when the behavior model converter performs activity graph mapping, it generates target code block syntax tree nodes that are logically equivalent to the activity model element instances by identifying the topological relationship between control nodes and action nodes based on the semantic parsing of the activity model element instances. The code blocks include loop, conditional, or concurrent code blocks.
[0024] When performing state machine diagram mapping, the behavior model converter, based on a pre-built runtime state management framework, transforms instances of state, transition, and behavioral semantic elements in the SysML state machine diagram into executable logic code syntax tree nodes for the target programming language. The runtime state management framework includes state classes for encapsulating state node information and their associated behavioral logic, and region classes for encapsulating multiple mutually exclusive state class instances and managing the transition logic between the state class instances.
[0025] Preferably, the method further includes constructing a communication channel, including:
[0026] A predefined active object framework base class is defined, which encapsulates communication mechanisms including thread execution, message queues, event dispatch, and event handling. When the converter recognizes the interaction or event semantics in the model element instance, it converts them into the corresponding message structure and message routing code syntax tree nodes, thereby constructing a message-based asynchronous communication data path between threads.
[0027] Preferably, the semantic and syntactic verification of the abstract syntax tree includes:
[0028] Based on the syntax and semantic rules of the target programming language, traverse the abstract syntax tree to check the semantic integrity of its type definitions, variable declarations, and control flow.
[0029] When an error or missing element is detected, an error message is generated and the error information is traced back to the corresponding model element instance in the source SysML model.
[0030] Secondly, embodiments of the present invention also provide a SysML model-to-code generation apparatus, implemented using the aforementioned SysML model-to-code generation method, comprising: a model extension module, a model parsing module, a model conversion module, and a code generation module;
[0031] The model extension module is used to extend the SysML model by adding the target code generation configuration parameters and the semantic structure of the target programming language to the model semantics.
[0032] The model parsing module is used to parse the extended SysML model, build a repository of model element instances containing model element instances and their relationships, and perform validity checks on the model element instances according to the SysML specification.
[0033] The model conversion module is used to convert the validated model element instances into code syntax tree nodes by executing conversion rules according to the type of the model element instances through the converter, thereby obtaining the abstract syntax tree of the target programming language.
[0034] The code generation module is used to perform semantic and syntactic verification on the abstract syntax tree. After the verification is successful, the node information is extracted as context data and input into the template engine. The final executable code is generated by filling in the preset code template.
[0035] Thirdly, embodiments of the present invention also provide an electronic device, including a memory and one or more processors, wherein the memory is used to store a computer program, and the processor is used to implement the above-described SysML model-to-code generation method when the computer program is executed.
[0036] Fourthly, embodiments of the present invention also provide a computer-readable storage medium storing a computer program, which, when executed by a computer, implements the above-described SysML model-to-code generation method.
[0037] Compared with the prior art, the beneficial effects of the present invention include at least the following:
[0038] This invention extends the semantics of SysML models and establishes a full-process traceability mechanism based on a unique instance identifier (InstanceID), achieving precise mapping and error localization from model elements to code nodes. By designing a layered, fine-grained converter (including structure, behavior, and communication channels), it not only generates a code skeleton but also transforms dynamic behavioral semantics such as concurrency and state machines into executable logic, significantly improving the completeness and usability of the generated code. By performing executability checks on the model at both the structural and behavioral levels before conversion, the correctness and reliability of the generated code are ensured. Ultimately, this method outputs high-quality, directly usable foundational code for further development, effectively reducing the development burden and improving the development efficiency and quality of complex system software. Attached Figure Description
[0039] To more clearly illustrate the technical solutions in the embodiments of the present invention or the prior art, the drawings used in the description of the embodiments or the prior art will be briefly introduced below. Obviously, the drawings described below are only some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.
[0040] Figure 1 This is a flowchart illustrating a SysML model-to-code generation method provided in an embodiment of the present invention;
[0041] Figure 2 This is a schematic diagram of a reusable state machine runtime management framework provided in an embodiment of the present invention;
[0042] Figure 3 This is a schematic diagram of the off, start, running, and fault states in the engine working mode state diagram of the engine control module provided in the embodiment of the present invention;
[0043] Figure 4 This is a schematic diagram of the active object framework provided in an embodiment of the present invention;
[0044] Figure 5 This is a schematic diagram of the structure of a SysML model-to-code generation device provided in an embodiment of the present invention. Detailed Implementation
[0045] 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 of the invention and do not limit the scope of protection of this invention.
[0046] The inventive concept of this invention is as follows: Addressing the problems in existing SysML model-to-code conversion technologies, such as a lack of rigorous architecture, generated code often consisting of skeletons lacking business logic, difficulty in supporting dynamic behavior, and the inability to trace errors back to the source model, this invention provides a method and apparatus for generating SysML model-to-code. By using model element instances drawn by a visual modeling tool as input, the method first performs semantic expansion and instantiation, verifying the standardization of the model element instances. Then, based on refined mapping rules, the SysML model elements are converted into abstract syntax tree nodes of the target code, and the generated syntax tree is further verified. While ensuring semantic and syntactic correctness, the template context is obtained based on the information stored in the nodes of the syntax tree, and the template engine is activated to populate the template, ultimately resulting in high-quality, executable target code. This invention achieves accurate and reliable conversion from model to code by establishing a full-process bidirectional traceability mechanism.
[0047] like Figure 1 As shown, this embodiment provides a method for generating code from a SysML model. Taking an automotive engine control module as an example, it generates code from numerous SysML model elements using a visual modeling tool, a validator, a mapping engine, and a template engine. The specific steps include:
[0048] S1 extends the SysML model by adding the target code generation configuration parameters and the semantic structure of the target programming language to the model semantics.
[0049] In this embodiment, a visual modeling tool is used to create models according to requirements, including module definition diagrams, internal module diagrams, activity diagrams, state machine diagrams, and sequence diagrams. Each view directly displays model element instances, instance components, and relationships between instances. For example, a module instance is an engine control module, which internally defines attributes such as current engine speed, current throttle position, cooling temperature, and operating mode, and has a one-to-many relationship with ignition coils and sensors.
[0050] Configure the target code generation parameters, including setting the target code type, specifying the file storage location, specifying the target model element instance, and checking whether to automatically generate attribute accessors, among other generation parameters.
[0051] At the same time, the semantic structure of the target programming language is set, including model elements that cover code semantics, such as friends, virtual functions, and type modifiers of the target programming language (e.g., C++), to supplement the programming language semantics not covered by standard SysML at the model level.
[0052] S2 parses the extended SysML model, constructs a repository of model element instances containing model element instances and their relationships, and performs validity checks on the model element instances according to the SysML specification.
[0053] In this embodiment, the extended SysML model is obtained and parsed, and a model element instance repository containing model element instances and their associated relationships is constructed.
[0054] To standardize user modeling behavior and generate correct executable code, the validity of user-created model element instances (engine control module) is first validated. Based on the model attribute constraints and model relationship constraints defined in the SysML specification, the static semantics of the model are validated to ensure the semantic integrity of the model instances. Based on the executable unified modeling language constraints, the behavioral semantics of the model are validated to ensure that the model meets the execution requirements. Model instances that fail validation are located using their InstanceID and are populated with default values; if population is not possible, an error message is displayed to the user, prompting them to make modifications.
[0055] Static semantics refers to whether the definitions of model elements themselves and their interrelationships satisfy the syntax and structural rules of the Unified Modeling Language. This validation includes checking whether the attribute definitions of model elements are complete and of valid types based on model attribute constraints. For example, for the current speed attribute of the engine control module, the validator will check whether its data type (such as integer) has been explicitly defined. If the attribute lacks a type definition, the validator will locate the element based on InstanceID and report an error to the user: "Speed attribute data type not defined". This validation also includes checking whether the associations, generalizations, and other relationships between model elements are correctly defined and logically consistent based on model relationship constraints. For example, when validating the "one-to-many" association between the engine control module and the ignition coil, it will check whether the multiplicity at both ends of the association has been correctly defined (e.g., engine control end is 1, ignition coil end is 1..*).
[0056] In this context, behavioral semantics refers to whether the semantic elements of the system dynamic process (such as state transitions and activity flows) described by the model are complete and conform to logical rules. This verification mainly relies on the constraints of the Executable Unified Modeling Language (FUML) and focuses on the completeness and unambiguity of the behavioral model. For example, verifying the main control loop activity diagram checks whether each action node (such as "calculate fuel injection quantity") has clear input and output values.
[0057] S3, through the converter, executes conversion rules based on the type of the model element instance, converting the validated model element instance into a code syntax tree node, and obtaining the abstract syntax tree of the target programming language.
[0058] In this embodiment, a converter factory is activated to create corresponding converters based on the types of different model element instances (e.g., engine control module, current speed attribute, ignition coil association, main control loop activity). Each converter contains mapping logic to convert different model instances into specific abstract syntax tree nodes and populate the target language syntax element information covered by the nodes (e.g., engine control module → engine class declaration node, current speed attribute → speed variable declaration node in the engine class). For static semantic models, memory management-related syntax semantics are automatically mapped based on the relationships between elements. For behavioral semantic models, special mapping rules are established, an executable framework is designed according to semantics, an event handling framework is defined based on concurrency and event notification, and concurrency semantics and inter-model communication mapping rules are supplemented. Target code blocks equivalent to the model logic are generated based on the internal topological relationships of the behavioral model. Specifically, state machine diagram code generation has a complex state transition mechanism, generating executable state machine code based on state information triggering transition conditions.
[0059] Specifically, the converter is divided into a structural model converter (engine control module), a behavioral model converter (main control loop activity, engine working mode state machine) and its sub-converters. It generates abstract syntax tree nodes by judging all related instances of SysML model element instances based on the InstanceID marked by SysML element instance. The instance type is determined by the mapping relationship between SysML model elements and target language.
[0060] The structural model converter maps elements representing model structure information, such as modules, interfaces, signals, value types, operations, generalizations, and associations, with modules being its core processing object. The converter not only maps modules to classes, but more importantly, it handles the internal structure of modules, enabling deep nesting mappings of their sub-modules, ports, and attributes. This generates a hierarchical, modular code structure, rather than a flat list of code. The converter accurately handles logical relationships between modules, such as generalizations and associations. For generalizations, it generates inheritance code with keywords like `public virtual` (indicating public virtual inheritance), correctly reflecting the object-oriented design intent. For associations, it automatically introduces appropriate container classes (such as `std::vector`, a container class in the C++ Standard Template Library) based on the multiplicity of the associated elements (e.g., `1..*`, indicating the possible association of multiple elements of the same type, allowing values from 1 to infinity), ensuring that structural constraints in the model are fully mapped in the code. Interfaces, serving as the core description of the interaction contract between system components, are mapped to abstract classes. The converter losslessly transforms each operation defined in the interface into an abstract function in the target language (such as a pure virtual function in C++), providing a precise contract for subsequent code generation of the behavioral model and ensuring consistency in interactions between system components. Value types and signals defining the system's core data structures are mapped to structures in the target language to carry and transmit data information. Value types are mapped to strongly typed structures, precisely encapsulating the data's name, type, and value range, ensuring semantic consistency and type safety when data is transmitted between different parts of the system. Signals are mapped to message body structures with specific communication semantics, encapsulating specific types of communication data and possessing global visibility, used to implement asynchronous communication in the generated code for data communication between different objects.
[0061] The behavior model converter is responsible for converting key views in SysML that describe the dynamic behavior of a system, including activity diagrams, state machine diagrams, and sequence diagrams, along with their sub-attribute elements expressing behavioral logic and control flow, into executable behavioral code. The behavior model converter not only implements direct syntactic mapping of behavior model elements, but more importantly, it intelligently injects the necessary execution semantic code to ensure that the generated behavioral logic runs correctly and efficiently in the target environment. For example, in the conversion of a state machine (engine operating mode state machine), to ensure that the generated code accurately executes the behavioral logic expressed by the state diagram, the converter does not simply generate state names, but uses a predefined state management framework as a base class, such as... Figure 2As shown, this framework adopts an object-oriented design pattern to systematically encapsulate the semantic elements of SysML state diagrams, such as states, regions, and historical nodes, at runtime to support precise state transitions and behavior management. The core components of this framework are state classes and region classes. The core attributes of the state class include an identifier, a list of contained sub-regions, whether it is active, its parent state, its region, and its context. The identifier indicates the uniqueness of the state. The list of contained sub-regions stores and manages concurrent sub-regions within that region, which is the core data structure supporting orthogonal state semantics in SysML state machines. The active attribute identifies whether the region itself is currently in a logically active state, serving as a key basis for coordinating parent-child state activation and event-driven state transitions. The parent state identifies the upper-level state of this state in the state hierarchy. The context identifies the object in which the state machine runs (such as the engine control class mentioned above). The core methods of the state class include checking and notifying state completion, entering a state sub-region, obtaining the parent state, obtaining a sub-region based on the identifier, whether it is active, whether it is complete, entering a state, exiting a state, entering deep history, entering shallow history, and event handling. The "Check and Notify State Completion" function monitors the internal activity state in the generated executable code and automatically sends a state completion event to the execution context upon state completion, thereby driving the state transitions defined in the original state diagram. "Enter State Sub-region" automatically executes the logic flow for initializing and entering the internal sub-regions after state activation in the generated code. "Get Parent State" retrieves the parent state of the current state after code generation. "Get Sub-region by Identifier" retrieves a specific sub-region in the generated code. "Activation Status" determines the activation status of the runtime state in the generated execution. "State Entry" activates and executes the behavior sequence defined in the model when entering a specific state. "State Exit" executes the behavior sequence defined in the model when exiting a state. "Deep History Entry" and "Shallow History Entry" implement the historical semantics of the SysM state diagram, implementing different recovery methods for internal sub-states when a composite state is re-entered in the generated code. "Event Handling" is the unified entry point for state responses to specific events. It matches and judges based on state configuration, executes event-related behavior logic, or triggers state transitions. The specific response logic corresponding to a specific state is overridden in the specific state class.
[0062] In this embodiment, the behavior model converter generates a state class (e.g., ...) for each state in the state diagram. Figure 3As shown in the state diagram of the engine operating mode under the engine control module (off, start, running, and fault states), the generated states inherit from the state classes in the state management framework. Based on the specific behavioral logic defined by the user for each state in the state diagram, the state entry, state exit methods, and event handling methods of the state base class are overridden. For example, the state entry method for the start state is overridden to generate code that starts the fuel pump and initializes the fuel line pressure. The event handling method for the off state is overridden to respond to the ignition event and determine whether the conditions for transitioning from off to start are met, thus driving the transition from the off state to the start state. Simultaneously, state diagram initialization code is generated based on the state hierarchy defined in the state diagram. This maps data such as state identifiers, regions, and parent state relationships in the model to explicit diagram-building statements in the code. For example, if a rotating mode region of a running composite state contains high-speed rotating states and low-speed rotating states, the generated code will contain statements such as declaring running state objects, declaring rotating mode region objects, declaring high-speed rotating state objects, adding rotating mode sub-regions to running states, adding high-speed and low-speed rotating sub-states to rotating mode region objects, and setting the regions of high-speed and low-speed rotating state objects to rotating mode region objects. This establishes a state hierarchy that is completely consistent with the model at runtime.
[0063] By injecting extended code, the generated state machine code possesses complete event-driven and state-switching capabilities, enabling precise execution of the workflow and state transitions defined by the model. In addition to deep extended mapping of the behavioral elements themselves, the behavior model converter analyzes and synthesizes execution paths. The converter performs static analysis on the control flow of the behavior model, especially the activity graph, identifying independent and concurrent execution paths (main control loop activities) composed of nodes such as branches, decisions, merges, and loops. It efficiently maps complex control logic into corresponding conditional branch statements, loop structures, and concurrent threads (engine control loop code blocks) in the target language. Therefore, it avoids generating redundant or rigid code, allowing the target code to better conform to actual coding standards and performance requirements, significantly improving the readability, maintainability, and execution efficiency of the generated code.
[0064] Specifically, to handle composite models with both complex structures and dynamic behaviors, this invention introduces a behavior-structure fusion mapping mechanism. This mechanism can automatically identify active modules that internally encapsulate classifier behaviors. For such modules, the converter not only generates passive data structures but also inherits from a predefined, generic active object framework base class. Figure 4As shown, the system integrates components such as active classes, reactive classes, timers, signal events, timeout events, and the main thread class. The active class includes an event queue, queue mutex, condition variables, and an execution thread, supporting execution, event enqueueing, and dispatching. The reactive class provides methods for initiating main behaviors, handling events, and sending events; it is used to initiate converted behavior methods, handle events sent by the active class, and send events generated during its own runtime into the event queue. The timer generates time events, internally maintaining a time event queue and a dedicated worker thread. It achieves precise scheduling and triggering through condition variables and runtime flags, supporting both single timeouts and periodic time events. For example, if the engine control module is set to active and internally encapsulates a complete working state diagram and main control loop, the generated object, after being recognized by the converter, will inherit the characteristics of both the active and reactive classes. The generated engine control object will be instantiated as an independent system thread at runtime, with the main control loop serving as the execution body of this thread. Signal interactions between the engine control module and the transmission control module (such as shift request signals) generate specific message structures (e.g., `struct ShiftRequestMsg`, a C++ structure named "Automotive Shift Request Signal"), and convert signal sending and receiving into asynchronous message delivery and event handling via message queues. This predefined framework encapsulates the core capabilities of concurrent execution and asynchronous communication. By inheriting from this framework, these composite models are instantiated as independent execution threads or tasks during code generation. Their internal behavioral logic, such as state machine state transitions and activity action flows, will be driven to execute within their respective thread contexts. Furthermore, the framework provides a message queue-based communication infrastructure, thereby mapping interactions such as port or signal sending between modules in the SysML model to thread-safe, non-blocking asynchronous message passing.
[0065] Furthermore, under the top-level design of the structural model converter and the behavioral model converter, fine-grained and type-specific precise conversions of model element instances are performed through sub-converters. Specific functions of the sub-converters include: a type declaration sub-converter, used to convert elements such as classes, interfaces, and enumerations into corresponding type definition nodes; a member sub-converter, used to convert attributes and operations into field declarations and method signature nodes; a relation sub-converter, used to convert relationships such as association and generalization into code structures such as inheritance and composition; a behavioral sub-converter, used to convert elements such as actions and calls into statement nodes; and a control flow sub-converter, used to convert elements such as decisions and loops into control flow statement nodes such as conditionals and loops.
[0066] S4 performs semantic and syntactic verification on the abstract syntax tree. After successful verification, it extracts node information as context data and inputs it into the template engine. The final executable code is generated by filling in the preset code template.
[0067] In this embodiment, the transformed abstract syntax nodes are systematically constructed into a complete abstract syntax tree according to the syntax rules of the target language, and then sent to a code validator for static verification and quality assessment. This process deeply checks the completeness and correctness of the generated code elements. The validator verifies the legality of the syntax tree structure based on the syntax and semantic rules of the target language, such as checking type matching, function call conformity, and scope rule compliance. It also checks whether all necessary syntactic elements of the model elements are included, such as complete class member declarations or conditional branch structures. When the validator detects a defect, such as a missing syntax element due to mapping failure, it performs error tracing, locating the error position in the syntax tree back to the specific element in the SysML model based on the InstanceID. Clear diagnostic information is generated for the user, such as modules without names or attributes without defined types.
[0068] The validated syntax tree data is used to construct the template context. Based on the element type of the execution target, a suitable template is selected from the template library. The specific information contained in the syntax tree nodes, such as attribute names, type names, and parameter lists, is then populated into the corresponding placeholders in the template. For complex structures, the engine supports recursive filling and template nesting. For example, when filling a class template, it recursively generates and fills the corresponding function templates for each of its member methods, assembling them into a complete class definition. The final output is a code file that can be directly used by the compiler or development environment.
[0069] Based on the same inventive concept, such as Figure 5 As shown, this embodiment of the invention also provides a SysML model-to-code generation device 500, including: a model extension module 510, a model parsing module 520, a model conversion module 530, and a code generation module 540.
[0070] The model extension module 510 is used to extend the SysML model by adding the target code generation configuration parameters and the semantic structure of the target programming language to the model semantics.
[0071] The model parsing module 520 is used to parse the extended SysML model, build a repository of model element instances containing model element instances and their relationships, and perform validity checks on the model element instances according to the SysML specification.
[0072] The model conversion module 530 is used to convert the validated model element instances into code syntax tree nodes by executing conversion rules based on the type of the model element instances through the converter, thereby obtaining the abstract syntax tree of the target programming language.
[0073] The code generation module 540 is used to perform semantic and syntactic verification on the abstract syntax tree. After the verification is successful, the node information is extracted as context data and input into the template engine. The final executable code is generated by filling in the preset code template.
[0074] Based on the same inventive concept, embodiments of the present invention also provide an electronic device, including a memory and one or more processors, wherein the memory is used to store a computer program, and the processor is used to implement the above-described SysML model-to-code generation method when the computer program is executed.
[0075] Based on the same inventive concept, embodiments of the present invention also provide a computer-readable storage medium storing a computer program, which, when executed by a computer, implements the above-described SysML model-to-code generation method.
[0076] It should be noted that the SysML model-to-code generation apparatus, electronic device, and computer-readable storage medium provided in the above embodiments all belong to the same inventive concept as the SysML model-to-code generation method. For details of their specific implementation process, please refer to the SysML model-to-code generation method embodiments, which will not be repeated here.
[0077] The specific embodiments described above illustrate the technical solution and beneficial effects of the present invention in detail. It should be understood that the above description is only the most preferred embodiment of the present invention and is not intended to limit the present invention. Any modifications, additions, and equivalent substitutions made within the scope of the principles of the present invention should be included within the protection scope of the present invention.
Claims
1. A method for generating code from a SysML model, characterized in that, Includes the following steps: Extend the SysML model by adding the target code generation configuration parameters and the semantic structure of the target programming language to the model semantics; The extended SysML model is parsed, a repository of model element instances containing model element instances and their relationships is constructed, and the validity of the model element instances is validated according to the SysML specification. The converter executes conversion rules based on the type of model element instances, converting validated model element instances into code syntax tree nodes to obtain the abstract syntax tree of the target programming language. This includes: setting up a converter factory; creating and calling corresponding converters based on the type of model element instances; each converter including at least a structural model converter, a behavioral model converter, and its sub-converters; the structural model converter maps structural element instances in the model to syntax tree nodes corresponding to structural types in the target programming language to generate a code skeleton; the behavioral model converter maps behavioral logic element instances in the model to syntax tree nodes corresponding to function execution flows in the target programming language to generate executable business logic code syntax tree nodes; and the sub-converters perform fine-grained, type-based, and precise conversions of model element instances under the structural model converter and the behavioral model converter. Specifically, when performing activity graph mapping, the behavior model converter generates logically equivalent target code block syntax tree nodes by identifying the topological relationship between control nodes and action nodes based on the semantic parsing of activity model element instances. The code blocks include loop, conditional, or concurrent code blocks. When performing state machine graph mapping, the behavior model converter converts the state, transition, and behavior semantic element instances in the SysML state machine graph into executable logic code syntax tree nodes for the target programming language based on a pre-built runtime state management framework. The runtime state management framework includes state classes for encapsulating state node information and their associated behavioral logic, and region classes for encapsulating multiple mutually exclusive state class instances and managing the transition logic between the state class instances. The abstract syntax tree is semantically and syntactically validated. Once validated, the node information is extracted and used as context data to input into the template engine. The final executable code is generated by filling in the preset code template.
2. The SysML model-to-code generation method according to claim 1, characterized in that, The extended SysML model supplements the model semantics with the target code generation configuration parameters and the semantic structure of the target programming language, including: The SysML stereotype defines the configuration parameters for generating target code and the semantic structure of the target programming language, which are then added to the model semantics to extend the SysML model. The configuration parameters for generating target code include the target code type, code file storage location, conversion of target model element instances, and whether to automatically generate one or more attributes from the attribute accessors. The semantic structure of the target programming language includes one or more model elements that cover the code semantics, such as friend functions, virtual functions, and type modifiers of the target programming language.
3. The SysML model-to-code generation method according to claim 1, characterized in that, The validation of model element instances according to the SysML specification includes: Based on the model element instance repository, and in accordance with the model attribute constraints and model relationship constraints defined in the SysML specification, the static semantic integrity of the model element instances is verified, and in accordance with the executable unified modeling language constraints defined in the SysML specification, the behavioral semantic executability of the model element instances is verified. During the verification process, each model element instance is assigned a unique identifier, InstanceID, to enable precise location of the verification results and backtracking to the specific element instance in the source SysML model.
4. The SysML model-to-code generation method according to claim 1, characterized in that, The method also includes the construction of a communication channel, including: A predefined active object framework base class is defined, which encapsulates communication mechanisms including thread execution, message queues, event dispatch, and event handling. When the converter recognizes the interaction or event semantics in the model element instance, it converts them into the corresponding message structure and message routing code syntax tree nodes, thereby constructing a message-based asynchronous communication data path between threads.
5. The SysML model-to-code generation method according to claim 1, characterized in that, The semantic and syntactic verification of the abstract syntax tree includes: Based on the syntax and semantic rules of the target programming language, traverse the abstract syntax tree to check the semantic integrity of its type definitions, variable declarations, and control flow. When an error or missing element is detected, an error message is generated and the error information is traced back to the corresponding model element instance in the source SysML model.
6. A SysML model-to-code generation apparatus, implemented using the SysML model-to-code generation method according to any one of claims 1 to 5, characterized in that, include: Model extension module, model parsing module, model conversion module, and code generation module; The model extension module is used to extend the SysML model by adding the target code generation configuration parameters and the semantic structure of the target programming language to the model semantics. The model parsing module is used to parse the extended SysML model, build a repository of model element instances containing model element instances and their relationships, and perform validity checks on the model element instances according to the SysML specification. The model conversion module is used to convert the validated model element instances into code syntax tree nodes by executing conversion rules according to the type of the model element instances through the converter, thereby obtaining the abstract syntax tree of the target programming language. The code generation module is used to perform semantic and syntactic verification on the abstract syntax tree. After the verification is successful, the node information is extracted as context data and input into the template engine. The final executable code is generated by filling in the preset code template.
7. An electronic device comprising a memory and one or more processors, the memory being used to store a computer program, characterized in that, The processor is used to implement the SysML model-to-code generation method according to any one of claims 1 to 5 when executing a computer program.
8. A computer-readable storage medium storing a computer program thereon, characterized in that, When the computer program is executed by a computer, it implements the SysML model-to-code generation method according to any one of claims 1 to 5.