CppGenerator.xtend 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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. }
  147. }
  148. def calcSADefines(Collection<SAScalarVariable> variables) {
  149. var ArrayList<String> defines = newArrayList();
  150. for (SASV : variables) {
  151. defines.add("#define " + SASV.defineName + " " + SASV.valueReference);
  152. }
  153. return defines.join("\n");
  154. }
  155. def calcDefines2(LinkedHashMap<String, LinkedHashMap<String, MappedScalarVariable>> map) {
  156. var ArrayList<String> defines = newArrayList();
  157. for (fmuEntries : map.entrySet) {
  158. for (MappedScalarVariable mSV : fmuEntries.value.values) {
  159. defines.add("#define " + mSV.define + " " + mSV.valueReference);
  160. }
  161. }
  162. return defines.join("\n");
  163. }
  164. // Compiles the final source file
  165. def String compileSource(String include, String constructor, String getRuleThis, String getFunctions,
  166. String setFunctions, String inFunctions, String outFunctions, String controlFunction) {
  167. return '''
  168. «include»
  169. namespace adaptation
  170. {
  171. «constructor»
  172. «getRuleThis»
  173. «getFunctions»
  174. «setFunctions»
  175. «inFunctions»
  176. «controlFunction»
  177. «outFunctions»
  178. }
  179. '''
  180. }
  181. /*
  182. * Compiles the header file split into two: The first part contains the includes and using namespace definitions and start the ,
  183. * the second part contains the class
  184. */
  185. def String compileHeader(String adapClassName, String fmusDefines, String SADefines, List<String> inRulesFuncSig,
  186. List<String> outRulesFuncSig, List<String> crtlRulesFuncSig,
  187. LinkedHashMap<String, GlobalInOutVariable> globalVariables, ArrayList<Pair<String, String>> fmus,
  188. Collection<ScalarVariable> sVars) {
  189. return '''
  190. #ifndef SRC_«adapClassName.toUpperCase»_H
  191. #define SRC_«adapClassName.toUpperCase»_H
  192. #include "SemanticAdaptation.h"
  193. #include <memory>
  194. #include "Fmu.h"
  195. using namespace std;
  196. using namespace fmi2;
  197. namespace adaptation
  198. {
  199. «fmusDefines»
  200. «SADefines»
  201. class «adapClassName» : public SemanticAdaptation<«adapClassName»>, public enable_shared_from_this<«adapClassName»>
  202. {
  203. public:
  204. «adapClassName»(shared_ptr<string> resourceLocation, const fmi2CallbackFunctions* functions);
  205. void initialize();
  206. virtual ~«adapClassName»();
  207. void setFmiValue(fmi2ValueReference id, int value);
  208. void setFmiValue(fmi2ValueReference id, bool value);
  209. void setFmiValue(fmi2ValueReference id, double value);
  210. void setFmiValue(fmi2ValueReference id, string value);
  211. int getFmiValueInteger(fmi2ValueReference id);
  212. bool getFmiValueBoolean(fmi2ValueReference id);
  213. double getFmiValueReal(fmi2ValueReference id);
  214. string getFmiValueString(fmi2ValueReference id);
  215. private:
  216. «adapClassName»* getRuleThis();
  217. /*in rules*/
  218. «inRulesFuncSig.map[x | x+";"].join("\n")»
  219. /*out rules*/
  220. «outRulesFuncSig.map[x | x+";"].join("\n")»
  221. «crtlRulesFuncSig.map[x | x+";"].join("\n")»
  222. «FOR fmu : fmus»
  223. shared_ptr<FmuComponent> «fmu.key»;
  224. «ENDFOR»
  225. «FOR sv : sVars»
  226. «Conversions.fmiTypeToCppType(sv.type)» «sv.name»;
  227. «IF sv.causality == SVCausality.input»
  228. bool isSet«sv.name»;
  229. «ENDIF»
  230. «ENDFOR»
  231. «FOR v : globalVariables.entrySet»
  232. «Conversions.fmiTypeToCppType(v.value.type)» «v.key»;
  233. «ENDFOR»
  234. };
  235. }
  236. #endif
  237. ''';
  238. }
  239. /*
  240. * Compiles the source file constructor, destructor and the initialize function
  241. */
  242. def String compileDeAndConstructorAndInitialize(String adapClassName, LinkedHashMap<String, GlobalInOutVariable> globalVariables,
  243. String fmuName, String fmuTypeName, String guid) {
  244. return '''
  245. «adapClassName»::«adapClassName»(shared_ptr<string> resourceLocation, const fmi2CallbackFunctions* functions) :
  246. SemanticAdaptation(resourceLocation, createInputRules(),createOutputRules(), functions)
  247. {
  248. «FOR v : globalVariables.entrySet»
  249. this->«(v.key)» = «v.value.value»;
  250. «ENDFOR»
  251. }
  252. void «adapClassName»::initialize()
  253. {
  254. auto path = Fmu::combinePath(resourceLocation, make_shared<string>("«fmuTypeName».fmu"));
  255. auto «fmuName»Fmu = make_shared<fmi2::Fmu>(*path);
  256. «fmuName»Fmu->initialize();
  257. this->«fmuName» = «fmuName»Fmu->instantiate("«fmuName»",fmi2CoSimulation, "«guid»", true, true, shared_from_this());
  258. if(this->«fmuName»->component == NULL)
  259. this->lastErrorState = fmi2Fatal;
  260. this->instances->push_back(this->«fmuName»);
  261. }
  262. «adapClassName»::~«adapClassName»()
  263. {
  264. }
  265. ''';
  266. }
  267. /*
  268. * Compiles the source file function getRuleThis
  269. */
  270. def String compileGetRuleThis(String adaptationName) {
  271. return '''
  272. «adaptationName»* «adaptationName»::getRuleThis()
  273. {
  274. return this;
  275. }
  276. '''
  277. }
  278. /*
  279. * Compiles the source file functions getFmiValue<double, int, string, bool>
  280. */
  281. def String compileGetFmiValueFunctions(String adaptationName, LinkedHashMap<String, SAScalarVariable> variables) {
  282. var ArrayList<String> cpp = newArrayList();
  283. var List<ScalarVariable> convertedSASVs = variables.values.map[CalcSVar()].toList;
  284. var convertedSASVsOrdered = convertedSASVs.filter[causality === SVCausality.output].groupBy[type];
  285. for (SVType type : SVType.values) {
  286. val functionSignature = '''«Conversions.fmiTypeToCppType(type)» «adaptationName»::getFmiValue«type.toString»(fmi2ValueReference id)''';
  287. val functionReturn = '''return «Conversions.fmiTypeToCppDefaultValue(type)»''';
  288. if (convertedSASVsOrdered.containsKey(type)) {
  289. cpp.add(
  290. '''
  291. «functionSignature»
  292. {
  293. switch (id)
  294. {
  295. «FOR svInner : convertedSASVsOrdered.get(type)»
  296. case «variables.get(svInner.name).defineName»:
  297. {
  298. return this->«svInner.name»;
  299. }
  300. «ENDFOR»
  301. default:
  302. {
  303. «functionReturn»;
  304. }
  305. }
  306. }
  307. '''
  308. );
  309. } else {
  310. cpp.add(
  311. '''
  312. «functionSignature»
  313. {
  314. «functionReturn»;
  315. }
  316. '''
  317. );
  318. }
  319. }
  320. return cpp.join("\n");
  321. }
  322. /*
  323. * Compiles the source file functions setFmiValue<double, int, string, bool>*
  324. */
  325. def String compileSetFmiValueFunctions(String adapClassName, LinkedHashMap<String, SAScalarVariable> variables) {
  326. var ArrayList<String> cpp = newArrayList();
  327. var List<ScalarVariable> convertedSASVs = variables.values.map[CalcSVar()].filter [
  328. causality === SVCausality.input
  329. ].toList;
  330. var convertedSASVsOrdered = convertedSASVs.groupBy[type];
  331. for (SVType type : SVType.values) {
  332. cpp.add(
  333. '''
  334. void «adapClassName»::setFmiValue(fmi2ValueReference id, «Conversions.fmiTypeToCppType(type)» value)
  335. {
  336. «IF convertedSASVsOrdered.containsKey(type)»
  337. switch (id)
  338. {
  339. «FOR svInner : convertedSASVsOrdered.get(type)»
  340. case «variables.get(svInner.name).defineName»:
  341. {
  342. this->«svInner.name» = value;
  343. this->isSet«svInner.name» = true;
  344. break;
  345. }
  346. «ENDFOR»
  347. default:
  348. {
  349. }
  350. }
  351. «ENDIF»
  352. }
  353. '''
  354. );
  355. }
  356. return cpp.join("\n");
  357. }
  358. /*
  359. * Compiles the source file function executeInternalControlFlow.
  360. * Calculates necessary information on function signatures necessary for generation of the header file.
  361. */
  362. def RulesBlockResult compileControlRuleBlock(Iterable<ControlRuleBlock> crtlRuleBlocks, String adaptationClassName,
  363. String adaptationName, LinkedHashMap<String, SAScalarVariable> SASVs) {
  364. var cpp = "";
  365. val visitor = new ControlConditionSwitch(adaptationClassName, adaptationName, SASVs);
  366. for (crtlRule : crtlRuleBlocks) {
  367. cpp += visitor.doSwitch(crtlRule).code;
  368. }
  369. return new RulesBlockResult(cpp, visitor.functionSignatures);
  370. }
  371. def String SplitAtSpaceAndRemoveFirst(String content) {
  372. content.substring(content.indexOf(" ") + 1, content.length);
  373. }
  374. def String removeEmptyArgumentParenthesis(String content)
  375. {
  376. return content.substring(0,content.length-2);
  377. }
  378. /*
  379. * Compiles the source file functions <in/out>_rule_<condition, body, flush>.
  380. * Calculates necessary information on global in/out variables necessary for generation of the header file.
  381. * Calculates necessary information on function signatures necessary for generation of the header file.
  382. */
  383. def InOutRulesBlockResult compileInOutRuleBlocks(InputOutputType ioType, Iterable<InOutRules> rulesBlocks,
  384. String adaptationClassName, String adaptationName,
  385. LinkedHashMap<String, LinkedHashMap<String, MappedScalarVariable>> mSVars,
  386. LinkedHashMap<String, SAScalarVariable> SASVs) {
  387. val visitor = if (ioType == InputOutputType.Input)
  388. new InRulesConditionSwitch(adaptationClassName, adaptationName, mSVars, SASVs)
  389. else
  390. new OutRulesConditionSwitch(adaptationClassName, adaptationName, mSVars, SASVs);
  391. val functionName = "create" + ioType + "Rules()";
  392. var String cpp = "";
  393. val ruleBlock = rulesBlocks.head;
  394. if (ruleBlock !== null) {
  395. cpp += visitor.doSwitch(ruleBlock).code;
  396. if (!visitor.functionSignatures.empty) {
  397. var ArrayList<String> createRulesFunction = newArrayList();
  398. for (var int i = 0; i < (visitor.functionSignatures.length); i += 3) {
  399. createRulesFunction.add(
  400. '''
  401. list->push_back(
  402. (Rule<«adaptationClassName»>){
  403. &«adaptationClassName»::«visitor.functionSignatures.get(i).SplitAtSpaceAndRemoveFirst.removeEmptyArgumentParenthesis»,
  404. &«adaptationClassName»::«visitor.functionSignatures.get(i+1).SplitAtSpaceAndRemoveFirst.removeEmptyArgumentParenthesis»,
  405. &«adaptationClassName»::«visitor.functionSignatures.get(i+2).SplitAtSpaceAndRemoveFirst.removeEmptyArgumentParenthesis»
  406. });
  407. ''');
  408. }
  409. val functionPrefix = '''shared_ptr<list<Rule<«adaptationClassName»>>>''';
  410. visitor.functionSignatures.add(functionPrefix + " " + functionName + ";")
  411. cpp += '''
  412. «functionPrefix» «adaptationClassName»::«functionName»
  413. {
  414. auto list = make_shared<std::list<Rule<«adaptationClassName»>>>();
  415. «createRulesFunction.join("\n")»
  416. return list;
  417. }
  418. '''
  419. }
  420. }
  421. return new InOutRulesBlockResult(cpp, visitor.functionSignatures, visitor.vars, visitor.getGlobalVars);
  422. }
  423. /*
  424. * Calculates the semantic adaptation scalar variables via input ports and output ports.
  425. * Note: These a not fully populated yet as the in rules and out rules must be compiled first.
  426. */
  427. def LinkedHashMap<String, SAScalarVariable> calcSASVsFromInportsOutports(String definePrefix, EList<Port> inports,
  428. EList<Port> outports) {
  429. var LinkedHashMap<String, SAScalarVariable> saSVs = newLinkedHashMap();
  430. var int valueReference = 0;
  431. for (inport : inports) {
  432. var saSV = new SAScalarVariable();
  433. saSV.valueReference = valueReference++;
  434. saSV.name = inport.name;
  435. saSV.defineName = (definePrefix + inport.name).toUpperCase
  436. saSV.causality = SVCausality.input;
  437. saSVs.put(saSV.name, saSV);
  438. }
  439. for (outport : outports) {
  440. var saSV = new SAScalarVariable();
  441. saSV.valueReference = valueReference++;
  442. saSV.defineName = (definePrefix + outport.name).toUpperCase
  443. saSV.name = outport.name;
  444. saSV.causality = SVCausality.output;
  445. saSVs.put(saSV.name, saSV);
  446. }
  447. return saSVs;
  448. }
  449. }