CppGenerator.xtend 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838
  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 + " " + 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 <memory>
  325. #include "Fmu.h"
  326. using namespace std;
  327. using namespace fmi2;
  328. namespace adaptation
  329. {
  330. «fmusDefines»
  331. «SADefines»
  332. class «adapClassName» : public SemanticAdaptation<«adapClassName»>, public enable_shared_from_this<«adapClassName»>
  333. {
  334. public:
  335. «adapClassName»(shared_ptr<std::string> fmiInstanceName, shared_ptr<string> resourceLocation, const fmi2CallbackFunctions* functions);
  336. void initialize();
  337. virtual ~«adapClassName»();
  338. void setFmiValue(fmi2ValueReference id, int value);
  339. void setFmiValue(fmi2ValueReference id, bool value);
  340. void setFmiValue(fmi2ValueReference id, double value);
  341. void setFmiValue(fmi2ValueReference id, string value);
  342. int getFmiValueInteger(fmi2ValueReference id);
  343. bool getFmiValueBoolean(fmi2ValueReference id);
  344. double getFmiValueReal(fmi2ValueReference id);
  345. string getFmiValueString(fmi2ValueReference id);
  346. protected:
  347. «stateFunctions»
  348. private:
  349. «adapClassName»* getRuleThis();
  350. /*in rules*/
  351. «inRulesFuncSig.map[x | x+";"].join("\n")»
  352. /*out rules*/
  353. «outRulesFuncSig.map[x | x+";"].join("\n")»
  354. «crtlRulesFuncSig.map[x | x+";"].join("\n")»
  355. «FOR fmu : fmus»
  356. shared_ptr<FmuComponent> «fmu.name»;
  357. «ENDFOR»
  358. struct InternalState {
  359. «FOR sv : sVars»
  360. «Conversions.fmiTypeToCppType(sv.type)» «sv.name»;
  361. «IF sv.causality == SVCausality.input»
  362. bool isSet«sv.name»;
  363. «ENDIF»
  364. «ENDFOR»
  365. «FOR v : globalVariables.entrySet»
  366. «Conversions.fmiTypeToCppType(v.value.type)» «v.key»;
  367. «ENDFOR»
  368. };
  369. InternalState internalState;
  370. };
  371. }
  372. #endif
  373. ''';
  374. }
  375. /*
  376. * Compiles the source file constructor, destructor and the initialize function
  377. */
  378. def String compileDeAndConstructorAndInitialize(String adapClassName, ArrayList<InnerFMUData> fmus, String guid,
  379. String paramsCons, String inCons, String outCons, String crtlCons, MooreOrMealy machineType,
  380. ReactiveOrDelayed reactiveOrDealyed, boolean inputRules, boolean outputRules) {
  381. var ArrayList<String> initialisations = newArrayList();
  382. if (reactiveOrDealyed == ReactiveOrDelayed.DELAYED) {
  383. initialisations.add('''this->reactiveness = ReactiveOrDelayed::Delayed;''');
  384. } else if (reactiveOrDealyed == ReactiveOrDelayed.REACTIVE) {
  385. initialisations.add('''this->reactiveness = ReactiveOrDelayed::Reactive;''');
  386. }
  387. if (machineType == MooreOrMealy.MOORE) {
  388. initialisations.add('''this->machineType = MooreOrMealy::Moore;''');
  389. } else if (machineType == MooreOrMealy.MEALY) {
  390. initialisations.add('''this->machineType = MooreOrMealy::Mealy;''');
  391. }
  392. for (fmu : fmus) {
  393. initialisations.add('''
  394. auto path = make_shared<string>(*resourceLocation);
  395. path->append(string("«fmu.typeName».fmu"));
  396. auto «fmu.name»Fmu = make_shared<fmi2::Fmu>(*path);
  397. «fmu.name»Fmu->initialize();
  398. this->«fmu.name» = «fmu.name»Fmu->instantiate("«fmu.name»",fmi2CoSimulation, "«fmu.guid»", true, true, shared_from_this());
  399. if(this->«fmu.name»->component == NULL)
  400. this->lastErrorState = fmi2Fatal;
  401. this->instances->push_back(this->«fmu.name»);
  402. ''');
  403. }
  404. return '''
  405. «adapClassName»::«adapClassName»(shared_ptr<std::string> fmiInstanceName,shared_ptr<string> resourceLocation, const fmi2CallbackFunctions* functions) :
  406. SemanticAdaptation(fmiInstanceName, resourceLocation, «if(inputRules) "createInputRules()" else "NULL"», «if(outputRules) "createOutputRules()" else "NULL"», functions)
  407. {
  408. «paramsCons»
  409. «inCons»
  410. «outCons»
  411. «crtlCons»
  412. }
  413. void «adapClassName»::initialize()
  414. {
  415. «initialisations.join("\r\n")»
  416. }
  417. «adapClassName»::~«adapClassName»()
  418. {
  419. }
  420. ''';
  421. }
  422. /*
  423. * Compiles the source file function getRuleThis
  424. */
  425. def String compileGetRuleThis(String adaptationName) {
  426. return '''
  427. «adaptationName»* «adaptationName»::getRuleThis()
  428. {
  429. return this;
  430. }
  431. '''
  432. }
  433. /*
  434. * Compiles the source file functions getFmiValue<double, int, string, bool>
  435. */
  436. def String compileGetFmiValueFunctions(String adaptationName,
  437. LinkedHashMap<String, SAScalarVariable> variables) {
  438. var ArrayList<String> cpp = newArrayList();
  439. var List<ScalarVariable> convertedSASVs = variables.values.map[CalcSVar()].toList;
  440. var convertedSASVsOrdered = convertedSASVs.filter[causality === SVCausality.output].groupBy[type];
  441. for (SVType type : SVType.values) {
  442. val functionSignature = '''«Conversions.fmiTypeToCppType(type)» «adaptationName»::getFmiValue«type.toString»(fmi2ValueReference id)''';
  443. val functionReturn = '''return «Conversions.fmiTypeToCppDefaultValue(type)»''';
  444. if (convertedSASVsOrdered.containsKey(type)) {
  445. cpp.add(
  446. '''
  447. «functionSignature»
  448. {
  449. switch (id)
  450. {
  451. «FOR svInner : convertedSASVsOrdered.get(type)»
  452. case «variables.get(svInner.name).defineName»:
  453. {
  454. return this->internalState.«svInner.name»;
  455. }
  456. «ENDFOR»
  457. default:
  458. {
  459. «functionReturn»;
  460. }
  461. }
  462. }
  463. '''
  464. );
  465. } else {
  466. cpp.add(
  467. '''
  468. «functionSignature»
  469. {
  470. «functionReturn»;
  471. }
  472. '''
  473. );
  474. }
  475. }
  476. return cpp.join("\n");
  477. }
  478. /*
  479. * Compiles the source file functions setFmiValue<double, int, string, bool>*
  480. */
  481. def String compileSetFmiValueFunctions(String adapClassName,
  482. LinkedHashMap<String, SAScalarVariable> variables) {
  483. var ArrayList<String> cpp = newArrayList();
  484. var List<ScalarVariable> convertedSASVs = variables.values.map[CalcSVar()].filter [
  485. causality === SVCausality.input
  486. ].toList;
  487. var convertedSASVsOrdered = convertedSASVs.groupBy[type];
  488. for (SVType type : SVType.values) {
  489. cpp.add(
  490. '''
  491. void «adapClassName»::setFmiValue(fmi2ValueReference id, «Conversions.fmiTypeToCppType(type)» value)
  492. {
  493. «IF convertedSASVsOrdered.containsKey(type)»
  494. switch (id)
  495. {
  496. «FOR svInner : convertedSASVsOrdered.get(type)»
  497. case «variables.get(svInner.name).defineName»:
  498. {
  499. this->internalState.«svInner.name» = value;
  500. this->internalState.isSet«svInner.name» = true;
  501. break;
  502. }
  503. «ENDFOR»
  504. default:
  505. {
  506. }
  507. }
  508. «ENDIF»
  509. }
  510. '''
  511. );
  512. }
  513. return cpp.join("\n");
  514. }
  515. /*
  516. * Compiles the source file function executeInternalControlFlow.
  517. * Calculates necessary information on function signatures necessary for generation of the header file.
  518. */
  519. def InOutRulesBlockResult compileControlRuleBlock(ControlRuleBlock crtlRuleBlock, String adaptationClassName,
  520. String adaptationName, LinkedHashMap<String, LinkedHashMap<String, MappedScalarVariable>> mSVars,
  521. LinkedHashMap<String, SAScalarVariable> SASVs, LinkedHashMap<String, GlobalInOutVariable> params,
  522. LinkedHashMap<String, GlobalInOutVariable> inVars, LinkedHashMap<String, GlobalInOutVariable> outVars,
  523. LinkedHashMap<String, GlobalInOutVariable> crtlVars) {
  524. var cpp = "";
  525. val visitor = new ControlConditionSwitch(adaptationClassName, adaptationName, mSVars, SASVs, params, inVars,
  526. outVars, crtlVars);
  527. if (crtlRuleBlock !== null)
  528. cpp += visitor.doSwitch(crtlRuleBlock).code;
  529. return new InOutRulesBlockResult(cpp, visitor.functionSignatures);
  530. }
  531. def String SplitAtSpaceAndRemoveFirst(String content) {
  532. content.substring(content.indexOf(" ") + 1, content.length);
  533. }
  534. def String removeEmptyArgumentParenthesis(String content) {
  535. return content.substring(0, content.length - 2);
  536. }
  537. /*
  538. * Calculates necessary information on global in/out variables
  539. */
  540. def Pair<String, LinkedHashMap<String, GlobalInOutVariable>> compileRuleBlockVars(EList<Declaration> gVars,
  541. LinkedHashMap<String, GlobalInOutVariable> params) {
  542. val visitor = new RulesConditionSwitch("", "", "", null, null, params, null, null, null)
  543. return visitor.getGlobalVars(gVars);
  544. }
  545. /*
  546. * Compiles the source file functions <in/out>_rule_<condition, body, flush>.
  547. * Calculates necessary information on function signatures necessary for generation of the header file.
  548. * Added the extra input and output functions
  549. */
  550. def InOutRulesBlockResult compileInOutRuleBlocks(
  551. IORuleType ioType,
  552. InOutRules rulesBlock,
  553. String adaptationClassName,
  554. String adaptationName,
  555. LinkedHashMap<String, LinkedHashMap<String, MappedScalarVariable>> mSVars,
  556. LinkedHashMap<String, SAScalarVariable> SASVs,
  557. LinkedHashMap<String, GlobalInOutVariable> params,
  558. LinkedHashMap<String, GlobalInOutVariable> inVars,
  559. LinkedHashMap<String, GlobalInOutVariable> outVars,
  560. LinkedHashMap<String, GlobalInOutVariable> crtlVars,
  561. List<Port> portsWithSrcDep
  562. ) {
  563. val visitor = if (ioType == IORuleType.Input)
  564. new InRulesConditionSwitch(adaptationClassName, adaptationName, mSVars, SASVs, params, inVars,
  565. outVars, crtlVars)
  566. else
  567. new OutRulesConditionSwitch(adaptationClassName, adaptationName, mSVars, SASVs, params, inVars,
  568. outVars, crtlVars);
  569. val functionName = "create" + ioType + "Rules()";
  570. var String cpp = "";
  571. var List<String> allFunctionSignatures = newArrayList();
  572. if (rulesBlock !== null) {
  573. cpp += visitor.doSwitch(rulesBlock).code;
  574. }
  575. if (!visitor.functionSignatures.empty || !portsWithSrcDep.empty) {
  576. allFunctionSignatures.addAll(visitor.functionSignatures);
  577. var ArrayList<String> createRulesFunction = newArrayList();
  578. if (rulesBlock !== null) {
  579. // For-loop Handles the out rules defined in the sa file
  580. for (var int i = 0; i < (visitor.functionSignatures.length); i += 3) {
  581. createRulesFunction.add(
  582. '''
  583. list->push_back(
  584. (Rule<«adaptationClassName»>){
  585. &«adaptationClassName»::«visitor.functionSignatures.get(i).SplitAtSpaceAndRemoveFirst.removeEmptyArgumentParenthesis»,
  586. &«adaptationClassName»::«visitor.functionSignatures.get(i+1).SplitAtSpaceAndRemoveFirst.removeEmptyArgumentParenthesis»,
  587. &«adaptationClassName»::«visitor.functionSignatures.get(i+2).SplitAtSpaceAndRemoveFirst.removeEmptyArgumentParenthesis»
  588. });
  589. ''');
  590. }
  591. }
  592. var List<String> depFunctionSource = newArrayList();
  593. var List<String> depFunctionSignatures = newArrayList();
  594. for (var int i = 0; i < portsWithSrcDep.length; i++) {
  595. val currentPort = portsWithSrcDep.get(i);
  596. // Output ports uses source dependencies.
  597. // Input ports uses target dependencies;
  598. val dependency = (if (ioType == IORuleType.Input)
  599. currentPort.targetdependency
  600. else
  601. currentPort.sourcedependency);
  602. val newCount = visitor.functionSignatures.length + i + 1;
  603. val inOrOut = (if(ioType == IORuleType.Input) "in" else "out")
  604. val funcSigCon = visitor.createFunctionSignature('''condition''', "bool", newCount,
  605. depFunctionSignatures)
  606. val funcSigBody = visitor.createFunctionSignature('''body''', "void", newCount,
  607. depFunctionSignatures)
  608. val funcSigFlush = visitor.createFunctionSignature('''flush''', "void", newCount,
  609. depFunctionSignatures)
  610. val type = mSVars.get(dependency.owner.name).get(dependency.port.name).mappedSv.type;
  611. val define = mSVars.get(dependency.owner.name).get(dependency.port.name).define;
  612. var ruleCpp = "";
  613. if (ioType == IORuleType.Output) {
  614. val getValueCpp = '''getValue«Conversions.fmiTypeToGetValueString(type)»(«dependency.owner.name»,«define»)''';
  615. ruleCpp = '''
  616. «funcSigCon»{
  617. return true;
  618. }
  619. «funcSigBody»{
  620. this->internalState.stored_«dependency.owner.name»_«dependency.port.name» = «getValueCpp»;
  621. }
  622. «funcSigFlush»{
  623. this->internalState.«currentPort.name» = this->internalState.stored_«dependency.owner.name»_«dependency.port.name»;
  624. }
  625. '''
  626. } else if (ioType == IORuleType.Input) {
  627. val setValueCpp = '''setValue(«dependency.owner.name»,«define»,this->internalState.stored_«dependency.owner.name»_«dependency.port.name»);''';
  628. ruleCpp = '''
  629. «funcSigCon»{
  630. return true;
  631. }
  632. «funcSigBody»{
  633. this->internalState.stored_«dependency.owner.name»_«dependency.port.name» = this->internalState.«currentPort.name»;
  634. }
  635. «funcSigFlush»{
  636. «setValueCpp»
  637. }
  638. '''
  639. }
  640. cpp += ruleCpp;
  641. depFunctionSource.add(funcSigCon);
  642. depFunctionSource.add(funcSigBody);
  643. depFunctionSource.add(funcSigFlush);
  644. }
  645. allFunctionSignatures.addAll(depFunctionSignatures);
  646. for (var int i = 0; i < (depFunctionSource.length); i += 3) {
  647. createRulesFunction.add(
  648. '''
  649. list->push_back(
  650. (Rule<«adaptationClassName»>){
  651. &«depFunctionSource.get(i).SplitAtSpaceAndRemoveFirst.removeEmptyArgumentParenthesis»,
  652. &«depFunctionSource.get(i+1).SplitAtSpaceAndRemoveFirst.removeEmptyArgumentParenthesis»,
  653. &«depFunctionSource.get(i+2).SplitAtSpaceAndRemoveFirst.removeEmptyArgumentParenthesis»
  654. });
  655. ''');
  656. }
  657. // Handles the createOutputRules and createInputRules
  658. val functionPrefix = '''shared_ptr<list<Rule<«adaptationClassName»>>>''';
  659. allFunctionSignatures.add(functionPrefix + " " + functionName)
  660. cpp += '''
  661. «functionPrefix» «adaptationClassName»::«functionName»
  662. {
  663. auto list = make_shared<std::list<Rule<«adaptationClassName»>>>();
  664. «createRulesFunction.join("\n")»
  665. return list;
  666. }
  667. '''
  668. }
  669. return new InOutRulesBlockResult(cpp, allFunctionSignatures);
  670. }
  671. /*
  672. * Calculates the semantic adaptation scalar variables via input ports and output ports.
  673. * Note: These a not fully populated yet as the in rules and out rules must be compiled first.
  674. */
  675. def LinkedHashMap<String, SAScalarVariable> calcSASVsFromInportsOutports(String definePrefix,
  676. EList<Port> inports, EList<Port> outports,
  677. LinkedHashMap<String, LinkedHashMap<String, MappedScalarVariable>> mSVs) {
  678. var LinkedHashMap<String, SAScalarVariable> saSVs = newLinkedHashMap();
  679. var int valueReference = 0;
  680. for (inport : inports) {
  681. var saSV = new SAScalarVariable();
  682. saSV.SetPartOfMD(true);
  683. saSV.valueReference = valueReference++;
  684. saSV.name = inport.name;
  685. saSV.defineName = (definePrefix + inport.name).toUpperCase
  686. saSV.causality = SVCausality.input;
  687. saSVs.put(saSV.name, saSV);
  688. if (inport.targetdependency != null) {
  689. saSV.type = mSVs.get(inport.targetdependency.owner.name).get(inport.targetdependency.port.name).
  690. mappedSv.type;
  691. saSV.variability = mSVs.get(inport.targetdependency.owner.name).get(
  692. inport.targetdependency.port.name).mappedSv.variability;
  693. }
  694. }
  695. for (outport : outports) {
  696. var saSV = new SAScalarVariable();
  697. if (outport.sourcedependency !== null) {
  698. saSV.type = mSVs.get(outport.sourcedependency.owner.name).get(outport.sourcedependency.port.name).
  699. mappedSv.type;
  700. saSV.variability = mSVs.get(outport.sourcedependency.owner.name).get(
  701. outport.sourcedependency.port.name).mappedSv.variability;
  702. }
  703. saSV.SetPartOfMD(true);
  704. saSV.valueReference = valueReference++;
  705. saSV.defineName = (definePrefix + outport.name).toUpperCase
  706. saSV.name = outport.name;
  707. saSV.causality = SVCausality.output;
  708. saSVs.put(saSV.name, saSV);
  709. }
  710. return saSVs;
  711. }
  712. def List<File> getResourcePaths() {
  713. return resourcePaths;
  714. }
  715. }