-
Notifications
You must be signed in to change notification settings - Fork 298
/
CodegenCpp.tpl
7562 lines (6651 loc) · 253 KB
/
CodegenCpp.tpl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package CodegenCpp
import interface SimCodeTV;
// SECTION: SIMULATION TARGET, ROOT TEMPLATE
template translateModel(SimCode simCode) ::=
match simCode
case SIMCODE(modelInfo = MODELINFO(__)) then
let target = simulationCodeTarget()
let()= textFile(simulationHeaderFile(simCode), '<%lastIdentOfPath(modelInfo.name)%>.h')
let()= textFile(simulationCppFile(simCode), '<%lastIdentOfPath(modelInfo.name)%>.cpp')
let()= textFile(simulationFunctionsHeaderFile(simCode,modelInfo.functions,literals), 'Functions.h')
let()= textFile(simulationFunctionsFile(simCode, modelInfo.functions,literals), 'Functions.cpp')
let()= textFile(simulationMakefile(target,simCode), '<%fileNamePrefix%>.makefile')
// algloopfiles(odeEquations,algebraicEquations,whenClauses,parameterEquations,simCode)
algloopfiles(allEquations,simCode)
// empty result of the top-level template .., only side effects
end translateModel;
template translateFunctions(FunctionCode functionCode)
"Generates C code and Makefile for compiling and calling Modelica and
MetaModelica functions."
::=
match functionCode
case FUNCTIONCODE(__) then
"" // Return empty result since result written to files directly
end translateFunctions;
template simulationHeaderFile(SimCode simCode)
"Generates code for header file for simulation target."
::=
match simCode
case SIMCODE(__) then
<<
<%generateHeaderInlcudeString(simCode)%>
<%generateClassDeclarationCode(simCode)%>
>>
end simulationHeaderFile;
template algloopHeaderFile(SimCode simCode,SimEqSystem eq)
"Generates code for header file for simulation target."
::=
match simCode
case SIMCODE(__) then
<<
<%generateAlgloopHeaderInlcudeString(simCode)%>
<%generateAlgloopClassDeclarationCode(simCode,eq)%>
>>
end algloopHeaderFile;
template simulationFunctionsFile(SimCode simCode, list<Function> functions, list<Exp> literals)
"Generates the content of the Cpp file for functions in the simulation case."
::=
match simCode
case SIMCODE(modelInfo=MODELINFO(__)) then
<<
#include "Modelica.h"
#include "Functions.h"
Functions::Functions()
{
<%literals |> literal hasindex i0 fromindex 0 => literalExpConstImpl(literal,i0) ; separator="\n";empty%>
}
Functions::~Functions()
{
}
void Functions::Assert(bool cond,string msg)
{
if(!cond)
throw std::runtime_error(msg);
}
<%functionBodies(functions,simCode)%>
>>
end simulationFunctionsFile;
template simulationFunctionsHeaderFile(SimCode simCode, list<Function> functions, list<Exp> literals)
::=
match simCode
case SIMCODE(modelInfo=MODELINFO(__)) then
<<
#pragma once
#include "Math/Implementation/ArrayOperations.h"
#include "Math/Implementation/Functions.h"
#include "Math/Implementation/Utility.h"
#include "LibrariesConfig.h"
/*****************************************************************************
*
* Simulation code for FunctionCall functions generated by the OpenModelica Compiler.
*
*****************************************************************************/
//external c functions
extern "C" {
<%externfunctionHeaderDefinition(functions)%>
}
<%functionHeaderBodies1(functions,simCode)%>
class Functions
{
public:
Functions();
~Functions();
//Modelica functions
<%functionHeaderBodies2(functions,simCode)%>
void Assert(bool cond,string msg);
//Literals
<%literals |> literal hasindex i0 fromindex 0 => literalExpConst(literal,i0) ; separator="\n";empty%>
private:
//Function return variables
<%functionHeaderBodies3(functions,simCode)%>
};
>>
end simulationFunctionsHeaderFile;
template simulationMakefile(String target,SimCode simCode)
"Generates the contents of the makefile for the simulation case."
::=
match target
case "msvc" then
match simCode
case SIMCODE(modelInfo=MODELINFO(__), makefileParams=MAKEFILE_PARAMS(__), simulationSettingsOpt = sopt) then
let dirExtra = if modelInfo.directory then '-L"<%modelInfo.directory%>"' //else ""
let libsStr = (makefileParams.libs |> lib => lib ;separator=" ")
let libsPos1 = if not dirExtra then libsStr //else ""
let libsPos2 = if dirExtra then libsStr // else ""
let ParModelicaLibs = if acceptParModelicaGrammar() then '-lOMOCLRuntime -lOpenCL' // else ""
let extraCflags = match sopt case SOME(s as SIMULATION_SETTINGS(__)) then
'<%if s.measureTime then "-D_OMC_MEASURE_TIME "%> <%match s.method
case "inline-euler" then "-D_OMC_INLINE_EULER "
case "inline-rungekutta" then "-D_OMC_INLINE_RK "
case "dassljac" then "-D_OMC_JACOBIAN "%>'
<<
# Makefile generated by OpenModelica
# Simulations use -O3 by default
SIM_OR_DYNLOAD_OPT_LEVEL=
MODELICAUSERCFLAGS=
CXX=cl
EXEEXT=.exe
DLLEXT=.dll
include <%makefileParams.omhome%>/include/omc/cpp/ModelicaConfic.inc
# /Od - Optimization disabled
# /EHa enable C++ EH (w/ SEH exceptions)
# /fp:except - consider floating-point exceptions when generating code
# /arch:SSE2 - enable use of instructions available with SSE2 enabled CPUs
# /I - Include Directories
# /DNOMINMAX - Define NOMINMAX (does what it says)
# /TP - Use C++ Compiler
CFLAGS=/Od /EHa /MP /fp:except /I"<%makefileParams.omhome%>/include/omc/cpp/" -I"$(BOOST_INCLUDE)" /I. /DNOMINMAX /TP /DNO_INTERACTIVE_DEPENDENCY
# /ZI enable Edit and Continue debug info
CDFLAGS = /ZI
# /MD - link with MSVCRT.LIB
# /link - [linker options and libraries]
# /LIBPATH: - Directories where libs can be found
LDFLAGS=/MD /link /DLL /NOENTRY /LIBPATH:"<%makefileParams.omhome%>/lib/omc/cpp/" /LIBPATH:"<%makefileParams.omhome%>/bin" OMCppSystem.lib OMCppMath.lib OMCppModelicaExternalC.lib
# /MDd link with MSVCRTD.LIB debug lib
# lib names should not be appended with a d just switch to lib/omc/cpp
FILEPREFIX=<%fileNamePrefix%>
FUNCTIONFILE=Functions.cpp
MAINFILE=<%lastIdentOfPath(modelInfo.name)%><% if acceptMetaModelicaGrammar() then ".conv"%>.cpp
MAINOBJ=$(MODELICA_SYSTEM_LIB)
GENERATEDFILES=$(MAINFILE) $(FUNCTIONFILE) <%algloopcppfilenames(allEquations,simCode)%>
$(MODELICA_SYSTEM_LIB)$(DLLEXT):
<%\t%>$(CXX) /Fe$(MODELICA_SYSTEM_LIB) $(MAINFILE) $(FUNCTIONFILE) <%algloopcppfilenames(allEquations,simCode)%> $(CFLAGS) $(LDFLAGS)
>>
end match
case "gcc" then
match simCode
case SIMCODE(modelInfo=MODELINFO(__), makefileParams=MAKEFILE_PARAMS(__), simulationSettingsOpt = sopt) then
let extraCflags = match sopt case SOME(s as SIMULATION_SETTINGS(__)) then
'<%if s.measureTime then "-D_OMC_MEASURE_TIME "%> <%match s.method
case "inline-euler" then "-D_OMC_INLINE_EULER"
case "inline-rungekutta" then "-D_OMC_INLINE_RK"%>'
<<
# Makefile generated by OpenModelica
include <%makefileParams.omhome%>/include/omc/cpp/ModelicaConfic.inc
# Simulations use -O0 by default
SIM_OR_DYNLOAD_OPT_LEVEL=-O0
CC=<%makefileParams.ccompiler%>
CXX=<%makefileParams.cxxcompiler%>
LINK=<%makefileParams.linker%>
EXEEXT=<%makefileParams.exeext%>
DLLEXT=<%makefileParams.dllext%>
CFLAGS_BASED_ON_INIT_FILE=<%extraCflags%>
CFLAGS=$(CFLAGS_BASED_ON_INIT_FILE) -I"<%makefileParams.omhome%>/include/omc/cpp" -I"$(BOOST_INCLUDE)" <%makefileParams.includes ; separator=" "%> <%makefileParams.cflags%> <%match sopt case SOME(s as SIMULATION_SETTINGS(__)) then s.cflags %>
LDFLAGS=-L"<%makefileParams.omhome%>/lib/omc/cpp"
MAINFILE=<%lastIdentOfPath(modelInfo.name)%><% if acceptMetaModelicaGrammar() then ".conv"%>.cpp
FUNCTIONFILE=Functions.cpp
.PHONY: <%lastIdentOfPath(modelInfo.name)%>
<%lastIdentOfPath(modelInfo.name)%>: $(MAINFILE)
<%\t%>$(CXX) -shared -I. -o $(MODELICA_SYSTEM_LIB) $(MAINFILE) $(FUNCTIONFILE) <%algloopcppfilenames(allEquations,simCode)%> $(CFLAGS) $(LDFLAGS) -lOMCppSystem -lOMCppMath -lOMCppModelicaExternalC -Wl,-Bstatic -Wl,-Bdynamic
>>
end simulationMakefile;
template simulationCppFile(SimCode simCode)
"Generates code for main cpp file for simulation target."
::=
match simCode
case SIMCODE(modelInfo = MODELINFO(__)) then
<<
#include "Modelica.h"
#include "<%lastIdentOfPath(modelInfo.name)%>.h"
using boost::extensions::factory;
BOOST_EXTENSION_TYPE_MAP_FUNCTION {
types.get<std::map<std::string, factory<IDAESystem,IGlobalSettings&> > >()
["ModelicaSystem"].set<<%lastIdentOfPath(modelInfo.name)%>>();
}
<%lastIdentOfPath(modelInfo.name)%>::<%lastIdentOfPath(modelInfo.name)%>(IGlobalSettings& globalSettings)
:SystemDefaultImplementation(globalSettings)
<%simulationInitFile(simCode)%>
{
//Number of equations
<%dimension1(simCode)%>
_dimZeroFunc= <%zerocrosslength(simCode)%>;
//Number of residues
<%if Flags.isSet(Flags.WRITE_TO_BUFFER) then
<<
_dimResidues=<%numResidues(allEquations)%>;
>>
else
<<
_dimResidues=0;
>>
%>
//DAE's are not supported yet, Index reduction is enabled
_dimAE = 0; // algebraic equations
//Initialize the state vector
SystemDefaultImplementation::init();
//Instantiate auxiliary object for event handling functionality
_event_handling.resetHelpVar = boost::bind(&<%lastIdentOfPath(modelInfo.name)%>::resetHelpVar, this, _1);
_historyImpl = new HistoryImplType(globalSettings);
<%arrayReindex(modelInfo)%>
//Initialize array elements
<%initializeArrayElements(simCode)%>
//Load Algloopsolver library
type_map types;
std::string algsolver_name(SYSTEM_LIB);
if(!load_single_library(types, algsolver_name))
throw std::invalid_argument("Algsolver library could not be loaded");
std::map<std::string, factory<IAlgLoopSolverFactory> >::iterator iter;
std::map<std::string, factory<IAlgLoopSolverFactory> >& factories(types.get());
iter = factories.find("AlgLoopSolverFactory");
if (iter ==factories.end())
{
throw std::invalid_argument("No AlgLoopSolverFactory found");
}
<%generateAlgloopsolvers(allEquations,simCode)%>
}
<%lastIdentOfPath(modelInfo.name)%>::~<%lastIdentOfPath(modelInfo.name)%>()
{
delete _historyImpl;
}
<%init(simCode)%>
void <%lastIdentOfPath(modelInfo.name)%>::resetTimeEvents()
{
<%resetTimeEvents(sampleConditions,whenClauses,simCode)%>
}
<%Update(simCode)%>
<%writeoutput(simCode)%>
<%DefaultImplementationCode(simCode)%>
<%checkForDiscreteEvents(discreteModelVars,simCode)%>
<%giveZeroFunc1(zeroCrossings,simCode)%>
<%giveConditions(simCode)%>
<%setConditions(simCode)%>
<%saveConditions(simCode)%>
<%isODE(simCode)%>
<%DimZeroFunc(simCode)%>
<%DimInitEquations(simCode)%>
<%DimUnfixedStates(simCode)%>
<%DimUnfixedParameters(simCode)%>
<%DimIntialResiduals(simCode)%>
<%GetIntialStatus(simCode)%>
<%SetIntialStatus(simCode)%>
<%checkConditions(zeroCrossings,whenClauses,simCode)%>
<%handleSystemEvents(zeroCrossings,whenClauses,simCode)%>
<%saveall(modelInfo,simCode)%>
<%savediscreteVars(modelInfo,simCode)%>
<%resethelpvar(whenClauses,simCode)%>
<%LabeledDAE(modelInfo.labels,simCode)%>
<%functionAnalyticJacobians(jacobianMatrixes,simCode)%>
>>
end simulationCppFile;
/*<%arrayInit(simCode)%>*/
/* */
/* <%modelname%>Algloop<%index%>::<%modelname%>Algloop<%index%>(<%constructorParams%> double* z,double* zDot,EventHandling& event_handling )
,<%iniAlgloopParamas%>*/
template algloopCppFile(SimCode simCode,SimEqSystem eq)
"Generates code for main cpp file for algloop system ."
::=
match simCode
case SIMCODE(modelInfo = MODELINFO(__)) then
let modelname = lastIdentOfPath(modelInfo.name)
let &varDecls = buffer ""
let &arrayInit = buffer ""
let constructorParams = ConstructorParamAlgloop(modelInfo)
let iniAlgloopParamas = InitAlgloopParams(modelInfo,arrayInit)
match eq
case SES_LINEAR(__)
case SES_NONLINEAR(__) then
<<
#include "Modelica.h"
#include "<%modelname%>Algloop<%index%>.h"
#include "<%lastIdentOfPath(modelInfo.name)%>.h"
<%if Flags.isSet(Flags.WRITE_TO_BUFFER) then '#include "Math/Implementation/ArrayOperations.h"'%>
<%modelname%>Algloop<%index%>::<%modelname%>Algloop<%index%>(<%modelname%>* system, double* z,double* zDot,bool* conditions1, EventHandling& event_handling )
:AlgLoopDefaultImplementation()
,_system(system)
,_residuals(NULL)
,__z(z)
,__zDot(zDot)
,_conditions1(conditions1)
,_event_handling(event_handling)
<%alocateLinearSystem(eq)%>
{
<%initAlgloopDimension(eq,varDecls)%>
}
<%modelname%>Algloop<%index%>::~<%modelname%>Algloop<%index%>()
{
if(_residuals) delete [] _residuals;
}
<%algloopRHSCode(simCode,eq)%>
<%if Flags.isSet(Flags.WRITE_TO_BUFFER) then algloopResiduals(simCode,eq)%>
<%initAlgloop(simCode,eq)%>
<%upateAlgloopNonLinear(simCode,eq)%>
<%upateAlgloopLinear(simCode,eq)%>
<%AlgloopDefaultImplementationCode(simCode,eq)%>
<%getAMatrixCode(simCode,eq)%>
<%isLinearCode(simCode,eq)%>
>>
end algloopCppFile;
template upateAlgloopNonLinear( SimCode simCode,SimEqSystem eqn)
"Generates functions in simulation file."
::=
match simCode
case SIMCODE(modelInfo = MODELINFO(__)) then
let () = System.tmpTickReset(0)
let modelname = lastIdentOfPath(modelInfo.name)
match eqn
//case eq as SES_MIXED(__) then functionExtraResiduals(fill(eq.cont,1),simCode)
case eq as SES_NONLINEAR(__) then
let &varDecls = buffer "" /*BUFD*/
let algs = (eq.eqs |> eq2 as SES_ALGORITHM(__) =>
equation_(eq2, contextAlgloop, &varDecls /*BUFD*/,simCode)
;separator="\n")
let prebody = (eq.eqs |> eq2 as SES_SIMPLE_ASSIGN(__) =>
equation_(eq2, contextAlgloop, &varDecls /*BUFD*/,simCode)
;separator="\n")
let body = (eq.eqs |> eq2 as SES_RESIDUAL(__) hasindex i0 =>
let &preExp = buffer "" /*BUFD*/
let expPart = daeExp(eq2.exp, contextAlgloop,
&preExp /*BUFC*/, &varDecls /*BUFD*/,simCode)
'<%preExp%>_residuals[<%i0%>] = <%expPart%>;'
;separator="\n")
<<
void <%modelname%>Algloop<%index%>::update(const IContinous::UPDATE command)
{
<%varDecls%>
if(command & IContinous::CONTINOUS)
{
<%algs%>
<%prebody%>
<%body%>
}
}
>>
end upateAlgloopNonLinear;
template upateAlgloopLinear( SimCode simCode,SimEqSystem eqn)
"Generates functions in simulation file."
::=
match simCode
case SIMCODE(modelInfo = MODELINFO(__)) then
let () = System.tmpTickReset(0)
let modelname = lastIdentOfPath(modelInfo.name)
match eqn
case SES_LINEAR(__) then
let uid = System.tmpTick()
let size = listLength(vars)
let aname = 'A<%uid%>'
let bname = 'b<%uid%>'
let &varDecls = buffer "" /*BUFD*/
let &preExp = buffer "" /*BUFD*/
let Amatrix=
(simJac |> (row, col, eq as SES_RESIDUAL(__)) =>
let expPart = daeExp(eq.exp, contextAlgloop, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode)
'<%preExp%>__A[<%row%>][<%col%>]=<%expPart%>;'
;separator="\n")
let bvector = (beqs |> exp hasindex i0 =>
let expPart = daeExp(exp, contextAlgloop, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode)
'<%preExp%>__b[<%i0%>]=<%expPart%>;'
;separator="\n")
<<
void <%modelname%>Algloop<%index%>::update(const IContinous::UPDATE command)
{
<%varDecls%>
<%Amatrix%>
<%bvector%>
}
>>
end upateAlgloopLinear;
template inlineVars(Context context, list<SimVar> simvars)
::= match context case INLINE_CONTEXT(__) then match simvars
case {} then ''
else <<
<%simvars |> var => match var case SIMVAR(name = cr as CREF_QUAL(ident = "$DER")) then 'inline_integrate(<%cref(cr)%>);' ;separator="\n"%>
>>
end inlineVars;
template functionBodies(list<Function> functions,SimCode simCode)
"Generates the body for a set of functions."
::=
(functions |> fn => functionBody(fn, false,simCode) ;separator="\n")
end functionBodies;
template functionBody(Function fn, Boolean inFunc,SimCode simCode)
"Generates the body for a function."
::=
match fn
case fn as FUNCTION(__) then functionBodyRegularFunction(fn, inFunc,simCode)
case fn as EXTERNAL_FUNCTION(__) then functionBodyExternalFunction(fn, inFunc,simCode)
case fn as RECORD_CONSTRUCTOR(__) then functionBodyRecordConstructor(fn)
end functionBody;
template externfunctionHeaderDefinition(list<Function> functions)
"Generates the body for a set of functions."
::=
(functions |> fn => extFunDef(fn) ;separator="\n")
end externfunctionHeaderDefinition;
template functionHeaderBodies1(list<Function> functions,SimCode simCode)
"Generates the body for a set of functions."
::=
match simCode
case SIMCODE(modelInfo=modelInfo as MODELINFO(__)) then
let recorddecls = (recordDecls |> rd => recordDeclarationHeader(rd,simCode) ;separator="\n")
let rettypedecls = (functions |> fn => functionHeaderBody1(fn,simCode) ;separator="\n")
<<
<%recorddecls%>
<%rettypedecls%>
>>
end functionHeaderBodies1;
template functionHeaderBody1(Function fn,SimCode simCode)
"Generates the body for a function."
::=
match fn
case fn as FUNCTION(__) then functionHeaderRegularFunction1(fn,simCode)
case fn as EXTERNAL_FUNCTION(__) then functionHeaderExternFunction(fn,simCode)
case fn as RECORD_CONSTRUCTOR(__) then functionHeaderRegularFunction1(fn,simCode)
end functionHeaderBody1;
template functionHeaderBodies2(list<Function> functions,SimCode simCode)
"Generates the body for a set of functions."
::=
(functions |> fn => functionHeaderBody2(fn,simCode) ;separator="\n")
end functionHeaderBodies2;
template functionHeaderBody2(Function fn,SimCode simCode)
"Generates the body for a function."
::=
match fn
case fn as FUNCTION(__) then functionHeaderRegularFunction2(fn,simCode)
case fn as EXTERNAL_FUNCTION(__) then functionHeaderRegularFunction2(fn,simCode)
case fn as RECORD_CONSTRUCTOR(__) then functionHeaderRecordConstruct(fn,simCode)
end functionHeaderBody2;
template functionHeaderBodies3(list<Function> functions,SimCode simCode)
"Generates the body for a set of functions."
::=
(functions |> fn => functionHeaderBody3(fn,simCode) ;separator="\n")
end functionHeaderBodies3;
template functionHeaderBody3(Function fn,SimCode simCode)
"Generates the body for a function."
::=
match fn
case fn as FUNCTION(__) then functionHeaderRegularFunction3(fn,simCode)
case fn as EXTERNAL_FUNCTION(__) then functionHeaderRegularFunction3(fn,simCode)
case fn as RECORD_CONSTRUCTOR(__) then ""
end functionHeaderBody3;
template extFunDef(Function fn)
"Generates function header for an external function."
::=
match fn
case func as EXTERNAL_FUNCTION(__) then
//let fn_name = extFunctionName(extName, language)
let fargsStr = extFunDefArgs(extArgs, language)
'extern <%extReturnType(extReturn)%> <%extName%>(<%fargsStr%>);'
end extFunDef;
template extFunctionName(String name, String language)
::=
match language
case "C" then '<%name%>'
else error(sourceInfo(), 'Unsupport external language: <%language%>')
end extFunctionName;
template extFunDefArgs(list<SimExtArg> args, String language)
::=
match language
case "C" then (args |> arg => extFunDefArg(arg) ;separator=", ")
else error(sourceInfo(), 'Unsupport external language: <%language%>')
end extFunDefArgs;
template extFunDefArg(SimExtArg extArg)
"Generates the definition of an external function argument.
Assume that language is C for now."
::=
match extArg
case SIMEXTARG(cref=c, isInput=ii, isArray=ia, type_=t) then
let name = contextCref2(c,contextFunction)
let typeStr = extType2(t,ii,ia)
<<
<%typeStr%> /*<%name%>*/
>>
case SIMEXTARGEXP(__) then
let typeStr = extType2(type_,true,false)
<<
<%typeStr%>
>>
case SIMEXTARGSIZE(cref=c) then
<<
size_t
>>
end extFunDefArg;
template extType2(Type type, Boolean isInput, Boolean isArray)
"Generates type for external function argument or return value."
::=
let s = match type
case T_INTEGER(__) then "int"
case T_REAL(__) then "double"
case T_STRING(__) then "const char*"
case T_BOOL(__) then "int"
case T_ENUMERATION(__) then "int"
case T_ARRAY(__) then extType2(ty,isInput,true)
case T_COMPLEX(complexClassType=EXTERNAL_OBJ(__))
then "void *"
case T_COMPLEX(complexClassType=RECORD(path=rname))
then 'Test struct <%underscorePath(rname)%>'
case T_METATYPE(__) case T_METABOXED(__) then "modelica_metatype"
else error(sourceInfo(), 'Unknown external C type <%unparseType(type)%>')
match type case T_ARRAY(__) then s else if isInput then (if isArray then '<%match s case "const char*" then "" else "const "%><%s%>*' else s) else '<%s%>*'
end extType2;
template extReturnType(SimExtArg extArg)
"Generates return type for external function."
::=
match extArg
case ex as SIMEXTARG(__) then extType2(type_,true /*Treat this as an input (pass by value)*/,false)
case SIMNOEXTARG(__) then "void"
case SIMEXTARGEXP(__) then error(sourceInfo(), 'Expression types are unsupported as return arguments <%printExpStr(exp)%>')
else error(sourceInfo(), "Unsupported return argument")
end extReturnType;
template functionHeaderRegularFunction1(Function fn,SimCode simCode)
::=
match fn
case FUNCTION(outVars={var}) then
let fname = underscorePath(name)
<< /*default return type*/
typedef <%funReturnDefinition1(var,simCode)%> <%fname%>RetType;
typedef <%funReturnDefinition2(var,simCode)%> <%fname%>RefRetType;
>>
case FUNCTION(outVars=_::_) then
let fname = underscorePath(name)
<< /*tuple return type*/
typedef boost::tuple< <%outVars |> var => funReturnDefinition1(var,simCode) ;separator=", "%> > <%fname%>RetType;
typedef boost::tuple< <%outVars |> var => funReturnDefinition2(var,simCode) ;separator=", "%> > <%fname%>RefRetType;
>>
case RECORD_CONSTRUCTOR(__) then
let fname = underscorePath(name)
<<
typedef <%fname%>Type <%fname%>RetType;
>>
end functionHeaderRegularFunction1;
template functionHeaderRecordConstruct(Function fn,SimCode simCode)
::=
match fn
case RECORD_CONSTRUCTOR(__) then
let fname = underscorePath(name)
let funArgsStr = (funArgs |> var as VARIABLE(__) =>
'<%varType2(var)%> <%crefStr(name)%>'
;separator=", ")
<<
<%fname%>Type <%fname%>(<%funArgsStr%>);
>>
end functionHeaderRecordConstruct;
template functionHeaderExternFunction(Function fn,SimCode simCode)
::=
match fn
case EXTERNAL_FUNCTION(outVars={var}) then
let fname = underscorePath(name)
<<
typedef <%funReturnDefinition1(var,simCode)%> <%fname%>RetType;
>>
case EXTERNAL_FUNCTION(outVars=_::_) then
let fname = underscorePath(name)
<<
typedef boost::tuple< <%outVars |> var => funReturnDefinition1(var,simCode) ;separator=", "%> > <%fname%>RetType;
>>
end functionHeaderExternFunction;
template recordDeclarationHeader(RecordDeclaration recDecl,SimCode simCode)
"Generates structs for a record declaration."
::=
match recDecl
case RECORD_DECL_FULL(__) then
<<
struct <%name%>Type
{
//Constructor allocates arrays
<%name%>Type()
{
<%variables |> var as VARIABLE(__) => '<%recordDeclarationHeaderArrayAllocate(var,simCode)%>' ;separator="\n"%>
}
//Public Members
<%variables |> var as VARIABLE(__) => '<%varType1(var)%> <%crefStr(var.name)%>;' ;separator="\n"%>
};
>>
case RECORD_DECL_DEF(__) then
<<
RECORD DECL DEF
>>
end recordDeclarationHeader;
template recordDeclarationHeaderArrayAllocate(Variable v,SimCode simCode)
"Generates structs for a record declaration."
::=
match v
case var as VARIABLE(ty=ty as T_ARRAY(__)) then
let instDimsInit = (ty.dims |> exp =>
dimension(exp);separator="][")
let arrayname = crefStr(name)
<<
<%arrayname%>.resize((boost::extents[<%instDimsInit%>]));
<%arrayname%>.reindex(1);
>>
end recordDeclarationHeaderArrayAllocate;
template functionBodyRecordConstructor(Function fn)
"Generates the body for a record constructor."
::=
match fn
case RECORD_CONSTRUCTOR(__) then
let()= System.tmpTickReset(1)
let &varDecls = buffer "" /*BUFD*/
let fname = underscorePath(name)
let retType = '<%fname%>Type'
let retVar = tempDecl(retType, &varDecls /*BUFD*/)
let structType = '<%fname%>Type'
let structVar = tempDecl(structType, &varDecls /*BUFD*/)
<<
<%retType%> Functions::<%fname%>(<%funArgs |> var as VARIABLE(__) => '<%varType2(var)%> <%crefStr(name)%>' ;separator=", "%>)
{
<%varDecls%>
<%funArgs |> VARIABLE(__) => '<%structVar%>.<%crefStr(name)%> = <%crefStr(name)%>;' ;separator="\n"%>
return <%structVar%>;
}
>>
end functionBodyRecordConstructor;
template daeExpSharedLiteral(Exp exp, Context context, Text &preExp /*BUFP*/, Text &varDecls /*BUFP*/)
"Generates code for a match expression."
::=
match exp case exp as SHARED_LITERAL(__) then
match context case FUNCTION_CONTEXT(__) then
' _OMC_LIT<%exp.index%>'
else
'_functions._OMC_LIT<%exp.index%>'
end daeExpSharedLiteral;
template functionHeaderRegularFunction2(Function fn,SimCode simCode)
::=
match fn
case FUNCTION(__) then
let fname = underscorePath(name)
<<
<%fname%>RetType <%fname%>(<%functionArguments |> var => funArgDefinition(var,simCode) ;separator=", "%>);
>>
case EXTERNAL_FUNCTION(__) then
let fname = underscorePath(name)
<<
<%fname%>RetType <%fname%>(<%funArgs |> var => funArgDefinition(var,simCode) ;separator=", "%>);
>>
end functionHeaderRegularFunction2;
template functionHeaderRegularFunction3(Function fn,SimCode simCode)
::=
match fn
case FUNCTION(__) then
let fname = underscorePath(name)
<<
<%fname%>RetType _<%fname%>;
>>
case EXTERNAL_FUNCTION(__) then
let fname = underscorePath(name)
<<
<%fname%>RetType _<%fname%>;
>>
end functionHeaderRegularFunction3;
template functionBodyRegularFunction(Function fn, Boolean inFunc,SimCode simCode)
"Generates the body for a Modelica/MetaModelica function."
::=
match fn
case FUNCTION(__) then
let()= System.tmpTickReset(1)
let fname = underscorePath(name)
let retType = if outVars then '<%fname%>RetType' else "void"
let &varDecls = buffer "" /*BUFD*/
let &varInits = buffer "" /*BUFD*/
//let retVar = if outVars then tempDecl(retType, &varDecls /*BUFD*/)
//let stateVar = if not acceptMetaModelicaGrammar() then tempDecl("state", &varDecls /*BUFD*/)
let _ = (variableDeclarations |> var hasindex i1 fromindex 1 =>
varInit(var, "", i1, &varDecls /*BUFD*/, &varInits /*BUFC*/,simCode) ; empty /* increase the counter! */
)
//let addRootsInputs = (functionArguments |> var => addRoots(var) ;separator="\n")
//let addRootsOutputs = (outVars |> var => addRoots(var) ;separator="\n")
//let funArgs = (functionArguments |> var => functionArg(var, &varInits) ;separator="\n")
let bodyPart = (body |> stmt => funStatement(stmt, &varDecls /*BUFD*/,simCode) ;separator="\n")
let &outVarInits = buffer ""
let &outVarCopy = buffer ""
let &outVarAssign = buffer ""
let _ = match outVars case {var} then (outVars |> var hasindex i1 fromindex 0 =>
varOutput(fn, var,i1, &varDecls, &outVarInits, &outVarCopy, &outVarAssign, simCode)
;separator="\n"; empty /* increase the counter! */
)
else
(outVars |> var hasindex i1 fromindex 0 =>
varOutputTuple(fn, var,i1, &varDecls, &outVarInits, &outVarCopy, &outVarAssign, simCode)
;separator="\n"; empty /* increase the counter! */
)
//let boxedFn = if acceptMetaModelicaGrammar() then functionBodyBoxed(fn)
<<
<%retType%> Functions::<%fname%>(<%functionArguments |> var => funArgDefinition(var,simCode) ;separator=", "%>)
{
<%varDecls%>
<%outVarInits%>
<%varInits%>
<%bodyPart%>
<%outVarAssign%>
return <%if outVars then '_<%fname%>' %>;
}
<% if inFunc then
<<
int in_<%fname%>(type_description * inArgs, type_description * outVar)
{
<%functionArguments |> var => '<%funArgDefinition(var,simCode)%>;' ;separator="\n"%>
<%if outVars then '<%retType%> out;'%>
//MMC_TRY_TOP()
return 0;
}
>>
%>
>>
end functionBodyRegularFunction;
template functionBodyExternalFunction(Function fn, Boolean inFunc,SimCode simCode)
"Generates the body for an external function (just a wrapper)."
::=
match fn
case efn as EXTERNAL_FUNCTION(__) then
let()= System.tmpTickReset(1)
let fname = underscorePath(name)
let retType = if outVars then '<%fname%>RetType' else "void"
let &preExp = buffer "" /*BUFD*/
let &varDecls = buffer "" /*BUFD*/
// make sure the variable is named "out", doh!
let retVar = if outVars then '_<%fname%>'
let &outVarInits = buffer ""
let callPart = extFunCall(fn, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode)
let _ = ( outVars |> var hasindex i1 fromindex 1 =>
varInit(var, retVar, i1, &varDecls /*BUFD*/, &outVarInits /*BUFC*/,simCode)
; empty /* increase the counter! */
)
let fnBody = <<
<%retType%> Functions::<%fname%>(<%funArgs |> var => funArgDefinition(var,simCode) ;separator=", "%>)
{
/* functionBodyExternalFunction: varDecls */
<%varDecls%>
/* functionBodyExternalFunction: preExp */
<%preExp%>
/* functionBodyExternalFunction: outputAlloc */
<%outVarInits%>
/* functionBodyExternalFunction: callPart */
<%callPart%>
/* functionBodyExternalFunction: return */
return <%retVar%>;
}
>>
<<
<% if dynamicLoad then
<<
ptrT_<%extFunctionName(extName, language)%> ptr_<%extFunctionName(extName, language)%>=NULL;
>> %>
<%fnBody%>
<% if inFunc then
<<
int in_<%fname%>(type_description * inArgs, type_description * outVar)
{
<%funArgs |> VARIABLE(__) => '<%expTypeArrayIf(ty)%> <%contextCref(name,contextFunction,simCode)%>;' ;separator="\n"%>
<%retType%> out;
<%funArgs |> arg as VARIABLE(__) => readInVar(arg,simCode) ;separator="\n"%>
MMC_TRY_TOP()
out = _<%fname%>(<%funArgs |> VARIABLE(__) => contextCref(name,contextFunction,simCode) ;separator=", "%>);
MMC_CATCH_TOP(return 1)
<%outVars |> var as VARIABLE(__) hasindex i1 fromindex 1 => writeOutVar(var, i1) ;separator="\n";empty%>
return 0;
}
>> %>
>>
end functionBodyExternalFunction;
template writeOutVar(Variable var, Integer index)
"Generates code for writing a variable to outVar."
::=
match var
case VARIABLE(ty=T_COMPLEX(complexClassType=RECORD(__))) then
<<
write_modelica_record(outVar, <%writeOutVarRecordMembers(ty, index, "")%>);
>>
case VARIABLE(__) then
<<
write_<%varType(var)%>(outVar, &out.targTest8<%index%>);
>>
end writeOutVar;
template writeOutVarRecordMembers(Type type, Integer index, String prefix)
"Helper to writeOutVar."
::=
match type
case T_COMPLEX(varLst=vl, complexClassType = n) then
let basename = underscorePath(ClassInf.getStateName(n))
let args = (vl |> subvar as TYPES_VAR(__) =>
match ty case T_COMPLEX(__) then
let newPrefix = '<%prefix%>.<%subvar.name%>'
'<%expTypeRW(ty)%>, <%writeOutVarRecordMembers(ty, index, newPrefix)%>'
else
'<%expTypeRW(ty)%>, &(out.targTest7<%index%><%prefix%>.<%subvar.name%>)'
;separator=", ")
<<
&<%basename%>__desc<%if args then ', <%args%>'%>, TYPE_DESC_NONE
>>
end writeOutVarRecordMembers;
template expTypeRW(DAE.Type type)
"Helper to writeOutVarRecordMembers."
::=
match type
case T_INTEGER(__) then "TYPE_DESC_INT"
case T_REAL(__) then "TYPE_DESC_REAL"
case T_STRING(__) then "TYPE_DESC_STRING"
case T_BOOL(__) then "TYPE_DESC_BOOL"
case T_ENUMERATION(__) then "TYPE_DESC_INT"
case T_ARRAY(__) then '<%expTypeRW(ty)%>_ARRAY'
case T_COMPLEX(complexClassType=RECORD(__))
then "TYPE_DESC_RECORD"
case T_METATYPE(__) case T_METABOXED(__) then "TYPE_DESC_MMC"
end expTypeRW;
template readInVar(Variable var,SimCode simCode)
"Generates code for reading a variable from inArgs."
::=
match var
case VARIABLE(name=cr, ty=T_COMPLEX(complexClassType=RECORD(__))) then
<<
if (read_modelica_record(&inArgs, <%readInVarRecordMembers(ty, contextCref(cr,contextFunction,simCode))%>)) return 1;
>>
case VARIABLE(name=cr, ty=T_STRING(__)) then
<<
if (read_<%expTypeArrayIf(ty)%>(&inArgs, <%if not acceptMetaModelicaGrammar() then "(char**)"%> &<%contextCref(name,contextFunction,simCode)%>)) return 1;
>>
case VARIABLE(__) then
<<
if (read_<%expTypeArrayIf(ty)%>(&inArgs, &<%contextCref(name,contextFunction,simCode)%>)) return 1;
>>
end readInVar;
template readInVarRecordMembers(Type type, String prefix)
"Helper to readInVar."
::=
match type
case T_COMPLEX(varLst=vl) then
(vl |> subvar as TYPES_VAR(__) =>
match ty case T_COMPLEX(__) then
let newPrefix = '<%prefix%>.<%subvar.name%>'
readInVarRecordMembers(ty, newPrefix)
else
'&(<%prefix%>.<%subvar.name%>)'
;separator=", ")
end readInVarRecordMembers;
template outDecl(String ty, Text &varDecls /*BUFP*/)
"Declares a temporary variable in varDecls and returns the name."
::=
let newVar = 'out'
let &varDecls += '<%ty%> <%newVar%>;<%\n%>'