MCPcopy Create free account
hub / github.com/davidmoreno/rtpmidid / generate_cpp_source

Function generate_cpp_source

scripts/statemachine_to_cpp.py:132–198  ·  view source on GitHub ↗
(stm)

Source from the content-addressed store, hash-verified

130
131
132def generate_cpp_source(stm):
133 code = ""
134 code += "// This is an autogenerated file. It should be included at source\n"
135 code += "/** STATE MACHINE\n"
136 code += " * ```mermaid\n"
137 code += cpp_comment(stm.code)
138 code += " * ```\n"
139 code += " */\n"
140
141 code += f"void {stm.name}::handle_event(event_e event){{\n"
142 code += " state_e oldstate = state;\n"
143 code += " state = state_e::Error;\n"
144 code += " switch(oldstate){\n"
145 for state in stm.states:
146 code += f" case state_e::{state}:\n"
147 code += " switch(event){\n"
148 for transition in stm.transitions:
149 source, target, event = transition
150 if source == state:
151 code += f" case event_e::{event}:\n"
152 code += f" state = state_e::{target};\n"
153 code += " break;\n"
154 code += " default:;\n"
155 code += " }\n"
156 code += " break;\n"
157 code += " }\n"
158
159 # call a function with the state name in snake_case
160 code += " switch(state){\n"
161 for state in stm.states:
162 snake_name = re.sub(r"([a-z])([A-Z])", r"\1_\2", state).lower()
163 code += f" case state_e::{state}:\n"
164 if state == "Error":
165 code += ' DEBUG("Error, previous state: {}", oldstate);\n'
166 code += f" state_{snake_name}();\n"
167 code += " break;\n"
168 code += " }\n"
169
170 code += "}\n"
171 # formatters
172 code += f"""// event formatter
173const char *{stm.name}::to_string({stm.name}::event_e value) {{
174 switch (value) {{
175"""
176 for event in stm.events:
177 code += f" case {stm.name}::event_e::{event}:\n"
178 code += f' return "{event}";\n'
179 code += """ default:
180 return "unknown";
181"""
182 code += " } \n"
183 code += "}\n"
184
185 # state formatter
186 code += f"""// state formatter
187const char *{stm.name}::to_string({stm.name}::state_e value) {{
188 switch (value) {{
189"""

Callers 1

mainFunction · 0.85

Calls 1

cpp_commentFunction · 0.85

Tested by

no test coverage detected