/
NFFlatten.mo
1158 lines (1009 loc) · 33.1 KB
/
NFFlatten.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.
*
*/
encapsulated package NFFlatten
" file: NFFlatten.mo
package: NFFlatten
description: Flattening
New instantiation, enable with -d=newInst.
"
import NFBinding.Binding;
import Equation = NFEquation;
import NFFunction.Function;
import NFInstNode.InstNode;
import Statement = NFStatement;
import FlatModel = NFFlatModel;
import Prefix;
import Algorithm = NFAlgorithm;
protected
import ComponentRef = NFComponentRef;
import Dimension = NFDimension;
import ExecStat.execStat;
import ExpressionIterator = NFExpressionIterator;
import Expression = NFExpression;
import Inst = NFInst;
import List;
import NFCall.Call;
import NFClass.Class;
import NFClassTree.ClassTree;
import NFComponent.Component;
import NFModifier.Modifier;
import Sections = NFSections;
import Prefixes = NFPrefixes;
import NFPrefixes.Visibility;
import RangeIterator = NFRangeIterator;
import Subscript = NFSubscript;
import Type = NFType;
import Util;
import MetaModelica.Dangerous.listReverseInPlace;
import ConnectionSets = NFConnectionSets.ConnectionSets;
import Connection = NFConnection;
import Connector = NFConnector;
import ConnectEquations = NFConnectEquations;
import Connections = NFConnections;
import Face = NFConnector.Face;
import System;
import ComplexType = NFComplexType;
import NFInstNode.CachedData;
import NFPrefixes.Variability;
import Variable = NFVariable;
import ElementSource;
import Ceval = NFCeval;
import NFTyping.ExpOrigin;
import SimplifyExp = NFSimplifyExp;
public
type FunctionTree = FunctionTreeImpl.Tree;
encapsulated package FunctionTreeImpl
import Absyn.Path;
import NFFunction.Function;
import BaseAvlTree;
extends BaseAvlTree;
redeclare type Key = Absyn.Path;
redeclare type Value = Function;
redeclare function extends keyStr
algorithm
outString := Absyn.pathString(inKey);
end keyStr;
redeclare function extends valueStr
algorithm
outString := "";
end valueStr;
redeclare function extends keyCompare
algorithm
outResult := Absyn.pathCompareNoQual(inKey1, inKey2);
end keyCompare;
redeclare function addConflictDefault = addConflictKeep;
end FunctionTreeImpl;
function flatten
input InstNode classInst;
input String name;
output FlatModel flatModel;
output FunctionTree funcs;
protected
Sections sections;
list<Variable> vars;
list<Equation> eql, ieql;
list<Algorithm> alg, ialg;
Option<SCode.Comment> cmt;
algorithm
sections := Sections.EMPTY();
cmt := SCode.getElementComment(InstNode.definition(classInst));
(vars, sections) := flattenClass(InstNode.getClass(classInst), ComponentRef.EMPTY(),
Visibility.PUBLIC, NONE(), {}, sections);
vars := listReverseInPlace(vars);
flatModel := match sections
case Sections.SECTIONS()
algorithm
eql := listReverseInPlace(sections.equations);
ieql := listReverseInPlace(sections.initialEquations);
alg := listReverseInPlace(sections.algorithms);
ialg := listReverseInPlace(sections.initialAlgorithms);
then
FlatModel.FLAT_MODEL(vars, eql, ieql, alg, ialg, cmt);
else FlatModel.FLAT_MODEL(vars, {}, {}, {}, {}, cmt);
end match;
execStat(getInstanceName() + "(" + name + ")");
flatModel := resolveConnections(flatModel, name);
funcs := flattenFunctions(flatModel, name);
end flatten;
protected
function flattenClass
input Class cls;
input ComponentRef prefix;
input Visibility visibility;
input Option<Binding> binding;
input output list<Variable> vars;
input output Sections sections;
protected
array<InstNode> comps;
list<Binding> bindings;
Binding b;
algorithm
() := match cls
case Class.INSTANCED_CLASS(elements = ClassTree.FLAT_TREE(components = comps))
algorithm
if isSome(binding) then
SOME(b) := binding;
if Binding.isBound(b) then
b := flattenBinding(b, ComponentRef.rest(prefix));
bindings := getRecordBindings(b);
Error.assertion(listLength(bindings) == arrayLength(comps),
getInstanceName() + " got record binding with wrong number of elements for " +
ComponentRef.toString(prefix),
sourceInfo());
for c in comps loop
(vars, sections) := flattenComponent(c, prefix, visibility, SOME(listHead(bindings)), vars, sections);
bindings := listRest(bindings);
end for;
else
for c in comps loop
(vars, sections) := flattenComponent(c, prefix, visibility, binding, vars, sections);
end for;
end if;
else
for c in comps loop
(vars, sections) := flattenComponent(c, prefix, visibility, NONE(), vars, sections);
end for;
end if;
sections := flattenSections(cls.sections, prefix, sections);
then
();
case Class.TYPED_DERIVED()
algorithm
(vars, sections) :=
flattenClass(InstNode.getClass(cls.baseClass), prefix, visibility, binding, vars, sections);
then
();
case Class.INSTANCED_BUILTIN() then ();
else
algorithm
Error.assertion(false, getInstanceName() + " got non-instantiated component " + ComponentRef.toString(prefix) + "\n", sourceInfo());
then
();
end match;
end flattenClass;
function flattenComponent
input InstNode component;
input ComponentRef prefix;
input Visibility visibility;
input Option<Binding> outerBinding;
input output list<Variable> vars;
input output Sections sections;
protected
InstNode comp_node;
Component c;
Type ty;
Binding condition;
Class cls;
Visibility vis;
algorithm
// Remove components that are only outer.
if InstNode.isOnlyOuter(component) or InstNode.isEmpty(component) then
return;
end if;
comp_node := InstNode.resolveOuter(component);
c := InstNode.component(comp_node);
() := match c
case Component.TYPED_COMPONENT(condition = condition, ty = ty)
algorithm
// Don't add the component if it has a condition that's false.
if Binding.isBound(condition) and Expression.isFalse(Binding.getTypedExp(condition)) then
return;
end if;
cls := InstNode.getClass(c.classInst);
vis := if InstNode.isProtected(component) then Visibility.PROTECTED else visibility;
if isComplexComponent(ty) then
(vars, sections) := flattenComplexComponent(comp_node, c, cls, ty, vis, prefix, vars, sections);
else
(vars, sections) := flattenSimpleComponent(comp_node, c, vis, outerBinding,
Class.getTypeAttributes(cls), prefix, vars, sections);
end if;
then
();
else
algorithm
Error.assertion(false, getInstanceName() + " got unknown component", sourceInfo());
then
fail();
end match;
end flattenComponent;
function isComplexComponent
input Type ty;
output Boolean isComplex;
algorithm
isComplex := match ty
case Type.COMPLEX(complexTy = ComplexType.EXTERNAL_OBJECT()) then false;
case Type.COMPLEX() then true;
case Type.ARRAY() then isComplexComponent(ty.elementType);
else false;
end match;
end isComplexComponent;
function flattenSimpleComponent
input InstNode node;
input Component comp;
input Visibility visibility;
input Option<Binding> outerBinding;
input list<Modifier> typeAttrs;
input ComponentRef prefix;
input output list<Variable> vars;
input output Sections sections;
protected
InstNode comp_node = node;
ComponentRef name;
Binding binding;
Type ty;
Option<SCode.Comment> cmt;
SourceInfo info;
Component.Attributes comp_attr;
Visibility vis;
Equation eq;
list<tuple<String, Binding>> ty_attrs;
algorithm
Component.TYPED_COMPONENT(ty = ty, binding = binding, attributes = comp_attr,
comment = cmt, info = info) := comp;
if isSome(outerBinding) then
SOME(binding) := outerBinding;
else
binding := flattenBinding(binding, prefix);
end if;
// If the component is an array component with a binding and at least discrete variability,
// move the binding into an equation. This avoids having to scalarize the binding.
if Type.isArray(ty) and Binding.isBound(binding) and
Component.variability(comp) >= Variability.DISCRETE then
name := ComponentRef.prefixCref(comp_node, ty, {}, prefix);
eq := Equation.ARRAY_EQUALITY(Expression.CREF(ty, name), Binding.getTypedExp(binding), ty,
ElementSource.createElementSource(info));
sections := Sections.prependEquation(eq, sections);
binding := NFBinding.EMPTY_BINDING;
end if;
name := ComponentRef.prefixScope(comp_node, ty, {}, prefix);
ty_attrs := list(flattenTypeAttribute(m, name) for m in typeAttrs);
vars := Variable.VARIABLE(name, ty, binding, visibility, comp_attr, ty_attrs, cmt, info) :: vars;
end flattenSimpleComponent;
function flattenTypeAttribute
input Modifier attr;
input ComponentRef prefix;
output tuple<String, Binding> outAttr;
protected
Binding binding;
algorithm
binding := flattenBinding(Modifier.binding(attr), prefix, isTypeAttribute = true);
outAttr := (Modifier.name(attr), binding);
end flattenTypeAttribute;
function getRecordBindings
input Binding binding;
output list<Binding> recordBindings;
protected
Expression binding_exp;
list<Expression> expl;
Variability var;
algorithm
binding_exp := Binding.getTypedExp(binding);
var := Binding.variability(binding);
recordBindings := match binding_exp
case Expression.RECORD() then
list(if Expression.isEmpty(e) then
// The binding for a record field might be Expression.EMPTY if it comes
// from an evaluated function call where it wasn't assigned a value.
NFBinding.EMPTY_BINDING
else
Binding.FLAT_BINDING(e, var)
for e in binding_exp.elements);
else
algorithm
Error.assertion(false, getInstanceName() + " got non-record binding " +
Expression.toString(binding_exp), sourceInfo());
then
fail();
end match;
end getRecordBindings;
function flattenComplexComponent
input InstNode node;
input Component comp;
input Class cls;
input Type ty;
input Visibility visibility;
input ComponentRef prefix;
input output list<Variable> vars;
input output Sections sections;
protected
list<Dimension> dims;
ComponentRef name;
Binding binding;
Option<Binding> opt_binding;
Expression binding_exp;
Equation eq;
list<Expression> bindings;
Variability comp_var;
algorithm
dims := Type.arrayDims(ty);
binding := Component.getBinding(comp);
// Create an equation if there's a binding on a complex component.
if Binding.isExplicitlyBound(binding) then
binding := flattenBinding(binding, prefix);
binding_exp := Binding.getTypedExp(binding);
comp_var := Component.variability(comp);
if comp_var <= Variability.PARAMETER then
binding_exp := Ceval.evalExp(binding_exp);
else
binding_exp := SimplifyExp.simplify(binding_exp);
end if;
if not Expression.isRecord(binding_exp) then
name := ComponentRef.prefixCref(node, ty, {}, prefix);
eq := Equation.EQUALITY(Expression.CREF(ty, name), binding_exp, ty,
ElementSource.createElementSource(InstNode.info(node)));
sections := Sections.prependEquation(eq, sections);
opt_binding := SOME(NFBinding.EMPTY_BINDING);
else
binding := Binding.setTypedExp(binding_exp, binding);
opt_binding := SOME(binding);
end if;
else
opt_binding := NONE();
end if;
name := ComponentRef.prefixScope(node, ty, {}, prefix);
// Flatten the class directly if the component is a scalar, otherwise scalarize it.
if listEmpty(dims) then
(vars, sections) := flattenClass(cls, name, visibility, opt_binding, vars, sections);
else
(vars, sections) := flattenArray(cls, dims, name, visibility, opt_binding, vars, sections);
end if;
end flattenComplexComponent;
function flattenArray
input Class cls;
input list<Dimension> dimensions;
input ComponentRef prefix;
input Visibility visibility;
input Option<Binding> binding;
input output list<Variable> vars;
input output Sections sections;
input list<Subscript> subscripts = {};
protected
Dimension dim;
list<Dimension> rest_dims;
ComponentRef sub_pre;
RangeIterator range_iter;
Expression sub_exp;
algorithm
if listEmpty(dimensions) then
sub_pre := ComponentRef.setSubscripts(listReverse(subscripts), prefix);
(vars, sections) := flattenClass(cls, sub_pre, visibility, binding, vars, sections);
else
dim :: rest_dims := dimensions;
range_iter := RangeIterator.fromDim(dim);
while RangeIterator.hasNext(range_iter) loop
(range_iter, sub_exp) := RangeIterator.next(range_iter);
(vars, sections) := flattenArray(cls, rest_dims, prefix, visibility,
binding, vars, sections, Subscript.INDEX(sub_exp) :: subscripts);
end while;
end if;
end flattenArray;
function flattenBinding
input output Binding binding;
input ComponentRef prefix;
input Boolean isTypeAttribute = false;
algorithm
binding := match binding
local
list<Subscript> subs, accum_subs;
Integer binding_level;
Expression bind_exp;
list<InstNode> pars;
InstNode par;
case Binding.UNBOUND() then binding;
case Binding.TYPED_BINDING()
algorithm
bind_exp := binding.bindingExp;
pars := listRest(binding.parents);
// TODO: Optimize this, making a list of all subscripts in the prefix
// when only a few are needed is unnecessary.
if not (binding.isEach or listEmpty(pars)) then
if isTypeAttribute then
pars := listRest(pars);
end if;
binding_level := 0;
for parent in pars loop
binding_level := binding_level + Type.dimensionCount(InstNode.getType(parent));
end for;
if binding_level > 0 then
subs := listAppend(listReverse(s) for s in ComponentRef.subscriptsAll(prefix));
accum_subs := {};
for i in 1:binding_level loop
if listEmpty(subs) then
break;
end if;
accum_subs := listHead(subs) :: accum_subs;
subs := listRest(subs);
end for;
bind_exp := Expression.applySubscripts(accum_subs, bind_exp);
end if;
end if;
binding.bindingExp := flattenExp(bind_exp, prefix);
then
binding;
// CEVAL_BINDINGs are temporary bindings generated by the constant
// evaluation and no longer needed after flattening.
case Binding.CEVAL_BINDING() then NFBinding.EMPTY_BINDING;
else
algorithm
Error.assertion(false, getInstanceName() + " got untyped binding.", sourceInfo());
then
fail();
end match;
end flattenBinding;
function flattenExp
input output Expression exp;
input ComponentRef prefix;
algorithm
exp := Expression.map(exp, function flattenExp_traverse(prefix = prefix));
end flattenExp;
function flattenExp_traverse
input output Expression exp;
input ComponentRef prefix;
algorithm
exp := match exp
case Expression.CREF()
algorithm
exp.cref := ComponentRef.transferSubscripts(prefix, exp.cref);
then
exp;
else exp;
end match;
end flattenExp_traverse;
function flattenSections
input Sections sections;
input ComponentRef prefix;
input output Sections accumSections;
algorithm
() := match sections
local
list<Equation> eq, ieq;
list<Algorithm> alg, ialg;
case Sections.SECTIONS()
algorithm
eq := flattenEquations(sections.equations, prefix);
ieq := flattenEquations(sections.initialEquations, prefix);
alg := flattenAlgorithms(sections.algorithms, prefix);
ialg := flattenAlgorithms(sections.initialAlgorithms, prefix);
accumSections := Sections.prepend(eq, ieq, alg, ialg, accumSections);
then
();
else ();
end match;
end flattenSections;
function flattenEquations
input list<Equation> eql;
input ComponentRef prefix;
output list<Equation> equations = {};
algorithm
for eq in eql loop
equations := flattenEquation(eq, prefix, equations);
end for;
end flattenEquations;
function flattenEquation
input Equation eq;
input ComponentRef prefix;
input output list<Equation> equations;
algorithm
equations := match eq
local
Expression e1, e2, e3;
case Equation.EQUALITY()
algorithm
e1 := flattenExp(eq.lhs, prefix);
e2 := flattenExp(eq.rhs, prefix);
then
Equation.EQUALITY(e1, e2, eq.ty, eq.source) :: equations;
case Equation.FOR()
then unrollForLoop(eq, prefix, equations);
case Equation.CONNECT()
algorithm
e1 := flattenExp(eq.lhs, prefix);
e2 := flattenExp(eq.rhs, prefix);
then
Equation.CONNECT(e1, e2, eq.source) :: equations;
case Equation.IF()
then flattenIfEquation(eq.branches, prefix, eq.source, equations);
case Equation.WHEN()
algorithm
eq.branches := list(flattenEqBranch(b, prefix) for b in eq.branches);
then
eq :: equations;
case Equation.ASSERT()
algorithm
e1 := flattenExp(eq.condition, prefix);
e2 := flattenExp(eq.message, prefix);
e3 := flattenExp(eq.level, prefix);
then
Equation.ASSERT(e1, e2, e3, eq.source) :: equations;
case Equation.TERMINATE()
algorithm
e1 := flattenExp(eq.message, prefix);
then
Equation.TERMINATE(e1, eq.source) :: equations;
case Equation.REINIT()
algorithm
e1 := flattenExp(eq.cref, prefix);
e2 := flattenExp(eq.reinitExp, prefix);
then
Equation.REINIT(e1, e2, eq.source) :: equations;
case Equation.NORETCALL()
algorithm
e1 := flattenExp(eq.exp, prefix);
then
Equation.NORETCALL(e1, eq.source) :: equations;
else eq :: equations;
end match;
end flattenEquation;
function flattenIfEquation
input list<tuple<Expression, list<Equation>>> branches;
input ComponentRef prefix;
input DAE.ElementSource source;
input output list<Equation> equations;
protected
list<tuple<Expression, list<Equation>>> bl = {};
Expression cond;
list<Equation> eql;
algorithm
for b in branches loop
(cond, eql) := b;
eql := flattenEquations(eql, prefix);
if Expression.isTrue(cond) and listEmpty(bl) then
// If the condition is literal true and we haven't collected any other
// branches yet, replace the if equation with this branch.
equations := listAppend(eql, equations);
return;
elseif not Expression.isFalse(cond) then
// Only add the branch to the list of branches if the condition is not
// literal false, otherwise just drop it since it will never trigger.
bl := (cond, eql) :: bl;
end if;
end for;
// Add the flattened if equation to the list of equations if we got this far,
// and there are any branches still remaining.
if not listEmpty(bl) then
equations := Equation.IF(listReverseInPlace(bl), source) :: equations;
end if;
end flattenIfEquation;
function flattenEqBranch
input output tuple<Expression, list<Equation>> branch;
input ComponentRef prefix;
protected
Expression exp;
list<Equation> eql;
algorithm
(exp, eql) := branch;
exp := flattenExp(exp, prefix);
eql := flattenEquations(eql, prefix);
branch := (exp, listReverseInPlace(eql));
end flattenEqBranch;
function unrollForLoop
input Equation forLoop;
input ComponentRef prefix;
input output list<Equation> equations;
protected
InstNode iter;
list<Equation> body, unrolled_body;
Expression range;
RangeIterator range_iter;
Expression val;
algorithm
Equation.FOR(iterator = iter, range = SOME(range), body = body) := forLoop;
// Unroll the loop by replacing the iterator with each of its values in the for loop body.
range := Ceval.evalExp(range, Ceval.EvalTarget.RANGE(Equation.info(forLoop)));
range_iter := RangeIterator.fromExp(range);
while RangeIterator.hasNext(range_iter) loop
(range_iter, val) := RangeIterator.next(range_iter);
unrolled_body := list(Equation.mapExp(eq,
function Expression.replaceIterator(iterator = iter, iteratorValue = val)) for eq in body);
unrolled_body := flattenEquations(unrolled_body, prefix);
equations := listAppend(unrolled_body, equations);
end while;
end unrollForLoop;
function flattenAlgorithms
input list<Algorithm> algorithms;
input ComponentRef prefix;
output list<Algorithm> outAlgorithms = {};
algorithm
for alg in algorithms loop
alg.statements := Statement.mapExpList(alg.statements, function flattenExp(prefix = prefix));
// CheckModel relies on the ElementSource to know whether a certain algorithm comes from
// an array component, otherwise is will miscount the number of equations.
if ComponentRef.hasSubscripts(prefix) then
alg.source := addElementSourceArrayPrefix(alg.source, prefix);
end if;
outAlgorithms := alg :: outAlgorithms;
end for;
end flattenAlgorithms;
function addElementSourceArrayPrefix
input output DAE.ElementSource source;
input ComponentRef prefix;
protected
Prefix.ComponentPrefix comp_pre;
algorithm
// It seems the backend doesn't really care about the ComponentPrefix, and
// creating a proper prefix here could be rather expensive. So we just create
// a dummy prefix here with one subscript to keep CheckModel happy.
comp_pre := Prefix.ComponentPrefix.PRE(
ComponentRef.firstName(prefix),
{},
{DAE.Subscript.INDEX(DAE.Exp.ICONST(-1))},
Prefix.ComponentPrefix.NOCOMPPRE(),
ClassInf.State.UNKNOWN(Absyn.IDENT("?")),
Absyn.dummyInfo
);
source := ElementSource.addElementSourceInstanceOpt(source, comp_pre);
end addElementSourceArrayPrefix;
function resolveConnections
input output FlatModel flatModel;
input String name;
protected
Connections conns;
list<Equation> conn_eql;
ConnectionSets.Sets csets;
array<list<Connector>> csets_array;
algorithm
// Generate the connect equations and add them to the equation list.
(flatModel, conns) := Connections.collect(flatModel);
csets := ConnectionSets.fromConnections(conns);
csets_array := ConnectionSets.extractSets(csets);
conn_eql := ConnectEquations.generateEquations(csets_array);
flatModel.equations := listAppend(conn_eql, flatModel.equations);
// Evaluate any connection operators if they're used.
if System.getHasStreamConnectors() or System.getUsesCardinality() then
flatModel := evaluateConnectionOperators(flatModel, csets, csets_array);
end if;
execStat(getInstanceName() + "(" + name + ")");
end resolveConnections;
function evaluateConnectionOperators
input output FlatModel flatModel;
input ConnectionSets.Sets sets;
input array<list<Connector>> setsArray;
algorithm
flatModel.variables := list(evaluateBindingConnOp(c, sets, setsArray) for c in flatModel.variables);
flatModel.equations := evaluateEquationsConnOp(flatModel.equations, sets, setsArray);
flatModel.initialEquations := evaluateEquationsConnOp(flatModel.initialEquations, sets, setsArray);
// TODO: Implement evaluation for algorithm sections.
end evaluateConnectionOperators;
function evaluateBindingConnOp
input output Variable var;
input ConnectionSets.Sets sets;
input array<list<Connector>> setsArray;
protected
Binding binding;
Expression exp, eval_exp;
algorithm
() := match var
case Variable.VARIABLE(binding = binding as Binding.TYPED_BINDING(bindingExp = exp))
algorithm
eval_exp := ConnectEquations.evaluateOperators(exp, sets, setsArray);
if not referenceEq(exp, eval_exp) then
binding.bindingExp := eval_exp;
var.binding := binding;
end if;
then
();
else ();
end match;
end evaluateBindingConnOp;
function evaluateEquationsConnOp
input output list<Equation> equations;
input ConnectionSets.Sets sets;
input array<list<Connector>> setsArray;
algorithm
equations := list(
Equation.mapExp(eq, function ConnectEquations.evaluateOperators(sets = sets, setsArray = setsArray))
for eq in equations);
end evaluateEquationsConnOp;
function flattenFunctions
input FlatModel flatModel;
input String name;
output FunctionTree funcs;
algorithm
funcs := FunctionTree.new();
funcs := List.fold(flatModel.variables, collectComponentFuncs, funcs);
funcs := List.fold(flatModel.equations, collectEquationFuncs, funcs);
funcs := List.fold(flatModel.initialEquations, collectEquationFuncs, funcs);
funcs := List.fold(flatModel.algorithms, collectAlgorithmFuncs, funcs);
funcs := List.fold(flatModel.initialAlgorithms, collectAlgorithmFuncs, funcs);
execStat(getInstanceName() + "(" + name + ")");
end flattenFunctions;
function collectComponentFuncs
input Variable var;
input output FunctionTree funcs;
protected
Binding binding;
ComponentRef cref;
InstNode node;
Type ty;
algorithm
() := match var
case Variable.VARIABLE(ty = ty, binding = binding)
algorithm
// TODO: Collect functions from the component's type attributes.
funcs := collectTypeFuncs(ty, funcs);
// Collect functions used in the component's binding, if it has one.
if Binding.isExplicitlyBound(binding) then
funcs := collectExpFuncs(Binding.getTypedExp(binding), funcs);
end if;
then
();
end match;
end collectComponentFuncs;
function collectTypeFuncs
input Type ty;
input output FunctionTree funcs;
algorithm
() := match ty
local
InstNode con, de;
// Collect external object structors.
case Type.COMPLEX(complexTy = ComplexType.EXTERNAL_OBJECT(constructor = con, destructor = de))
algorithm
funcs := collectStructor(con, funcs);
funcs := collectStructor(de, funcs);
then
();
// Collect record constructors.
case Type.COMPLEX(complexTy = ComplexType.RECORD(constructor = con))
algorithm
funcs := collectStructor(con, funcs);
then
();
else ();
end match;
end collectTypeFuncs;
function collectStructor
input InstNode node;
input output FunctionTree funcs;
protected
CachedData cache;
list<Function> fn;
algorithm
cache := InstNode.getFuncCache(node);
() := match cache
case CachedData.FUNCTION()
algorithm
for fn in cache.funcs loop
funcs := flattenFunction(fn, funcs);
end for;
then
();
else ();
end match;
end collectStructor;
function collectEquationFuncs
input Equation eq;
input output FunctionTree funcs;
algorithm
() := match eq
case Equation.EQUALITY()
algorithm
funcs := collectExpFuncs(eq.lhs, funcs);
funcs := collectExpFuncs(eq.rhs, funcs);
then
();
case Equation.ARRAY_EQUALITY()
algorithm
// Lhs is always a cref, no need to check it.
funcs := collectExpFuncs(eq.rhs, funcs);
then
();
case Equation.FOR()
algorithm
funcs := List.fold(eq.body, collectEquationFuncs, funcs);
then
();
case Equation.IF()
algorithm
funcs := List.fold(eq.branches, collectEqBranchFuncs, funcs);
then
();
case Equation.WHEN()
algorithm
funcs := List.fold(eq.branches, collectEqBranchFuncs, funcs);
then
();
case Equation.ASSERT()
algorithm
funcs := collectExpFuncs(eq.condition, funcs);
funcs := collectExpFuncs(eq.message, funcs);
funcs := collectExpFuncs(eq.level, funcs);
then
();
case Equation.TERMINATE()
algorithm
funcs := collectExpFuncs(eq.message, funcs);
then
();
case Equation.REINIT()
algorithm
funcs := collectExpFuncs(eq.reinitExp, funcs);
then
();
case Equation.NORETCALL()
algorithm
funcs := collectExpFuncs(eq.exp, funcs);
then
();
else ();
end match;
end collectEquationFuncs;
function collectEqBranchFuncs
input tuple<Expression, list<Equation>> branch;
input output FunctionTree funcs;
algorithm
funcs := collectExpFuncs(Util.tuple21(branch), funcs);
funcs := List.fold(Util.tuple22(branch), collectEquationFuncs, funcs);
end collectEqBranchFuncs;
function collectAlgorithmFuncs
input Algorithm alg;
input output FunctionTree funcs;
algorithm
funcs := List.fold(alg.statements, collectStatementFuncs, funcs);
end collectAlgorithmFuncs;
function collectStatementFuncs
input Statement stmt;
input output FunctionTree funcs;