CppGenerator.xtend 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. package be.uantwerpen.ansymo.semanticadaptation.cg.cpp.generation
  2. import be.uantwerpen.ansymo.semanticadaptation.generator.SemanticAdaptationGenerator
  3. import org.eclipse.xtext.generator.IFileSystemAccess2
  4. import org.eclipse.xtext.generator.IGeneratorContext
  5. import be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.SemanticAdaptation
  6. import org.eclipse.emf.ecore.resource.Resource
  7. import be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.Adaptation
  8. import java.util.ArrayList
  9. import java.util.LinkedHashMap
  10. import be.uantwerpen.ansymo.semanticadaptation.cg.cpp.data.MappedScalarVariable
  11. import be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.InnerFMU
  12. import be.uantwerpen.ansymo.semanticadaptation.cg.cpp.exceptions.IncorrectAmountOfElementsException
  13. import java.io.File
  14. import be.uantwerpen.ansymo.semanticadaptation.cg.cpp.data.SAScalarVariable
  15. import be.uantwerpen.ansymo.semanticadaptation.cg.cpp.data.InputOutputType
  16. import org.eclipse.emf.common.util.EList
  17. import be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.Port
  18. import be.uantwerpen.ansymo.semanticadaptation.cg.cpp.data.SVCausality
  19. import java.util.Collection
  20. import be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.InOutRules
  21. import be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.InRulesBlock
  22. import be.uantwerpen.ansymo.semanticadaptation.cg.cpp.data.InOutRulesBlockResult
  23. import be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.OutRulesBlock
  24. import be.uantwerpen.ansymo.semanticadaptation.cg.cpp.data.GlobalInOutVariable
  25. import be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.ControlRuleBlock
  26. import be.uantwerpen.ansymo.semanticadaptation.cg.cpp.data.RulesBlockResult
  27. import be.uantwerpen.ansymo.semanticadaptation.cg.cpp.data.ScalarVariable
  28. import java.util.List
  29. import be.uantwerpen.ansymo.semanticadaptation.cg.cpp.data.SVType
  30. class CppGenerator extends SemanticAdaptationGenerator {
  31. private var IFileSystemAccess2 fsa;
  32. override void doGenerate(Resource resource, IFileSystemAccess2 fsa, IGeneratorContext context) {
  33. this.fsa = fsa;
  34. for (SemanticAdaptation type : resource.allContents.toIterable.filter(SemanticAdaptation)) {
  35. type.compile;
  36. }
  37. }
  38. // TODO: Verify adaptation.name is not a C++ keyword
  39. def void compile(SemanticAdaptation adaptation) {
  40. for (Adaptation type : adaptation.elements.filter(Adaptation)) {
  41. // Value used for scoping variables in the .sa file
  42. val adapInteralRefName = type.name;
  43. // The CPP class name
  44. val adapClassName = type.name.toFirstUpper;
  45. // This is the external name used in the model description file for the semantic adaptation FMU.
  46. val adapExternalName = type.type.name;
  47. // List of FMUs with a pairing between its name and its type.name.
  48. var ArrayList<Pair<String, String>> fmus = newArrayList();
  49. // The scalar variables above with additional data
  50. var LinkedHashMap<String, LinkedHashMap<String, MappedScalarVariable>> mappedScalarVariables = newLinkedHashMap();
  51. // TODO: Currently only 1 inner fmu is supported
  52. val innerFmus = type.inner.eAllContents.toList.filter(InnerFMU);
  53. if (innerFmus.size > 1) {
  54. throw new IncorrectAmountOfElementsException("Only one InnerFmu is supported.")
  55. }
  56. if (innerFmus.isEmpty) {
  57. throw new IncorrectAmountOfElementsException("The adaptation does not contain any InnerFMUs.")
  58. }
  59. /*
  60. * Loading the FMU defined in InnerFMU, the related model description file and its scalar variables.
  61. * This is stored in a map of fmuName -> (SVName -> mappedSV)
  62. * where the mappedSV contains the original scalar variable and some extra data such as define name.
  63. */
  64. // TODO: Currently only 1 model description is supported
  65. var ModelDescription md;
  66. for (fmu : type.inner.eAllContents.toList.filter(InnerFMU)) {
  67. md = new ModelDescription(fmu.name, fmu.type.name, new File(fmu.path.replace('\"', '')));
  68. fmus.add(fmu.name -> fmu.type.name);
  69. val LinkedHashMap<String, MappedScalarVariable> mSV = newLinkedHashMap();
  70. for (sv : md.sv.values) {
  71. var mappedSv = new MappedScalarVariable(sv);
  72. mappedSv.define = (mappedSv.mappedSv.owner + mappedSv.mappedSv.name).toUpperCase;
  73. mSV.put(mappedSv.mappedSv.name, mappedSv);
  74. }
  75. mappedScalarVariables.put(fmu.name, mSV);
  76. }
  77. // Defines for accessing FMU scalar variables.
  78. val String fmusDefines = calcDefines2(mappedScalarVariables);
  79. /*
  80. * This map contains all the ScalarVariables for the semantic adaptation.
  81. * The are not populated yet, but they will be during the compilation of the in and out rule blocks.
  82. */
  83. var LinkedHashMap<String, SAScalarVariable> SASVs = calcSASVsFromInportsOutports(adapInteralRefName,
  84. type.inports, type.outports)
  85. // Generate defines for the scalar variables of the semantic adaptation
  86. val String SADefines = calcSADefines(SASVs.values);
  87. // Compile the in rules
  88. val inRuleResult = compileInOutRuleBlocks(InputOutputType.Input, adaptation.eAllContents.toIterable.filter(
  89. InRulesBlock).map[x|x as InOutRules], adapClassName, adapInteralRefName, mappedScalarVariables, SASVs);
  90. // Compile the out rules
  91. val outRuleResult = compileInOutRuleBlocks(InputOutputType.Output, adaptation.eAllContents.toIterable.
  92. filter(OutRulesBlock).map[x|x as InOutRules], adapClassName, adapInteralRefName, mappedScalarVariables,
  93. SASVs);
  94. // Merge the global variables
  95. // TODO: Check for duplicates
  96. var LinkedHashMap<String, GlobalInOutVariable> globalVariables = newLinkedHashMap();
  97. globalVariables.putAll(outRuleResult.globalVars2);
  98. globalVariables.putAll(inRuleResult.globalVars2);
  99. // Compile the Control Rules
  100. val crtlRuleResult = compileControlRuleBlock(adaptation.eAllContents.toIterable.filter(ControlRuleBlock),
  101. adapClassName, adapInteralRefName, SASVs);
  102. /*
  103. * As the in and out rules have populated the semantic adaptation scalar variables we can generate the getFmiValue* and setFmiValue functions.
  104. */
  105. val String getFuncsSource = compileGetFmiValueFunctions(adapClassName, SASVs);
  106. val String setFuncsSource = compileSetFmiValueFunctions(adapClassName, SASVs);
  107. /*
  108. * Compile the constructor, destructor and initialize functions
  109. */
  110. val String deAndConstructorAndInitializeSource = compileDeAndConstructorAndInitialize(adapClassName, globalVariables, fmus.head.key,
  111. fmus.head.value, md.guid);
  112. /*
  113. * Compile getRuleThis function
  114. */
  115. val String getRuleThisSource = compileGetRuleThis(adapClassName);
  116. // Compile the source file
  117. val String sourceInclude = '''#include "«adapClassName».h"''';
  118. val sourceFile = compileSource(
  119. sourceInclude,
  120. deAndConstructorAndInitializeSource,
  121. getRuleThisSource,
  122. getFuncsSource,
  123. setFuncsSource,
  124. inRuleResult.generatedCpp,
  125. outRuleResult.generatedCpp,
  126. crtlRuleResult.generatedCpp
  127. );
  128. fsa.generateFile(adapClassName + ".cpp", sourceFile);
  129. // Compile the header file
  130. val headerFile = compileHeader(
  131. adapClassName,
  132. fmusDefines,
  133. SADefines,
  134. inRuleResult.functionSignatures,
  135. outRuleResult.functionSignatures,
  136. crtlRuleResult.functionSignatures,
  137. globalVariables,
  138. fmus,
  139. SASVs.values.map[CalcSVar()].toList
  140. );
  141. fsa.generateFile(adapClassName + ".h", headerFile);
  142. // Compile the model description file
  143. val modelDescCreator = new ModelDescriptionCreator(adapExternalName);
  144. val modelDescription = modelDescCreator.generateModelDescription(SASVs.values);
  145. fsa.generateFile("modelDescription.xml", modelDescription);
  146. // Compile the fmu.cpp file
  147. val fmuCppFile = StaticGenerators.GenFmuCppFile(adapClassName);
  148. fsa.generateFile("Fmu.cpp", fmuCppFile);
  149. }
  150. }
  151. def calcSADefines(Collection<SAScalarVariable> variables) {
  152. var ArrayList<String> defines = newArrayList();
  153. for (SASV : variables) {
  154. defines.add("#define " + SASV.defineName + " " + SASV.valueReference);
  155. }
  156. return defines.join("\n");
  157. }
  158. def calcDefines2(LinkedHashMap<String, LinkedHashMap<String, MappedScalarVariable>> map) {
  159. var ArrayList<String> defines = newArrayList();
  160. for (fmuEntries : map.entrySet) {
  161. for (MappedScalarVariable mSV : fmuEntries.value.values) {
  162. defines.add("#define " + mSV.define + " " + mSV.valueReference);
  163. }
  164. }
  165. return defines.join("\n");
  166. }
  167. // Compiles the final source file
  168. def String compileSource(String include, String constructor, String getRuleThis, String getFunctions,
  169. String setFunctions, String inFunctions, String outFunctions, String controlFunction) {
  170. return '''
  171. «include»
  172. namespace adaptation
  173. {
  174. «constructor»
  175. «getRuleThis»
  176. «getFunctions»
  177. «setFunctions»
  178. «inFunctions»
  179. «controlFunction»
  180. «outFunctions»
  181. }
  182. '''
  183. }
  184. /*
  185. * Compiles the header file split into two: The first part contains the includes and using namespace definitions and start the ,
  186. * the second part contains the class
  187. */
  188. def String compileHeader(String adapClassName, String fmusDefines, String SADefines, List<String> inRulesFuncSig,
  189. List<String> outRulesFuncSig, List<String> crtlRulesFuncSig,
  190. LinkedHashMap<String, GlobalInOutVariable> globalVariables, ArrayList<Pair<String, String>> fmus,
  191. Collection<ScalarVariable> sVars) {
  192. return '''
  193. #ifndef SRC_«adapClassName.toUpperCase»_H
  194. #define SRC_«adapClassName.toUpperCase»_H
  195. #include "SemanticAdaptation.h"
  196. #include <memory>
  197. #include "Fmu.h"
  198. using namespace std;
  199. using namespace fmi2;
  200. namespace adaptation
  201. {
  202. «fmusDefines»
  203. «SADefines»
  204. class «adapClassName» : public SemanticAdaptation<«adapClassName»>, public enable_shared_from_this<«adapClassName»>
  205. {
  206. public:
  207. «adapClassName»(shared_ptr<string> resourceLocation, const fmi2CallbackFunctions* functions);
  208. void initialize();
  209. virtual ~«adapClassName»();
  210. void setFmiValue(fmi2ValueReference id, int value);
  211. void setFmiValue(fmi2ValueReference id, bool value);
  212. void setFmiValue(fmi2ValueReference id, double value);
  213. void setFmiValue(fmi2ValueReference id, string value);
  214. int getFmiValueInteger(fmi2ValueReference id);
  215. bool getFmiValueBoolean(fmi2ValueReference id);
  216. double getFmiValueReal(fmi2ValueReference id);
  217. string getFmiValueString(fmi2ValueReference id);
  218. private:
  219. «adapClassName»* getRuleThis();
  220. /*in rules*/
  221. «inRulesFuncSig.map[x | x+";"].join("\n")»
  222. /*out rules*/
  223. «outRulesFuncSig.map[x | x+";"].join("\n")»
  224. «crtlRulesFuncSig.map[x | x+";"].join("\n")»
  225. «FOR fmu : fmus»
  226. shared_ptr<FmuComponent> «fmu.key»;
  227. «ENDFOR»
  228. «FOR sv : sVars»
  229. «Conversions.fmiTypeToCppType(sv.type)» «sv.name»;
  230. «IF sv.causality == SVCausality.input»
  231. bool isSet«sv.name»;
  232. «ENDIF»
  233. «ENDFOR»
  234. «FOR v : globalVariables.entrySet»
  235. «Conversions.fmiTypeToCppType(v.value.type)» «v.key»;
  236. «ENDFOR»
  237. };
  238. }
  239. #endif
  240. ''';
  241. }
  242. /*
  243. * Compiles the source file constructor, destructor and the initialize function
  244. */
  245. def String compileDeAndConstructorAndInitialize(String adapClassName, LinkedHashMap<String, GlobalInOutVariable> globalVariables,
  246. String fmuName, String fmuTypeName, String guid) {
  247. return '''
  248. «adapClassName»::«adapClassName»(shared_ptr<string> resourceLocation, const fmi2CallbackFunctions* functions) :
  249. SemanticAdaptation(resourceLocation, createInputRules(),createOutputRules(), functions)
  250. {
  251. «FOR v : globalVariables.entrySet»
  252. this->«(v.key)» = «v.value.value»;
  253. «ENDFOR»
  254. }
  255. void «adapClassName»::initialize()
  256. {
  257. auto path = Fmu::combinePath(resourceLocation, make_shared<string>("«fmuTypeName».fmu"));
  258. auto «fmuName»Fmu = make_shared<fmi2::Fmu>(*path);
  259. «fmuName»Fmu->initialize();
  260. this->«fmuName» = «fmuName»Fmu->instantiate("«fmuName»",fmi2CoSimulation, "«guid»", true, true, shared_from_this());
  261. if(this->«fmuName»->component == NULL)
  262. this->lastErrorState = fmi2Fatal;
  263. this->instances->push_back(this->«fmuName»);
  264. }
  265. «adapClassName»::~«adapClassName»()
  266. {
  267. }
  268. ''';
  269. }
  270. /*
  271. * Compiles the source file function getRuleThis
  272. */
  273. def String compileGetRuleThis(String adaptationName) {
  274. return '''
  275. «adaptationName»* «adaptationName»::getRuleThis()
  276. {
  277. return this;
  278. }
  279. '''
  280. }
  281. /*
  282. * Compiles the source file functions getFmiValue<double, int, string, bool>
  283. */
  284. def String compileGetFmiValueFunctions(String adaptationName, LinkedHashMap<String, SAScalarVariable> variables) {
  285. var ArrayList<String> cpp = newArrayList();
  286. var List<ScalarVariable> convertedSASVs = variables.values.map[CalcSVar()].toList;
  287. var convertedSASVsOrdered = convertedSASVs.filter[causality === SVCausality.output].groupBy[type];
  288. for (SVType type : SVType.values) {
  289. val functionSignature = '''«Conversions.fmiTypeToCppType(type)» «adaptationName»::getFmiValue«type.toString»(fmi2ValueReference id)''';
  290. val functionReturn = '''return «Conversions.fmiTypeToCppDefaultValue(type)»''';
  291. if (convertedSASVsOrdered.containsKey(type)) {
  292. cpp.add(
  293. '''
  294. «functionSignature»
  295. {
  296. switch (id)
  297. {
  298. «FOR svInner : convertedSASVsOrdered.get(type)»
  299. case «variables.get(svInner.name).defineName»:
  300. {
  301. return this->«svInner.name»;
  302. }
  303. «ENDFOR»
  304. default:
  305. {
  306. «functionReturn»;
  307. }
  308. }
  309. }
  310. '''
  311. );
  312. } else {
  313. cpp.add(
  314. '''
  315. «functionSignature»
  316. {
  317. «functionReturn»;
  318. }
  319. '''
  320. );
  321. }
  322. }
  323. return cpp.join("\n");
  324. }
  325. /*
  326. * Compiles the source file functions setFmiValue<double, int, string, bool>*
  327. */
  328. def String compileSetFmiValueFunctions(String adapClassName, LinkedHashMap<String, SAScalarVariable> variables) {
  329. var ArrayList<String> cpp = newArrayList();
  330. var List<ScalarVariable> convertedSASVs = variables.values.map[CalcSVar()].filter [
  331. causality === SVCausality.input
  332. ].toList;
  333. var convertedSASVsOrdered = convertedSASVs.groupBy[type];
  334. for (SVType type : SVType.values) {
  335. cpp.add(
  336. '''
  337. void «adapClassName»::setFmiValue(fmi2ValueReference id, «Conversions.fmiTypeToCppType(type)» value)
  338. {
  339. «IF convertedSASVsOrdered.containsKey(type)»
  340. switch (id)
  341. {
  342. «FOR svInner : convertedSASVsOrdered.get(type)»
  343. case «variables.get(svInner.name).defineName»:
  344. {
  345. this->«svInner.name» = value;
  346. this->isSet«svInner.name» = true;
  347. break;
  348. }
  349. «ENDFOR»
  350. default:
  351. {
  352. }
  353. }
  354. «ENDIF»
  355. }
  356. '''
  357. );
  358. }
  359. return cpp.join("\n");
  360. }
  361. /*
  362. * Compiles the source file function executeInternalControlFlow.
  363. * Calculates necessary information on function signatures necessary for generation of the header file.
  364. */
  365. def RulesBlockResult compileControlRuleBlock(Iterable<ControlRuleBlock> crtlRuleBlocks, String adaptationClassName,
  366. String adaptationName, LinkedHashMap<String, SAScalarVariable> SASVs) {
  367. var cpp = "";
  368. val visitor = new ControlConditionSwitch(adaptationClassName, adaptationName, SASVs);
  369. for (crtlRule : crtlRuleBlocks) {
  370. cpp += visitor.doSwitch(crtlRule).code;
  371. }
  372. return new RulesBlockResult(cpp, visitor.functionSignatures);
  373. }
  374. def String SplitAtSpaceAndRemoveFirst(String content) {
  375. content.substring(content.indexOf(" ") + 1, content.length);
  376. }
  377. def String removeEmptyArgumentParenthesis(String content)
  378. {
  379. return content.substring(0,content.length-2);
  380. }
  381. /*
  382. * Compiles the source file functions <in/out>_rule_<condition, body, flush>.
  383. * Calculates necessary information on global in/out variables necessary for generation of the header file.
  384. * Calculates necessary information on function signatures necessary for generation of the header file.
  385. */
  386. def InOutRulesBlockResult compileInOutRuleBlocks(InputOutputType ioType, Iterable<InOutRules> rulesBlocks,
  387. String adaptationClassName, String adaptationName,
  388. LinkedHashMap<String, LinkedHashMap<String, MappedScalarVariable>> mSVars,
  389. LinkedHashMap<String, SAScalarVariable> SASVs) {
  390. val visitor = if (ioType == InputOutputType.Input)
  391. new InRulesConditionSwitch(adaptationClassName, adaptationName, mSVars, SASVs)
  392. else
  393. new OutRulesConditionSwitch(adaptationClassName, adaptationName, mSVars, SASVs);
  394. val functionName = "create" + ioType + "Rules()";
  395. var String cpp = "";
  396. val ruleBlock = rulesBlocks.head;
  397. if (ruleBlock !== null) {
  398. cpp += visitor.doSwitch(ruleBlock).code;
  399. if (!visitor.functionSignatures.empty) {
  400. var ArrayList<String> createRulesFunction = newArrayList();
  401. for (var int i = 0; i < (visitor.functionSignatures.length); i += 3) {
  402. createRulesFunction.add(
  403. '''
  404. list->push_back(
  405. (Rule<«adaptationClassName»>){
  406. &«adaptationClassName»::«visitor.functionSignatures.get(i).SplitAtSpaceAndRemoveFirst.removeEmptyArgumentParenthesis»,
  407. &«adaptationClassName»::«visitor.functionSignatures.get(i+1).SplitAtSpaceAndRemoveFirst.removeEmptyArgumentParenthesis»,
  408. &«adaptationClassName»::«visitor.functionSignatures.get(i+2).SplitAtSpaceAndRemoveFirst.removeEmptyArgumentParenthesis»
  409. });
  410. ''');
  411. }
  412. val functionPrefix = '''shared_ptr<list<Rule<«adaptationClassName»>>>''';
  413. visitor.functionSignatures.add(functionPrefix + " " + functionName + ";")
  414. cpp += '''
  415. «functionPrefix» «adaptationClassName»::«functionName»
  416. {
  417. auto list = make_shared<std::list<Rule<«adaptationClassName»>>>();
  418. «createRulesFunction.join("\n")»
  419. return list;
  420. }
  421. '''
  422. }
  423. }
  424. return new InOutRulesBlockResult(cpp, visitor.functionSignatures, visitor.vars, visitor.getGlobalVars);
  425. }
  426. /*
  427. * Calculates the semantic adaptation scalar variables via input ports and output ports.
  428. * Note: These a not fully populated yet as the in rules and out rules must be compiled first.
  429. */
  430. def LinkedHashMap<String, SAScalarVariable> calcSASVsFromInportsOutports(String definePrefix, EList<Port> inports,
  431. EList<Port> outports) {
  432. var LinkedHashMap<String, SAScalarVariable> saSVs = newLinkedHashMap();
  433. var int valueReference = 0;
  434. for (inport : inports) {
  435. var saSV = new SAScalarVariable();
  436. saSV.valueReference = valueReference++;
  437. saSV.name = inport.name;
  438. saSV.defineName = (definePrefix + inport.name).toUpperCase
  439. saSV.causality = SVCausality.input;
  440. saSVs.put(saSV.name, saSV);
  441. }
  442. for (outport : outports) {
  443. var saSV = new SAScalarVariable();
  444. saSV.valueReference = valueReference++;
  445. saSV.defineName = (definePrefix + outport.name).toUpperCase
  446. saSV.name = outport.name;
  447. saSV.causality = SVCausality.output;
  448. saSVs.put(saSV.name, saSV);
  449. }
  450. return saSVs;
  451. }
  452. }