/
SimCode.mo
7702 lines (7315 loc) · 272 KB
/
SimCode.mo
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
/*
* This file is part of OpenModelica.
*
* Copyright (c) 1998-CurrentYear, Linköping University,
* Department of Computer and Information Science,
* SE-58183 Linköping, Sweden.
*
* All rights reserved.
*
* THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3
* AND THIS OSMC PUBLIC LICENSE (OSMC-PL).
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S
* ACCEPTANCE OF THE OSMC PUBLIC LICENSE.
*
* The OpenModelica software and the Open Source Modelica
* Consortium (OSMC) Public License (OSMC-PL) are obtained
* from Linköping University, either from the above address,
* from the URLs: http://www.ida.liu.se/projects/OpenModelica or
* http://www.openmodelica.org, and in the OpenModelica distribution.
* GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html.
*
* This program is distributed WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH
* IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS
* OF OSMC-PL.
*
* See the full OSMC Public License conditions for more details.
*
*/
package SimCode
" file: SimCode.mo
package: SimCode
description: Code generation using Susan templates
RCS: $Id: SimCode.mo 3689 2009-02-26 07:38:30Z adrpo $
The entry points to this module are the translateModel function and the
translateFunctions fuction.
Except for the entry points, the only other public functions are those that
can be imported and called from templates.
The number of imported functions should be kept as low as possible. Today
some of them are needed to generate target code from templates. More careful
design of data structures passed to templates should reduce the number of
imported functions needed.
Many of the functions in this module were originally copied from the Codegen
and SimCodegen modules.
"
public import Exp;
public import Algorithm;
public import Values;
public import Types;
public import DAELow;
public import Env;
public import Dependency;
public import Interactive;
public import Absyn;
public import Ceval;
public import Tpl;
public import SCode;
public import DAE;
public import Inline;
protected import DAEUtil;
protected import SCodeUtil;
protected import ClassInf;
protected import SimCodeC;
protected import SimCodeCSharp;
protected import Util;
protected import Debug;
protected import Error;
protected import Inst;
protected import InnerOuter;
protected import Settings;
protected import RTOpts;
protected import System;
protected import VarTransform;
protected import CevalScript;
protected import ModUtil;
protected import DAEDump;
protected import PartFn;
protected import ValuesUtil;
public
type ExtConstructor = tuple<DAE.ComponentRef, String, list<DAE.Exp>>;
type ExtDestructor = tuple<String, DAE.ComponentRef>;
type ExtAlias = tuple<DAE.ComponentRef, DAE.ComponentRef>;
type HelpVarInfo = tuple<Integer, Exp.Exp, Integer>; // helpvarindex, expression, whenclause index
// Root data structure containing information required for templates to
// generate simulation code for a Modelica model.
uniontype SimCode
record SIMCODE
ModelInfo modelInfo;
list<Function> functions;
list<SimEqSystem> allEquations;
list<SimEqSystem> allEquationsPlusWhen;
list<SimEqSystem> stateContEquations;
list<SimEqSystem> nonStateContEquations;
list<SimEqSystem> nonStateDiscEquations;
list<SimEqSystem> residualEquations;
list<SimEqSystem> initialEquations;
list<SimEqSystem> parameterEquations;
list<SimEqSystem> removedEquations;
list<DAE.Statement> algorithmAndEquationAsserts;
list<DAELow.ZeroCrossing> zeroCrossings;
list<list<SimVar>> zeroCrossingsNeedSave;
list<HelpVarInfo> helpVarInfo;
list<SimWhenClause> whenClauses;
list<DAE.ComponentRef> discreteModelVars;
ExtObjInfo extObjInfo;
MakefileParams makefileParams;
DelayedExpression delayedExps;
end SIMCODE;
end SimCode;
// Delayed expressions type
uniontype DelayedExpression
record DELAYED_EXPRESSIONS
list<tuple<Integer, DAE.Exp>> delayedExps;
Integer maxDelayedIndex;
end DELAYED_EXPRESSIONS;
end DelayedExpression;
// Root data structure containing information required for templates to
// generate C functions for Modelica/MetaModelica functions.
uniontype FunctionCode
record FUNCTIONCODE
String name;
list<Function> functions;
MakefileParams makefileParams;
list<RecordDeclaration> extraRecordDecls;
end FUNCTIONCODE;
end FunctionCode;
// Container for metadata about a Modelica model.
uniontype ModelInfo
record MODELINFO
String name;
String directory;
VarInfo varInfo;
SimVars vars;
end MODELINFO;
end ModelInfo;
// Number of variables of various types in a Modelica model.
uniontype VarInfo
record VARINFO
Integer numHelpVars;
Integer numZeroCrossings;
Integer numTimeEvents;
Integer numStateVars;
Integer numAlgVars;
Integer numParams;
Integer numOutVars;
Integer numInVars;
Integer numResiduals;
Integer numExternalObjects;
Integer numStringAlgVars;
Integer numStringParamVars;
end VARINFO;
end VarInfo;
// Container for metadata about variables in a Modelica model.
uniontype SimVars
record SIMVARS
list<SimVar> stateVars;
list<SimVar> derivativeVars;
list<SimVar> algVars;
list<SimVar> inputVars;
list<SimVar> outputVars;
list<SimVar> paramVars;
list<SimVar> stringAlgVars;
list<SimVar> stringParamVars;
list<SimVar> extObjVars;
end SIMVARS;
end SimVars;
// Information about a variable in a Modelica model.
uniontype SimVar
record SIMVAR
DAE.ComponentRef name;
DAELow.VarKind varKind;
String comment;
Integer index;
Boolean isFixed;
Exp.Type type_;
Boolean isDiscrete;
// arrayCref is the name of the array if this variable is the first in that
// array
Option<DAE.ComponentRef> arrayCref;
end SIMVAR;
end SimVar;
// Represents a Modelica or MetaModelica function.
// TODO: I believe some of these fields can be removed. Check to see what is
// used in templates.
uniontype Function
record FUNCTION
Absyn.Path name;
list<Variable> inVars;
list<Variable> outVars;
list<RecordDeclaration> recordDecls;
list<Variable> functionArguments;
list<Variable> variableDeclarations;
list<Statement> body;
end FUNCTION;
record EXTERNAL_FUNCTION
Absyn.Path name;
String extName;
list<Variable> funArgs;
list<SimExtArg> extArgs;
SimExtArg extReturn;
list<Variable> inVars;
list<Variable> outVars;
list<Variable> biVars;
list<String> includes;
list<String> libs;
String language "C or Fortran";
list<RecordDeclaration> recordDecls;
end EXTERNAL_FUNCTION;
record RECORD_CONSTRUCTOR
Absyn.Path name;
list<Variable> funArgs;
list<RecordDeclaration> recordDecls;
end RECORD_CONSTRUCTOR;
end Function;
uniontype RecordDeclaration
record RECORD_DECL_FULL
String name; // struct (record) name ? encoded
Absyn.Path defPath; //definition path
list<Variable> variables; //only name and type
end RECORD_DECL_FULL;
record RECORD_DECL_DEF
Absyn.Path path; //definition path .. encoded ?
list<String> fieldNames;
end RECORD_DECL_DEF;
end RecordDeclaration;
// Information about an argument to an external function.
uniontype SimExtArg
record SIMEXTARG
DAE.ComponentRef cref;
Boolean isInput;
Integer outputIndex; // > 0 if output
Boolean isArray;
DAE.ExpType type_;
end SIMEXTARG;
record SIMEXTARGEXP
DAE.Exp exp;
DAE.ExpType type_;
end SIMEXTARGEXP;
record SIMEXTARGSIZE
DAE.ComponentRef cref;
Boolean isInput;
Integer outputIndex; // > 0 if output
DAE.ExpType type_;
DAE.Exp exp;
end SIMEXTARGSIZE;
record SIMNOEXTARG end SIMNOEXTARG;
end SimExtArg;
/* a variable represents a name, a type and a possible default value */
uniontype Variable
record VARIABLE
DAE.ComponentRef name;
Exp.Type ty;
Option<Exp.Exp> value; // Default value
list<DAE.Exp> instDims;
end VARIABLE;
record FUNCTION_PTR
String name;
Exp.Type ty;
list<Variable> args;
end FUNCTION_PTR;
end Variable;
// TODO: Replace Statement with just list<Algorithm.Statement>?
uniontype Statement
record ALGORITHM
list<Algorithm.Statement> statementLst; // in functions
end ALGORITHM;
end Statement;
// Represents a single equation or a system of equations that must be solved
// together.
uniontype SimEqSystem
record SES_RESIDUAL
DAE.Exp exp;
end SES_RESIDUAL;
record SES_SIMPLE_ASSIGN
DAE.Exp cref;
DAE.Exp exp;
end SES_SIMPLE_ASSIGN;
record SES_ARRAY_CALL_ASSIGN
DAE.ComponentRef componentRef;
DAE.Exp exp;
end SES_ARRAY_CALL_ASSIGN;
record SES_ALGORITHM
list<DAE.Statement> statements;
end SES_ALGORITHM;
record SES_LINEAR
Boolean partOfMixed;
list<SimVar> vars;
list<DAE.Exp> beqs;
list<tuple<Integer, Integer, SimEqSystem>> simJac;
end SES_LINEAR;
record SES_NONLINEAR
Integer index;
list<SimEqSystem> eqs;
list<DAE.ComponentRef> crefs;
end SES_NONLINEAR;
record SES_MIXED
SimEqSystem cont;
list<SimVar> discVars;
list<SimEqSystem> discEqs;
list<String> values;
list<Integer> value_dims;
end SES_MIXED;
record SES_WHEN
DAE.ComponentRef left;
DAE.Exp right;
list<tuple<DAE.Exp, Integer>> conditions; // condition, help var index
end SES_WHEN;
end SimEqSystem;
uniontype SimWhenClause
record SIM_WHEN_CLAUSE
list<DAE.ComponentRef> conditionVars;
list<DAELow.ReinitStatement> reinits;
Option<DAELow.WhenEquation> whenEq;
end SIM_WHEN_CLAUSE;
end SimWhenClause;
uniontype ExtObjInfo
record EXTOBJINFO
list<String> includes;
list<ExtConstructor> constructors;
list<ExtDestructor> destructors;
list<ExtAlias> aliases;
end EXTOBJINFO;
end ExtObjInfo;
// Platform specific parameters used when generating makefiles.
uniontype MakefileParams
record MAKEFILE_PARAMS
String ccompiler;
String cxxcompiler;
String linker;
String exeext;
String dllext;
String omhome;
String cflags;
String ldflags;
String senddatalibs;
list<String> libs;
end MAKEFILE_PARAMS;
end MakefileParams;
// Constants of this type defined below are used by templates to be able to
// generate different code depending on the context it is generated in.
uniontype Context
record SIMULATION
Boolean genDiscrete;
end SIMULATION;
record FUNCTION_CONTEXT
end FUNCTION_CONTEXT;
record OTHER
end OTHER;
end Context;
public constant Context contextSimulationNonDiscrete = SIMULATION(false);
public constant Context contextSimulationDiscrete = SIMULATION(true);
public constant Context contextFunction = FUNCTION_CONTEXT();
public constant Context contextOther = OTHER();
public function valueblockVars
"Used by templates to get a list of variables from a valueblock."
input DAE.Exp valueblock;
output list<Variable> vars;
algorithm
vars :=
matchcontinue (valueblock)
local
list<DAE.Element> ld;
case (DAE.VALUEBLOCK(localDecls=ld))
equation
ld = Util.listFilter(ld, isVarQ);
vars = Util.listMap(ld, daeInOutSimVar);
then vars;
end matchcontinue;
end valueblockVars;
public function crefSubIsScalar
"Used by templates to determine if a component reference's subscripts are
scalar."
input DAE.ComponentRef cref;
output Boolean isScalar;
list<DAE.Subscript> subs;
algorithm
subs := crefSubs(cref);
isScalar := subsToScalar(subs);
end crefSubIsScalar;
public function crefNoSub
"Used by templates to determine if a component reference has no subscripts."
input DAE.ComponentRef cref;
output Boolean noSub;
list<DAE.Subscript> subs;
Integer len;
algorithm
subs := crefSubs(cref);
noSub := Util.isListEmpty(subs);
end crefNoSub;
public function crefIsScalar
"Whether a component reference is a scalar depends on what context we are in.
If we are generating code for a function, then only crefs without subscripts
are scalar. If we are generating code for simulation though, then crefs with
only constant subscripts are also scalars, since a variable is generated for
each element of an array in the model."
input DAE.ComponentRef cref;
input Context context;
output Boolean isScalar;
algorithm
isScalar := matchcontinue(cref, context)
local
Boolean res;
case (_, FUNCTION_CONTEXT)
equation
res = crefNoSub(cref);
then
res;
case (_, _)
equation
res = Exp.crefHasScalarSubscripts(cref);
then
res;
end matchcontinue;
end crefIsScalar;
function crefSubs
"Used by templates to get the subscript list from a component reference."
input DAE.ComponentRef cref;
output list<DAE.Subscript> subs;
algorithm
subs :=
matchcontinue (cref)
local
list<DAE.Subscript> subs1;
list<DAE.Subscript> subs2;
DAE.ComponentRef cref1;
case (DAE.CREF_IDENT(subscriptLst=subs1))
then subs1;
case (DAE.CREF_QUAL(subscriptLst=subs1, componentRef=cref1))
equation
subs2 = crefSubs(cref1);
subs = Util.listFlatten({subs1, subs2});
then subs;
end matchcontinue;
end crefSubs;
public function buildCrefExpFromAsub
"Used by templates to convert an ASUB expression to a component reference
with subscripts."
input DAE.Exp cref;
input list<DAE.Exp> subs;
output DAE.Exp cRefOut;
algorithm
cRefOut := matchcontinue(cref, subs)
local
DAE.Exp sub;
DAE.ExpType ty;
list<DAE.Exp> rest;
DAE.ComponentRef crNew;
list<DAE.Subscript> indexes;
case (cref, {}) then cref;
case (DAE.CREF(componentRef=crNew, ty=ty), subs)
equation
indexes = Util.listMap(subs, Exp.makeIndexSubscript);
crNew = Exp.subscriptCref(crNew, indexes);
then
DAE.CREF(crNew, ty);
end matchcontinue;
end buildCrefExpFromAsub;
public function incrementInt
"Used by templates to create new integers that are increments of another."
input Integer inInt;
input Integer increment;
output Integer outInt;
algorithm
outInt := inInt + increment;
end incrementInt;
public function generateModelCode
"Generates code for a model by creating a SimCode structure and calling the
template-based code generator on it."
input SCode.Program program;
input DAE.DAElist dae;
input DAELow.DAELow indexedDAELow;
input Absyn.Path className;
input String filenamePrefix;
input String fileDir;
input Integer[:] equationIndices;
input Integer[:] variableIndices;
input DAELow.IncidenceMatrix incidenceMatrix;
input DAELow.IncidenceMatrix incidenceMatrixT;
input list<list<Integer>> strongComponents;
output DAELow.DAELow outIndexedDAELow;
output list<String> libs;
list<Function> functions;
DAE.DAElist dae2;
String filename, funcfilename;
SimCode simCode;
algorithm
(libs, functions, outIndexedDAELow, dae2) :=
createFunctions(program, dae, indexedDAELow, className, filenamePrefix);
simCode := createSimCode(dae2, outIndexedDAELow, equationIndices,
variableIndices, incidenceMatrix, incidenceMatrixT, strongComponents,
className, fileDir, functions, libs);
callTargetTemplates(simCode);
end generateModelCode;
public function translateModel
"Entry point to translate a Modelica model for simulation.
Called from other places in the compiler."
input Env.Cache inCache;
input Env.Env inEnv;
input Absyn.Path className "path for the model";
input Interactive.InteractiveSymbolTable inInteractiveSymbolTable;
input Ceval.Msg inMsg;
input Exp.Exp inExp;
input Boolean addDummy "if true, add a dummy state";
output Env.Cache outCache;
output Values.Value outValue;
output Interactive.InteractiveSymbolTable outInteractiveSymbolTable;
output DAELow.DAELow outDAELow;
output list<String> outStringLst;
output String outString;
algorithm
(outCache,outValue,outInteractiveSymbolTable,outDAELow,outStringLst,outString):=
matchcontinue (inCache,inEnv,className,inInteractiveSymbolTable,inMsg,inExp,addDummy)
local
String filenameprefix,file_dir;
list<SCode.Class> p_1;
DAE.DAElist dae;
list<Env.Frame> env;
DAELow.DAELow dlow,dlow_1,indexed_dlow,indexed_dlow_1;
list<Integer>[:] m,mT;
Integer[:] ass1,ass2;
list<list<Integer>> comps;
Absyn.ComponentRef a_cref;
list<String> libs;
Interactive.InteractiveSymbolTable st;
Absyn.Program p,ptot;
Ceval.Msg msg;
Exp.Exp fileprefix;
Env.Cache cache;
DAE.FunctionTree funcs;
case (cache,env,className,(st as Interactive.SYMBOLTABLE(ast = p)),msg,fileprefix,addDummy)
equation
/* calculate stuff that we need to create SimCode data structure */
(cache,Values.STRING(filenameprefix),SOME(_)) = Ceval.ceval(cache,env, fileprefix, true, SOME(st), NONE, msg);
ptot = Dependency.getTotalProgram(className,p);
p_1 = SCodeUtil.translateAbsyn2SCode(ptot);
(cache,env,_,dae) = Inst.instantiateClass(cache,InnerOuter.emptyInstHierarchy,p_1,className);
dae = DAEUtil.transformIfEqToExpr(dae,false);
dlow = DAELow.lower(dae, addDummy, true);
Debug.fprint("bltdump", "Lowered DAE:\n");
Debug.fcall("bltdump", DAELow.dump, dlow);
m = DAELow.incidenceMatrix(dlow);
mT = DAELow.transposeMatrix(m);
funcs = DAEUtil.daeFunctionTree(dae);
(ass1,ass2,dlow_1,m,mT) = DAELow.matchingAlgorithm(dlow, m, mT, (DAELow.INDEX_REDUCTION(),DAELow.EXACT(),DAELow.REMOVE_SIMPLE_EQN()),funcs);
// late Inline
dlow_1 = Inline.inlineCalls(NONE(),SOME(funcs),{DAE.NORM_INLINE(),DAE.AFTER_INDEX_RED_INLINE()},dlow_1);
(comps) = DAELow.strongComponents(m, mT, ass1, ass2);
indexed_dlow = DAELow.translateDae(dlow_1,NONE);
indexed_dlow_1 = DAELow.calculateValues(indexed_dlow);
Debug.fprint("bltdump", "indexed DAE:\n");
Debug.fcall("bltdump", DAELow.dumpIncidenceMatrix, m);
Debug.fcall("bltdump", DAELow.dumpIncidenceMatrixT, mT);
Debug.fcall("bltdump", DAELow.dump, indexed_dlow_1);
Debug.fcall("bltdump", DAELow.dumpMatching, ass1);
Debug.fprintln("dynload", "translateModel: Generating simulation code and functions.");
a_cref = Absyn.pathToCref(className);
file_dir = CevalScript.getFileDir(a_cref, p);
(indexed_dlow_1, libs) = generateModelCode(p_1, dae, indexed_dlow_1, className, filenameprefix,
file_dir, ass1, ass2, m, mT, comps);
then
(cache,Values.STRING("SimCode: The model has been translated"),st,indexed_dlow_1,libs,file_dir);
end matchcontinue;
end translateModel;
public function translateFunctions
"Entry point to translate Modelica/MetaModelica functions to C functions.
Called from other places in the compiler."
input String name;
input list<DAE.Element> daeElements;
input list<DAE.Type> metarecordTypes;
algorithm
_ :=
matchcontinue (name, daeElements, metarecordTypes)
local
list<Function> fns;
list<String> libs;
MakefileParams makefileParams;
FunctionCode fnCode;
list<RecordDeclaration> extraRecordDecls;
case (name, daeElements, metarecordTypes)
equation
// Create FunctionCode
(fns, extraRecordDecls) = elaborateFunctions(daeElements, metarecordTypes);
libs = extractLibs(fns);
makefileParams = createMakefileParams(libs);
fnCode = FUNCTIONCODE(name, fns, makefileParams, extraRecordDecls);
// Generate code
_ = Tpl.tplString(SimCodeC.translateFunctions, fnCode);
then
();
end matchcontinue;
end translateFunctions;
/* Finds the called functions in DAELow and transforms them to a list of
libraries and a list of Function uniontypes. */
protected function createFunctions
input SCode.Program inProgram;
input DAE.DAElist inDAElist;
input DAELow.DAELow inDAELow;
input Absyn.Path inPath;
input String inString;
output list<String> libs;
output list<Function> functions;
output DAELow.DAELow outDAELow;
output DAE.DAElist outDAE;
algorithm
(libs, functions, outDAELow, outDAE) :=
matchcontinue (inProgram,inDAElist,inDAELow,inPath,inString)
local
list<Absyn.Path> funcPaths, funcRefPaths, funcNormalPaths;
list<String> debugpathstrs,libs1,libs2,includes;
String debugpathstr,debugstr,filenameprefix, str;
list<DAE.Element> funcelems,part_func_elems, elements, funcRefElems, funcNormal;
list<SCode.Class> p;
DAE.DAElist dae;
DAELow.DAELow dlow;
Absyn.Path path;
list<Function> fns;
SimCode sc;
DAE.FunctionTree funcs;
case (p,(dae as DAE.DAE(elementLst = elements, functions = funcs)),dlow,path,filenameprefix)
equation
// get all the used functions from the function tree
funcelems = Util.listMap(DAEUtil.avlTreeToList(funcs),Util.tuple22);
// print ("Detected DAE functions: "+& intString(listLength(funcelems)) +& "\n");
// Debug.fprint("info", "Found called functions: ") "debug" ;
// debugpathstrs = Util.listMap(funcpaths, Absyn.pathString) "debug" ;
// debugpathstr = Util.stringDelimitList(debugpathstrs, ", ") "debug" ;
// Debug.fprintln("info", debugpathstr) "debug" ;
part_func_elems = PartFn.createPartEvalFunctions(funcelems);
(dae, part_func_elems) = PartFn.partEvalDAE(dae, part_func_elems);
(part_func_elems, dlow) = PartFn.partEvalDAELow(part_func_elems, dlow);
funcelems = Util.listUnion(part_func_elems, part_func_elems);
//funcelems = Util.listUnion(funcelems, part_func_elems);
funcelems = Inline.inlineCallsInFunctions(funcelems,
{DAE.NORM_INLINE(), DAE.AFTER_INDEX_RED_INLINE()});
//debugstr = Print.getString();
//Print.clearBuf();
//Debug.fprintln("info", "Generating functions, call Codegen.\n") "debug" ;
(_, libs1) = generateExternalObjectIncludes(dlow);
//libs1 = {};
//usless filter, all are already functions from generateFunctions2
//funcelems := Util.listFilter(funcelems, DAEUtil.isFunction);
(fns, _) = elaborateFunctions(funcelems, {}); // Do we need metarecords here as well?
//TODO: libs ? see in Codegen.cPrintFunctionIncludes(cfns)
libs2 = extractLibs(fns);
then
(Util.listUnion(libs1,libs2), fns, dlow, dae);
case (_,_,_,_,_)
equation
Error.addMessage(Error.INTERNAL_ERROR, {"Creation of Modelica functions failed. "});
then
fail();
end matchcontinue;
end createFunctions;
public function getCalledFunctions
"Goes through the DAELow structure, finds all function calls, and returns them
in a list. Removes duplicates."
input DAE.DAElist dae;
input DAELow.DAELow dlow;
output list<Absyn.Path> res;
list<Exp.Exp> explist,fcallexps,fcallexps_1,fcallexps_2;
list<Absyn.Path> calledfuncs;
algorithm
explist := DAELow.getAllExps(dlow);
fcallexps := getMatchingExpsList(explist, matchCalls);
fcallexps_1 := Util.listSelect(fcallexps, isNotBuiltinCall);
fcallexps_2 := getMatchingExpsList(explist, matchFnRefs);
calledfuncs := Util.listMap(listAppend(fcallexps_1,fcallexps_2), getCallPath);
res := removeDuplicatePaths(calledfuncs);
end getCalledFunctions;
public function getCalledFunctionReferences
"Goes through the DAELow structure, finds all function references calls,
and returns them in a list. Removes duplicates."
input DAE.DAElist dae;
input DAELow.DAELow dlow;
output list<Absyn.Path> res;
list<Exp.Exp> explist,fcallexps;
list<Absyn.Path> calledfuncs;
algorithm
res := matchcontinue(dae, dlow)
case (dae, dlow)
equation
false = RTOpts.acceptMetaModelicaGrammar();
then {};
case (dae, dlow)
equation
true = RTOpts.acceptMetaModelicaGrammar();
explist = DAELow.getAllExps(dlow);
fcallexps = getMatchingExpsList(explist, matchFnRefs);
calledfuncs = Util.listMap(fcallexps, getCallPath);
res = removeDuplicatePaths(calledfuncs);
then res;
end matchcontinue;
end getCalledFunctionReferences;
protected function generateExternalObjectIncludes
"Generates the library paths for external objects"
input DAELow.DAELow daelow;
output list<String> includes;
output list<String> libs;
algorithm
(includes,libs) :=
matchcontinue (daelow)
local
list<list<String>> libsL,includesL;
DAELow.ExternalObjectClasses extObjs;
case DAELow.DAELOW(extObjClasses = extObjs)
equation
(includesL, libsL) = Util.listMap_2(extObjs, generateExternalObjectInclude);
includes = Util.listListUnion(includesL);
libs = Util.listListUnion(libsL);
then (includes,libs);
end matchcontinue;
end generateExternalObjectIncludes;
protected function generateExternalObjectInclude
"Helper function to generateExteralObjectInclude"
input DAELow.ExternalObjectClass extObjCls;
output list<String> includes;
output list<String> libs;
algorithm
(includes,libs) :=
matchcontinue(extObjCls)
local
Option<Absyn.Annotation> ann1,ann2;
list<String> includes1,libs1,includes2,libs2;
case (DAELow.EXTOBJCLASS(constructor=DAE.FUNCTION(functions={DAE.FUNCTION_EXT(externalDecl=DAE.EXTERNALDECL(language=ann1))}),
destructor=DAE.FUNCTION(functions={DAE.FUNCTION_EXT(externalDecl=DAE.EXTERNALDECL(language=ann2))})))
equation
(includes1,libs1) = generateExtFunctionIncludes(ann1);
(includes2,libs2) = generateExtFunctionIncludes(ann2);
includes = Util.listListUnion({includes1, includes2});
libs = Util.listListUnion({libs1, libs2});
then (includes,libs);
end matchcontinue;
end generateExternalObjectInclude;
protected function elaborateFunctions
input list<DAE.Element> daeElements;
input list<DAE.Type> metarecordTypes;
output list<Function> functions;
output list<RecordDeclaration> extraRecordDecls;
protected
list<Function> fns;
list<String> outRecordTypes;
algorithm
(fns, outRecordTypes) := elaborateFunctions2(daeElements, {},{});
functions := listReverse(fns); // Is there a reason why we reverse here?
(extraRecordDecls,_) := elaborateRecordDeclarationsFromTypes(metarecordTypes, {}, outRecordTypes);
end elaborateFunctions;
protected function elaborateFunctions2
input list<DAE.Element> daeElements;
input list<Function> inFunctions;
input list<String> inRecordTypes;
output list<Function> outFunctions;
output list<String> outRecordTypes;
algorithm
(outFunctions, outRecordTypes) :=
matchcontinue (daeElements, inFunctions, inRecordTypes)
local
list<Function> accfns, fns;
Function fn;
list<String> rt, rt_1, rt_2;
DAE.Element fel;
list<DAE.Element> rest;
case ({}, accfns, rt)
then (accfns, rt);
case ((DAE.FUNCTION(partialPrefix = true) :: rest), accfns, rt)
equation
// skip over partial functions
(fns, rt_2) = elaborateFunctions2(rest, accfns, rt);
then
(fns, rt_2);
case ((fel :: rest), accfns, rt)
equation
(fn, rt_1) = elaborateFunction(fel, rt);
(fns, rt_2) = elaborateFunctions2(rest, (fn :: accfns), rt_1);
then
(fns, rt_2);
end matchcontinue;
end elaborateFunctions2;
/* Does the actual work of transforming a DAE.FUNCTION to a Function. */
protected function elaborateFunction
input DAE.Element inElement;
input list<String> inRecordTypes;
output Function outFunction;
output list<String> outRecordTypes;
algorithm
(outFunction,outRecordTypes):=
matchcontinue (inElement,inRecordTypes)
local
String fn_name_str,fn_name_str_1,retstr,extfnname,lang,retstructtype,extfnname_1,n,str;
list<DAE.Element> dae,bivars,orgdae,daelist,funrefs, algs, vars, invars, outvars;
list<String> struct_strs,arg_strs,includes,libs,struct_strs_1,funrefStrs;
Absyn.Path fpath;
list<tuple<String, Types.Type>> args;
Types.Type restype,tp;
list<DAE.ExtArg> extargs;
list<SimExtArg> simextargs;
SimExtArg extReturn;
DAE.ExtArg extretarg;
Option<Absyn.Annotation> ann;
DAE.ExternalDecl extdecl;
DAE.Element comp;
list<String> rt, rt_1, struct_funrefs, struct_funrefs_int;
list<Absyn.Path> funrefPaths;
list<Variable> outVars, inVars, biVars, funArgs, varDecls;
list<RecordDeclaration> recordDecls;
list<Statement> body;
DAE.InlineType inl;
list<DAE.Element> daeElts;
/* Modelica functions. */
case (DAE.FUNCTION(path = fpath,
functions = DAE.FUNCTION_DEF(body = daeElts)::_, // might be followed by derivative maps
type_ = tp as (DAE.T_FUNCTION(funcArg=args, funcResultType=restype), _),
partialPrefix=false), rt)
equation
outVars = Util.listMap(DAEUtil.getOutputVars(daeElts), daeInOutSimVar);
inVars = Util.listMap(DAEUtil.getInputVars(daeElts), daeInOutSimVar);
funArgs = Util.listMap(args, typesSimFunctionArg);
(recordDecls,rt_1) = elaborateRecordDeclarations(daeElts, {}, rt);
vars = Util.listFilter(daeElts, isVarQ);
varDecls = Util.listMap(vars, daeInOutSimVar);
algs = Util.listFilter(daeElts, DAEUtil.isAlgorithm);
body = Util.listMap(algs, elaborateStatement);
then
(FUNCTION(fpath,inVars,outVars,recordDecls,funArgs,varDecls,body),
rt_1);
/* External functions. */
case (DAE.FUNCTION(path = fpath,
functions = DAE.FUNCTION_EXT(body = daeElts, externalDecl = extdecl)::_, // might be followed by derivative maps
type_ = (tp as (DAE.T_FUNCTION(funcArg = args,funcResultType = restype),_))),rt)
equation
DAE.EXTERNALDECL(ident=extfnname, external_=extargs,
parameters=extretarg, returnType=lang, language=ann) = extdecl;
outvars = DAEUtil.getOutputVars(daeElts);
invars = DAEUtil.getInputVars(daeElts);
bivars = DAEUtil.getBidirVars(daeElts);
funArgs = Util.listMap(args, typesSimFunctionArg);
outVars = Util.listMap(DAEUtil.getOutputVars(daeElts), daeInOutSimVar);
inVars = Util.listMap(DAEUtil.getInputVars(daeElts), daeInOutSimVar);
biVars = Util.listMap(DAEUtil.getBidirVars(daeElts), daeInOutSimVar);
(recordDecls,rt_1) = elaborateRecordDeclarations(daeElts, {}, rt);
(includes, libs) = generateExtFunctionIncludes(ann);
simextargs = Util.listMap(extargs, extArgsToSimExtArgs);
extReturn = extArgsToSimExtArgs(extretarg);
(simextargs, extReturn) = fixOutputIndex(outVars, simextargs, extReturn);
then
(EXTERNAL_FUNCTION(fpath, extfnname, funArgs, simextargs, extReturn,
inVars, outVars, biVars, includes, libs, lang,
recordDecls),
rt_1);
/* Record constructor. */
case (DAE.RECORD_CONSTRUCTOR(path = fpath, type_ = tp as (DAE.T_FUNCTION(funcArg = args,funcResultType = restype as (DAE.T_COMPLEX(complexClassType = ClassInf.RECORD(name)),_)),_)), rt)
local
String defhead, head, foot, body, decl1, decl2, assign_res, ret_var, record_var, record_var_dot, return_stmt;
DAE.ExpType expType;
list<String> arg_names, arg_tmp1, arg_tmp2, arg_assignments;
Integer tnr;
Absyn.Path name;
equation
funArgs = Util.listMap(args, typesSimFunctionArg);
(recordDecls,rt_1) = elaborateRecordDeclarationsForRecord(restype, {}, rt);
then
(RECORD_CONSTRUCTOR(name, funArgs, recordDecls),
rt_1);
case (comp,rt)
equation
str = "SimCode.elaborateFunction failed for function: \n" +& DAEDump.dumpFunctionStr(comp);
Error.addMessage(Error.INTERNAL_ERROR, {str});
then
fail();
end matchcontinue;
end elaborateFunction;
protected function typesSimFunctionArg
"function: generateFunctionArgs
Generates code from a function argument."
input Types.FuncArg inFuncArg;
output Variable outVar;
algorithm
outString:=
matchcontinue (inFuncArg)
local
Types.Type tty;
Exp.Type expType;
String name;
case ((name, tty as (DAE.T_FUNCTION(funcArg = args, funcResultType = res_ty), _)))
local
list<Types.FuncArg> args;
DAE.Type res_ty;
Exp.Type res_exp_ty;
list<Variable> var_args;
equation
//expType = Types.elabType(tty);
res_exp_ty = Types.elabType(res_ty);
var_args = Util.listMap(args, typesSimFunctionArg);
then
FUNCTION_PTR(name, res_exp_ty, var_args);
case ((name,tty))
equation
expType = Types.elabType(tty);
then
VARIABLE(DAE.CREF_IDENT(name, expType, {}),expType,NONE,{});
end matchcontinue;
end typesSimFunctionArg;
protected function daeInOutSimVar
input DAE.Element inElement;
output Variable outVar;
algorithm
outVar := matchcontinue(inElement)
local
String name;
Exp.Type expType;
DAE.Type daeType;
Exp.ComponentRef id;
list<Exp.Subscript> inst_dims;
list<DAE.Exp> inst_dims_exp;
Option<DAE.Exp> binding;
case (DAE.VAR(componentRef = id,
kind = DAE.VARIABLE(),
ty = daeType,
binding = binding,
dims = inst_dims
))
equation
expType = Types.elabType(daeType);
inst_dims_exp = Util.listMap(inst_dims, indexSubscriptToExp);
then VARIABLE(id,expType,binding,inst_dims_exp);
case (_)
equation
// TODO: ArrayEqn fails here
Error.addMessage(Error.INTERNAL_ERROR, {"SimCode.daeInOutSimVar failed\n"});
then
fail();
end matchcontinue;
end daeInOutSimVar;
protected function extArgsToSimExtArgs
input DAE.ExtArg extArg;
output SimExtArg simExtArg;
algorithm