CppGenerator.xtend 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  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 org.eclipse.emf.common.util.EList
  16. import be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.Port
  17. import be.uantwerpen.ansymo.semanticadaptation.cg.cpp.data.SVCausality
  18. import java.util.Collection
  19. import be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.InOutRules
  20. import be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.InRulesBlock
  21. import be.uantwerpen.ansymo.semanticadaptation.cg.cpp.data.InOutRulesBlockResult
  22. import be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.OutRulesBlock
  23. import be.uantwerpen.ansymo.semanticadaptation.cg.cpp.data.GlobalInOutVariable
  24. import be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.ControlRuleBlock
  25. import be.uantwerpen.ansymo.semanticadaptation.cg.cpp.data.RulesBlockResult
  26. import be.uantwerpen.ansymo.semanticadaptation.cg.cpp.data.ScalarVariable
  27. import java.util.List
  28. import be.uantwerpen.ansymo.semanticadaptation.cg.cpp.data.SVType
  29. import be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.ParamDeclarations
  30. import be.uantwerpen.ansymo.semanticadaptation.cg.cpp.data.InnerFMUData
  31. import be.uantwerpen.ansymo.semanticadaptation.cg.cpp.data.IORuleType
  32. import be.uantwerpen.ansymo.semanticadaptation.cg.cpp.data.RuleType
  33. import org.eclipse.emf.ecore.EObject
  34. import be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.Declaration
  35. import be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.MooreOrMealy
  36. import be.uantwerpen.ansymo.semanticadaptation.semanticAdaptation.ReactiveOrDelayed
  37. class CppGenerator extends SemanticAdaptationGenerator {
  38. private var IFileSystemAccess2 fsa;
  39. private List<File> resourcePaths = newArrayList();
  40. override void doGenerate(Resource resource, IFileSystemAccess2 fsa, IGeneratorContext context) {
  41. this.fsa = fsa;
  42. for (SemanticAdaptation type : resource.allContents.toIterable.filter(SemanticAdaptation)) {
  43. type.compile;
  44. }
  45. }
  46. // TODO: Verify adaptation.name is not a C++ keyword
  47. def void compile(SemanticAdaptation adaptation) {
  48. for (Adaptation adap : adaptation.elements.filter(Adaptation)) {
  49. // Value used for scoping variables in the .sa file
  50. val adapInteralRefName = adap.name;
  51. // The CPP class name
  52. val adapClassName = adap.name.toFirstUpper;
  53. // This is the external name used in the model description file for the semantic adaptation FMU
  54. val adapExternalName = adap.type.name;
  55. // List of inner FMUs
  56. var ArrayList<InnerFMUData> innerFMUsData = newArrayList();
  57. val innerFmus = adap.inner.eAllContents.toList.filter(InnerFMU);
  58. if (innerFmus.isEmpty) {
  59. throw new IncorrectAmountOfElementsException("The adaptation does not contain any InnerFMUs.")
  60. }
  61. /*
  62. * This map will contain scalar variables from the FMUs defined in InnerFMU.
  63. * The structure is fmuName -> (SVName -> mappedSV) where SVName = mappedSV.name for easy lookup.
  64. * The mappedSV contains the original scalar variable and extra data such as define name.
  65. */
  66. var LinkedHashMap<String, LinkedHashMap<String, MappedScalarVariable>> mappedScalarVariables = newLinkedHashMap();
  67. /*
  68. * Loading the FMU defined in InnerFMU, the related model description file and its scalar variables.
  69. */
  70. // TODO: Add support for multiple inner fmus. Only partially supported
  71. var ModelDescription md;
  72. for (fmu : adap.inner.eAllContents.toList.filter(InnerFMU)) {
  73. val fmuFile = new File(fmu.path.replace('\"', ''));
  74. this.resourcePaths.add(fmuFile);
  75. md = new ModelDescription(fmu.name, fmu.type.name, fmuFile);
  76. innerFMUsData.add(new InnerFMUData(fmu.name, fmu.type.name, md.guid));
  77. // fmus.add(fmu.name -> fmu.type.name);
  78. val LinkedHashMap<String, MappedScalarVariable> mSV = newLinkedHashMap();
  79. for (sv : md.sv.values) {
  80. var mappedSv = new MappedScalarVariable(sv);
  81. mappedSv.define = (mappedSv.mappedSv.owner + mappedSv.mappedSv.name).toUpperCase;
  82. mSV.put(mappedSv.mappedSv.name, mappedSv);
  83. }
  84. mappedScalarVariables.put(fmu.name, mSV);
  85. }
  86. // C++ Defines for accessing FMU scalar variables.
  87. val String fmusDefines = calcDefines(mappedScalarVariables);
  88. /*
  89. * This map contains all the ScalarVariables for the semantic adaptation.
  90. * Some of them are not populated yet, but they will be during the compilation of the in and out rule blocks.
  91. */
  92. var LinkedHashMap<String, SAScalarVariable> SASVs = calcSASVsFromInportsOutports(adapInteralRefName,
  93. adap.inports, adap.outports, mappedScalarVariables)
  94. // C++ defines for accessing semantic adaptation scalar variables
  95. val String SADefines = calcSADefines(SASVs.values);
  96. // Compile Params
  97. var LinkedHashMap<String, GlobalInOutVariable> params = newLinkedHashMap;
  98. val String paramsConstructorSource = compileParams(params, adap.params);
  99. // Handles cases like this: output ports tau <- loop_sa.tau
  100. var List<Port> outPortsWithSrcDep = newArrayList();
  101. if (adap.outports !== null) {
  102. outPortsWithSrcDep = adap.outports.filter[x|x.sourcedependency !== null].toList;
  103. }
  104. var List<Port> inPortsWithSrcDep = newArrayList();
  105. if (adap.inports !== null) {
  106. inPortsWithSrcDep = adap.inports.filter[x|x.targetdependency !== null].toList;
  107. }
  108. // The three rule blocks
  109. val inRuleBlock = adap.in;
  110. val outRuleBlock = adap.out;
  111. val crtlRuleBlock = adap.control;
  112. // Get the control vars, in vars, and out vars
  113. var inVars = if(inRuleBlock !== null) compileRuleBlockVars(inRuleBlock.globalInVars, params);
  114. var outVars = if(outRuleBlock !== null) compileRuleBlockVars(outRuleBlock.globalOutVars, params);
  115. val crtlVars = if(crtlRuleBlock !== null) compileRuleBlockVars(crtlRuleBlock.globalCtrlVars, params);
  116. /*
  117. * Support for source dependency: output ports tau <- loop_sa.tau
  118. * Only carried out for outVars.
  119. * TODO: Do for inVars
  120. */
  121. for (Port port : outPortsWithSrcDep) {
  122. val name = '''stored_«port.sourcedependency.owner.name»_«port.sourcedependency.port.name»''';
  123. val type = mappedScalarVariables.get(port.sourcedependency.owner.name).get(
  124. port.sourcedependency.port.name).mappedSv.type;
  125. val globVar = new GlobalInOutVariable(name, type);
  126. val sourceDepType = mappedScalarVariables.get(port.sourcedependency.owner.name).get(
  127. port.sourcedependency.port.name).mappedSv.type;
  128. val constructorInit = '''this->internalState.«name» = «Conversions.fmiTypeToCppDefaultValue(sourceDepType)»;'''
  129. if (outVars !== null) {
  130. outVars.value.put(name, globVar);
  131. outVars = outVars.key.concat(constructorInit) -> outVars.value;
  132. } else {
  133. val LinkedHashMap<String, GlobalInOutVariable> gVars = newLinkedHashMap();
  134. gVars.put(name, globVar)
  135. outVars = constructorInit -> gVars;
  136. }
  137. }
  138. for (Port port : inPortsWithSrcDep) {
  139. val dependency = port.targetdependency;
  140. val name = '''stored_«dependency.owner.name»_«dependency.port.name»'''
  141. val type = mappedScalarVariables.get(dependency.owner.name).get(dependency.port.name).mappedSv.type;
  142. val globVar = new GlobalInOutVariable(name, type);
  143. val constructorInit = '''this->internalState.«name» = «Conversions.fmiTypeToCppDefaultValue(type)»;''';
  144. if (inVars !== null) {
  145. inVars.value.put(name, globVar);
  146. inVars = inVars.key.concat("\n" + constructorInit) -> inVars.value;
  147. } else {
  148. val LinkedHashMap<String, GlobalInOutVariable> gVars = newLinkedHashMap();
  149. gVars.put(name, globVar);
  150. inVars = constructorInit -> gVars;
  151. }
  152. }
  153. // Compile the in rules
  154. val inRules = if(adap.in !== null) adap.in as InOutRules else null;
  155. val inRuleResult = compileInOutRuleBlocks(IORuleType.Input, inRules, adapClassName, adapInteralRefName,
  156. mappedScalarVariables, SASVs, params, if(inVars !== null) inVars.value else null,
  157. if(outVars !== null) outVars.value else null, if(crtlVars !== null) crtlVars.value else null,
  158. inPortsWithSrcDep);
  159. // Compile the out rules
  160. val outRules = if(adap.out !== null) adap.out as InOutRules else null;
  161. val outRuleResult = compileInOutRuleBlocks(IORuleType.Output, outRules, adapClassName,
  162. adapInteralRefName, mappedScalarVariables, SASVs, params,
  163. if(inVars !== null) inVars.value else null, if(outVars !== null) outVars.value else null,
  164. if(crtlVars !== null) crtlVars.value else null, outPortsWithSrcDep);
  165. // Compile the Control Rules. These might use the out vars, so pass these along.
  166. val crtlRules = if(adap.control !== null) adap.control else null;
  167. val crtlRuleResult = compileControlRuleBlock(crtlRules, adapClassName, adapInteralRefName,
  168. mappedScalarVariables, SASVs, params, if(inVars !== null) inVars.value else null,
  169. if(outVars !== null) outVars.value else null, if(crtlVars !== null) crtlVars.value else null);
  170. /*
  171. * Compile the constructor, destructor and initialize functions
  172. */
  173. val String deAndConstructorAndInitializeSource = compileDeAndConstructorAndInitialize(
  174. adapClassName,
  175. innerFMUsData,
  176. md.guid,
  177. paramsConstructorSource,
  178. if(inVars !== null) inVars.key else "",
  179. if(outVars !== null) outVars.key else "",
  180. if(crtlVars !== null) crtlVars.key else "",
  181. adap.machine,
  182. adap.reactiveness,
  183. inRules !== null || inPortsWithSrcDep.length > 0,
  184. outRules !== null || outPortsWithSrcDep.length > 0
  185. );
  186. /*
  187. * Compile getRuleThis function
  188. */
  189. val String getRuleThisSource = compileGetRuleThis(adapClassName);
  190. /*
  191. * The in and out rules have populated the semantic adaptation scalar variables we can generate the getFmiValue* and setFmiValue functions.
  192. */
  193. val String getFuncsSource = compileGetFmiValueFunctions(adapClassName, SASVs);
  194. val String setFuncsSource = compileSetFmiValueFunctions(adapClassName, SASVs);
  195. // Compile the state functions
  196. val Pair<String,String> stateFunctions = compileStateFunctions(adapClassName);
  197. // Compile the source file
  198. val String sourceInclude = '''#include "«adapClassName».h"''';
  199. val sourceFile = compileSource(
  200. sourceInclude,
  201. deAndConstructorAndInitializeSource,
  202. getRuleThisSource,
  203. getFuncsSource,
  204. setFuncsSource,
  205. inRuleResult.generatedCpp,
  206. outRuleResult.generatedCpp,
  207. crtlRuleResult.generatedCpp,
  208. stateFunctions.value
  209. );
  210. fsa.generateFile(adapClassName + ".cpp", sourceFile);
  211. // Merge the global variables for use in compiling the header file.
  212. // TODO: Check for duplicates
  213. var LinkedHashMap<String, GlobalInOutVariable> allGVars = newLinkedHashMap();
  214. allGVars.putAll(params);
  215. if (inVars !== null)
  216. allGVars.putAll(inVars.value);
  217. if (outVars !== null)
  218. allGVars.putAll(outVars.value);
  219. if (crtlVars !== null)
  220. allGVars.putAll(crtlVars.value);
  221. // Compile the header file
  222. val headerFile = compileHeader(
  223. adapClassName,
  224. fmusDefines,
  225. SADefines,
  226. inRuleResult.functionSignatures,
  227. outRuleResult.functionSignatures,
  228. crtlRuleResult.functionSignatures,
  229. allGVars,
  230. innerFMUsData,
  231. SASVs.values.map[CalcSVar()].toList,
  232. stateFunctions.key
  233. );
  234. fsa.generateFile(adapClassName + ".h", headerFile);
  235. // Compile the model description file
  236. val modelDescCreator = new ModelDescriptionCreator(adapExternalName);
  237. val modelDescription = modelDescCreator.generateModelDescription(SASVs.values);
  238. fsa.generateFile("modelDescription.xml", modelDescription);
  239. // Compile the fmu.cpp file
  240. val fmuCppFile = FmuGenerator.genFmuCppFile(adapClassName);
  241. fsa.generateFile("Fmu.cpp", fmuCppFile);
  242. }
  243. }
  244. def String compileParams(LinkedHashMap<String, GlobalInOutVariable> gVars, EList<ParamDeclarations> params) {
  245. val paramsConditionSwitch = new ParamConditionSwitch(gVars);
  246. var String paramsConstructorSource = "";
  247. for (paramDecl : params) {
  248. val doSwitchRes = paramsConditionSwitch.doSwitch(paramDecl);
  249. paramsConstructorSource += doSwitchRes.code;
  250. }
  251. return paramsConstructorSource;
  252. }
  253. def calcSADefines(Collection<SAScalarVariable> variables) {
  254. var ArrayList<String> defines = newArrayList();
  255. for (SASV : variables) {
  256. defines.add("#define " + SASV.defineName + " " + SASV.valueReference);
  257. }
  258. return defines.join("\n");
  259. }
  260. def calcDefines(LinkedHashMap<String, LinkedHashMap<String, MappedScalarVariable>> map) {
  261. var ArrayList<String> defines = newArrayList();
  262. for (fmuEntries : map.entrySet) {
  263. for (MappedScalarVariable mSV : fmuEntries.value.values) {
  264. defines.add("#define " + mSV.define.replace('(','_').replace(')','_') + " " + mSV.valueReference);
  265. }
  266. }
  267. return defines.join("\n");
  268. }
  269. def Pair<String,String> compileStateFunctions(String saName)
  270. {
  271. return
  272. '''
  273. fmi2FMUstate getInternalFMUState();
  274. void setInternalFMUState(fmi2FMUstate state);
  275. void freeInternalFMUState(fmi2FMUstate state);
  276. '''
  277. ->
  278. '''
  279. fmi2FMUstate «saName»::getInternalFMUState()
  280. {
  281. InternalState* s = new InternalState();
  282. *s = this->internalState;
  283. return s;
  284. }
  285. void «saName»::setInternalFMUState(fmi2FMUstate state)
  286. {
  287. this->internalState = *(InternalState*)state;
  288. }
  289. void «saName»::freeInternalFMUState(fmi2FMUstate state)
  290. {
  291. delete (InternalState*)state;
  292. }''';
  293. }
  294. // Compiles the final source file
  295. def String compileSource(String include, String constructor, String getRuleThis, String getFunctions,
  296. String setFunctions, String inFunctions, String outFunctions, String controlFunction, String stateFunctions) {
  297. return '''
  298. «include»
  299. namespace adaptation
  300. {
  301. «constructor»
  302. «getRuleThis»
  303. «getFunctions»
  304. «setFunctions»
  305. «inFunctions»
  306. «controlFunction»
  307. «outFunctions»
  308. «stateFunctions»
  309. }
  310. '''
  311. }
  312. /*
  313. * Compiles the header file split into two: The first part contains the includes and using namespace definitions and start the ,
  314. * the second part contains the class
  315. */
  316. def String compileHeader(String adapClassName, String fmusDefines, String SADefines,
  317. List<String> inRulesFuncSig, List<String> outRulesFuncSig, List<String> crtlRulesFuncSig,
  318. LinkedHashMap<String, GlobalInOutVariable> globalVariables, ArrayList<InnerFMUData> fmus,
  319. Collection<ScalarVariable> sVars, String stateFunctions) {
  320. return '''
  321. #ifndef SRC_«adapClassName.toUpperCase»_H
  322. #define SRC_«adapClassName.toUpperCase»_H
  323. #include "SemanticAdaptation.h"
  324. #include "HyfMath.h"
  325. #include <memory>
  326. #include "Fmu.h"
  327. using namespace std;
  328. using namespace fmi2;
  329. namespace adaptation
  330. {
  331. «fmusDefines»
  332. «SADefines»
  333. class «adapClassName» : public SemanticAdaptation<«adapClassName»>, public enable_shared_from_this<«adapClassName»>
  334. {
  335. public:
  336. «adapClassName»(shared_ptr<std::string> fmiInstanceName, shared_ptr<string> resourceLocation, const fmi2CallbackFunctions* functions);
  337. void initialize();
  338. virtual ~«adapClassName»();
  339. void setFmiValue(fmi2ValueReference id, int value);
  340. void setFmiValue(fmi2ValueReference id, bool value);
  341. void setFmiValue(fmi2ValueReference id, double value);
  342. void setFmiValue(fmi2ValueReference id, string value);
  343. int getFmiValueInteger(fmi2ValueReference id);
  344. bool getFmiValueBoolean(fmi2ValueReference id);
  345. double getFmiValueReal(fmi2ValueReference id);
  346. string getFmiValueString(fmi2ValueReference id);
  347. protected:
  348. «stateFunctions»
  349. private:
  350. «adapClassName»* getRuleThis();
  351. /*in rules*/
  352. «inRulesFuncSig.map[x | x+";"].join("\n")»
  353. /*out rules*/
  354. «outRulesFuncSig.map[x | x+";"].join("\n")»
  355. «crtlRulesFuncSig.map[x | x+";"].join("\n")»
  356. «FOR fmu : fmus»
  357. shared_ptr<FmuComponent> «fmu.name»;
  358. «ENDFOR»
  359. struct InternalState {
  360. «FOR sv : sVars»
  361. «Conversions.fmiTypeToCppType(sv.type)» «sv.name»;
  362. «IF sv.causality == SVCausality.input»
  363. bool isSet«sv.name»;
  364. «ENDIF»
  365. «ENDFOR»
  366. «FOR v : globalVariables.entrySet»
  367. «Conversions.fmiTypeToCppType(v.value.type)» «v.key»;
  368. «ENDFOR»
  369. };
  370. InternalState internalState;
  371. };
  372. }
  373. #endif
  374. ''';
  375. }
  376. /*
  377. * Compiles the source file constructor, destructor and the initialize function
  378. */
  379. def String compileDeAndConstructorAndInitialize(String adapClassName, ArrayList<InnerFMUData> fmus, String guid,
  380. String paramsCons, String inCons, String outCons, String crtlCons, MooreOrMealy machineType,
  381. ReactiveOrDelayed reactiveOrDealyed, boolean inputRules, boolean outputRules) {
  382. var ArrayList<String> initialisations = newArrayList();
  383. if (reactiveOrDealyed == ReactiveOrDelayed.DELAYED) {
  384. initialisations.add('''this->reactiveness = ReactiveOrDelayed::Delayed;''');
  385. } else if (reactiveOrDealyed == ReactiveOrDelayed.REACTIVE) {
  386. initialisations.add('''this->reactiveness = ReactiveOrDelayed::Reactive;''');
  387. }
  388. if (machineType == MooreOrMealy.MOORE) {
  389. initialisations.add('''this->machineType = MooreOrMealy::Moore;''');
  390. } else if (machineType == MooreOrMealy.MEALY) {
  391. initialisations.add('''this->machineType = MooreOrMealy::Mealy;''');
  392. }
  393. var pathCount = 1;
  394. for (fmu : fmus) {
  395. val pathName = '''path«pathCount»''';
  396. pathCount++;
  397. initialisations.add('''
  398. auto «pathName» = make_shared<string>(*resourceLocation);
  399. «pathName»->append(string("«fmu.typeName».fmu"));
  400. auto «fmu.name»Fmu = make_shared<fmi2::Fmu>(*«pathName»);
  401. «fmu.name»Fmu->initialize();
  402. this->«fmu.name» = «fmu.name»Fmu->instantiate("«fmu.name»",fmi2CoSimulation, "«fmu.guid»", true, true, shared_from_this());
  403. if(this->«fmu.name»->component == NULL)
  404. this->lastErrorState = fmi2Fatal;
  405. this->instances->push_back(this->«fmu.name»);
  406. ''');
  407. }
  408. return '''
  409. «adapClassName»::«adapClassName»(shared_ptr<std::string> fmiInstanceName,shared_ptr<string> resourceLocation, const fmi2CallbackFunctions* functions) :
  410. SemanticAdaptation(fmiInstanceName, resourceLocation, «if(inputRules) "createInputRules()" else "NULL"», «if(outputRules) "createOutputRules()" else "NULL"», functions)
  411. {
  412. «paramsCons»
  413. «inCons»
  414. «outCons»
  415. «crtlCons»
  416. }
  417. void «adapClassName»::initialize()
  418. {
  419. «initialisations.join("\r\n")»
  420. }
  421. «adapClassName»::~«adapClassName»()
  422. {
  423. }
  424. ''';
  425. }
  426. /*
  427. * Compiles the source file function getRuleThis
  428. */
  429. def String compileGetRuleThis(String adaptationName) {
  430. return '''
  431. «adaptationName»* «adaptationName»::getRuleThis()
  432. {
  433. return this;
  434. }
  435. '''
  436. }
  437. /*
  438. * Compiles the source file functions getFmiValue<double, int, string, bool>
  439. */
  440. def String compileGetFmiValueFunctions(String adaptationName,
  441. LinkedHashMap<String, SAScalarVariable> variables) {
  442. var ArrayList<String> cpp = newArrayList();
  443. var List<ScalarVariable> convertedSASVs = variables.values.map[CalcSVar()].toList;
  444. var convertedSASVsOrdered = convertedSASVs.filter[causality === SVCausality.output].groupBy[type];
  445. for (SVType type : SVType.values) {
  446. val functionSignature = '''«Conversions.fmiTypeToCppType(type)» «adaptationName»::getFmiValue«type.toString»(fmi2ValueReference id)''';
  447. val functionReturn = '''return «Conversions.fmiTypeToCppDefaultValue(type)»''';
  448. if (convertedSASVsOrdered.containsKey(type)) {
  449. cpp.add(
  450. '''
  451. «functionSignature»
  452. {
  453. switch (id)
  454. {
  455. «FOR svInner : convertedSASVsOrdered.get(type)»
  456. case «variables.get(svInner.name).defineName»:
  457. {
  458. return this->internalState.«svInner.name»;
  459. }
  460. «ENDFOR»
  461. default:
  462. {
  463. «functionReturn»;
  464. }
  465. }
  466. }
  467. '''
  468. );
  469. } else {
  470. cpp.add(
  471. '''
  472. «functionSignature»
  473. {
  474. «functionReturn»;
  475. }
  476. '''
  477. );
  478. }
  479. }
  480. return cpp.join("\n");
  481. }
  482. /*
  483. * Compiles the source file functions setFmiValue<double, int, string, bool>*
  484. */
  485. def String compileSetFmiValueFunctions(String adapClassName,
  486. LinkedHashMap<String, SAScalarVariable> variables) {
  487. var ArrayList<String> cpp = newArrayList();
  488. var List<ScalarVariable> convertedSASVs = variables.values.map[CalcSVar()].filter [
  489. causality === SVCausality.input
  490. ].toList;
  491. var convertedSASVsOrdered = convertedSASVs.groupBy[type];
  492. for (SVType type : SVType.values) {
  493. cpp.add(
  494. '''
  495. void «adapClassName»::setFmiValue(fmi2ValueReference id, «Conversions.fmiTypeToCppType(type)» value)
  496. {
  497. «IF convertedSASVsOrdered.containsKey(type)»
  498. switch (id)
  499. {
  500. «FOR svInner : convertedSASVsOrdered.get(type)»
  501. case «variables.get(svInner.name).defineName»:
  502. {
  503. this->internalState.«svInner.name» = value;
  504. this->internalState.isSet«svInner.name» = true;
  505. break;
  506. }
  507. «ENDFOR»
  508. default:
  509. {
  510. }
  511. }
  512. «ENDIF»
  513. }
  514. '''
  515. );
  516. }
  517. return cpp.join("\n");
  518. }
  519. /*
  520. * Compiles the source file function executeInternalControlFlow.
  521. * Calculates necessary information on function signatures necessary for generation of the header file.
  522. */
  523. def InOutRulesBlockResult compileControlRuleBlock(ControlRuleBlock crtlRuleBlock, String adaptationClassName,
  524. String adaptationName, LinkedHashMap<String, LinkedHashMap<String, MappedScalarVariable>> mSVars,
  525. LinkedHashMap<String, SAScalarVariable> SASVs, LinkedHashMap<String, GlobalInOutVariable> params,
  526. LinkedHashMap<String, GlobalInOutVariable> inVars, LinkedHashMap<String, GlobalInOutVariable> outVars,
  527. LinkedHashMap<String, GlobalInOutVariable> crtlVars) {
  528. var cpp = "";
  529. val visitor = new ControlConditionSwitch(adaptationClassName, adaptationName, mSVars, SASVs, params, inVars,
  530. outVars, crtlVars);
  531. if (crtlRuleBlock !== null)
  532. cpp += visitor.doSwitch(crtlRuleBlock).code;
  533. return new InOutRulesBlockResult(cpp, visitor.functionSignatures);
  534. }
  535. def String SplitAtSpaceAndRemoveFirst(String content) {
  536. content.substring(content.indexOf(" ") + 1, content.length);
  537. }
  538. def String removeEmptyArgumentParenthesis(String content) {
  539. return content.substring(0, content.length - 2);
  540. }
  541. /*
  542. * Calculates necessary information on global in/out variables
  543. */
  544. def Pair<String, LinkedHashMap<String, GlobalInOutVariable>> compileRuleBlockVars(EList<Declaration> gVars,
  545. LinkedHashMap<String, GlobalInOutVariable> params) {
  546. val visitor = new RulesConditionSwitch("", "", "", null, null, params, null, null, null)
  547. return visitor.getGlobalVars(gVars);
  548. }
  549. /*
  550. * Compiles the source file functions <in/out>_rule_<condition, body, flush>.
  551. * Calculates necessary information on function signatures necessary for generation of the header file.
  552. * Added the extra input and output functions
  553. */
  554. def InOutRulesBlockResult compileInOutRuleBlocks(
  555. IORuleType ioType,
  556. InOutRules rulesBlock,
  557. String adaptationClassName,
  558. String adaptationName,
  559. LinkedHashMap<String, LinkedHashMap<String, MappedScalarVariable>> mSVars,
  560. LinkedHashMap<String, SAScalarVariable> SASVs,
  561. LinkedHashMap<String, GlobalInOutVariable> params,
  562. LinkedHashMap<String, GlobalInOutVariable> inVars,
  563. LinkedHashMap<String, GlobalInOutVariable> outVars,
  564. LinkedHashMap<String, GlobalInOutVariable> crtlVars,
  565. List<Port> portsWithSrcDep
  566. ) {
  567. val visitor = if (ioType == IORuleType.Input)
  568. new InRulesConditionSwitch(adaptationClassName, adaptationName, mSVars, SASVs, params, inVars,
  569. outVars, crtlVars)
  570. else
  571. new OutRulesConditionSwitch(adaptationClassName, adaptationName, mSVars, SASVs, params, inVars,
  572. outVars, crtlVars);
  573. val functionName = "create" + ioType + "Rules()";
  574. var String cpp = "";
  575. var List<String> allFunctionSignatures = newArrayList();
  576. if (rulesBlock !== null) {
  577. cpp += visitor.doSwitch(rulesBlock).code;
  578. }
  579. if (!visitor.functionSignatures.empty || !portsWithSrcDep.empty) {
  580. allFunctionSignatures.addAll(visitor.functionSignatures);
  581. var ArrayList<String> createRulesFunction = newArrayList();
  582. if (rulesBlock !== null) {
  583. // For-loop Handles the out rules defined in the sa file
  584. for (var int i = 0; i < (visitor.functionSignatures.length); i += 3) {
  585. createRulesFunction.add(
  586. '''
  587. list->push_back(
  588. (Rule<«adaptationClassName»>){
  589. &«adaptationClassName»::«visitor.functionSignatures.get(i).SplitAtSpaceAndRemoveFirst.removeEmptyArgumentParenthesis»,
  590. &«adaptationClassName»::«visitor.functionSignatures.get(i+1).SplitAtSpaceAndRemoveFirst.removeEmptyArgumentParenthesis»,
  591. &«adaptationClassName»::«visitor.functionSignatures.get(i+2).SplitAtSpaceAndRemoveFirst.removeEmptyArgumentParenthesis»
  592. });
  593. ''');
  594. }
  595. }
  596. var List<String> depFunctionSource = newArrayList();
  597. var List<String> depFunctionSignatures = newArrayList();
  598. for (var int i = 0; i < portsWithSrcDep.length; i++) {
  599. val currentPort = portsWithSrcDep.get(i);
  600. // Output ports uses source dependencies.
  601. // Input ports uses target dependencies;
  602. val dependency = (if (ioType == IORuleType.Input)
  603. currentPort.targetdependency
  604. else
  605. currentPort.sourcedependency);
  606. val newCount = visitor.functionSignatures.length + i + 1;
  607. val inOrOut = (if(ioType == IORuleType.Input) "in" else "out")
  608. val funcSigCon = visitor.createFunctionSignature('''condition''', "bool", newCount,
  609. depFunctionSignatures)
  610. val funcSigBody = visitor.createFunctionSignature('''body''', "void", newCount,
  611. depFunctionSignatures)
  612. val funcSigFlush = visitor.createFunctionSignature('''flush''', "void", newCount,
  613. depFunctionSignatures)
  614. val type = mSVars.get(dependency.owner.name).get(dependency.port.name).mappedSv.type;
  615. val define = mSVars.get(dependency.owner.name).get(dependency.port.name).define;
  616. var ruleCpp = "";
  617. if (ioType == IORuleType.Output) {
  618. val getValueCpp = '''getValue«Conversions.fmiTypeToGetValueString(type)»(«dependency.owner.name»,«define»)''';
  619. ruleCpp = '''
  620. «funcSigCon»{
  621. return true;
  622. }
  623. «funcSigBody»{
  624. this->internalState.stored_«dependency.owner.name»_«dependency.port.name» = «getValueCpp»;
  625. }
  626. «funcSigFlush»{
  627. this->internalState.«currentPort.name» = this->internalState.stored_«dependency.owner.name»_«dependency.port.name»;
  628. }
  629. '''
  630. } else if (ioType == IORuleType.Input) {
  631. val setValueCpp = '''setValue(«dependency.owner.name»,«define»,this->internalState.stored_«dependency.owner.name»_«dependency.port.name»);''';
  632. ruleCpp = '''
  633. «funcSigCon»{
  634. return true;
  635. }
  636. «funcSigBody»{
  637. this->internalState.stored_«dependency.owner.name»_«dependency.port.name» = this->internalState.«currentPort.name»;
  638. }
  639. «funcSigFlush»{
  640. «setValueCpp»
  641. }
  642. '''
  643. }
  644. cpp += ruleCpp;
  645. depFunctionSource.add(funcSigCon);
  646. depFunctionSource.add(funcSigBody);
  647. depFunctionSource.add(funcSigFlush);
  648. }
  649. allFunctionSignatures.addAll(depFunctionSignatures);
  650. for (var int i = 0; i < (depFunctionSource.length); i += 3) {
  651. createRulesFunction.add(
  652. '''
  653. list->push_back(
  654. (Rule<«adaptationClassName»>){
  655. &«depFunctionSource.get(i).SplitAtSpaceAndRemoveFirst.removeEmptyArgumentParenthesis»,
  656. &«depFunctionSource.get(i+1).SplitAtSpaceAndRemoveFirst.removeEmptyArgumentParenthesis»,
  657. &«depFunctionSource.get(i+2).SplitAtSpaceAndRemoveFirst.removeEmptyArgumentParenthesis»
  658. });
  659. ''');
  660. }
  661. // Handles the createOutputRules and createInputRules
  662. val functionPrefix = '''shared_ptr<list<Rule<«adaptationClassName»>>>''';
  663. allFunctionSignatures.add(functionPrefix + " " + functionName)
  664. cpp += '''
  665. «functionPrefix» «adaptationClassName»::«functionName»
  666. {
  667. auto list = make_shared<std::list<Rule<«adaptationClassName»>>>();
  668. «createRulesFunction.join("\n")»
  669. return list;
  670. }
  671. '''
  672. }
  673. return new InOutRulesBlockResult(cpp, allFunctionSignatures);
  674. }
  675. /*
  676. * Calculates the semantic adaptation scalar variables via input ports and output ports.
  677. * Note: These a not fully populated yet as the in rules and out rules must be compiled first.
  678. */
  679. def LinkedHashMap<String, SAScalarVariable> calcSASVsFromInportsOutports(String definePrefix,
  680. EList<Port> inports, EList<Port> outports,
  681. LinkedHashMap<String, LinkedHashMap<String, MappedScalarVariable>> mSVs) {
  682. var LinkedHashMap<String, SAScalarVariable> saSVs = newLinkedHashMap();
  683. var int valueReference = 0;
  684. for (inport : inports) {
  685. var saSV = new SAScalarVariable();
  686. saSV.SetPartOfMD(true);
  687. saSV.valueReference = valueReference++;
  688. saSV.name = inport.name;
  689. saSV.defineName = (definePrefix + inport.name).toUpperCase
  690. saSV.causality = SVCausality.input;
  691. saSVs.put(saSV.name, saSV);
  692. if (inport.targetdependency != null) {
  693. saSV.type = mSVs.get(inport.targetdependency.owner.name).get(inport.targetdependency.port.name).
  694. mappedSv.type;
  695. saSV.variability = mSVs.get(inport.targetdependency.owner.name).get(
  696. inport.targetdependency.port.name).mappedSv.variability;
  697. }
  698. }
  699. for (outport : outports) {
  700. var saSV = new SAScalarVariable();
  701. if (outport.sourcedependency !== null) {
  702. saSV.type = mSVs.get(outport.sourcedependency.owner.name).get(outport.sourcedependency.port.name).
  703. mappedSv.type;
  704. saSV.variability = mSVs.get(outport.sourcedependency.owner.name).get(
  705. outport.sourcedependency.port.name).mappedSv.variability;
  706. }
  707. saSV.SetPartOfMD(true);
  708. saSV.valueReference = valueReference++;
  709. saSV.defineName = (definePrefix + outport.name).toUpperCase
  710. saSV.name = outport.name;
  711. saSV.causality = SVCausality.output;
  712. saSVs.put(saSV.name, saSV);
  713. }
  714. return saSVs;
  715. }
  716. def List<File> getResourcePaths() {
  717. return resourcePaths;
  718. }
  719. }