/
NFFlatten.mo
1750 lines (1539 loc) · 52.3 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 Algorithm = NFAlgorithm;
import CardinalityTable = NFCardinalityTable;
protected
import ComponentRef = NFComponentRef;
import Dimension = NFDimension;
import ExecStat.execStat;
import ExpressionIterator = NFExpressionIterator;
import Expression = NFExpression;
import Flags;
import Inst = NFInst;
import List;
import NFCall.Call;
import NFClass.Class;
import NFClassTree.ClassTree;
import NFComponent.Component;
import NFModifier.Modifier;
import Sections = NFSections;
import NFOCConnectionGraph;
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;
import Restriction = NFRestriction;
import EvalConstants = NFEvalConstants;
import SimplifyModel = NFSimplifyModel;
import InstNodeType = NFInstNode.InstNodeType;
import ExpandableConnectors = NFExpandableConnectors;
import SCodeUtil;
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 := AbsynUtil.pathString(inKey);
end keyStr;
redeclare function extends valueStr
algorithm
outString := "";
end valueStr;
redeclare function extends keyCompare
algorithm
outResult := AbsynUtil.pathCompareNoQual(inKey1, inKey2);
end keyCompare;
redeclare function addConflictDefault = addConflictKeep;
end FunctionTreeImpl;
function flatten
input InstNode classInst;
input String name;
output FlatModel flatModel;
protected
Sections sections;
list<Variable> vars;
list<Equation> eql, ieql;
list<Algorithm> alg, ialg;
Option<SCode.Comment> cmt;
algorithm
sections := Sections.EMPTY();
cmt := SCodeUtil.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(name, vars, eql, ieql, alg, ialg, cmt);
else FlatModel.FLAT_MODEL(name, vars, {}, {}, {}, {}, cmt);
end match;
execStat(getInstanceName() + "(" + name + ")");
flatModel := resolveConnections(flatModel, name);
end flatten;
function collectFunctions
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 collectFunctions;
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
// print(">" + stringAppendList(List.fill(" ", ComponentRef.depth(prefix)-1)) + ComponentRef.toString(prefix) + "\n");
() := 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;
// print("<" + stringAppendList(List.fill(" ", ComponentRef.depth(prefix)-1)) + ComponentRef.toString(prefix) + "\n");
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);
// print("->" + stringAppendList(List.fill(" ", ComponentRef.depth(prefix))) + ComponentRef.toString(prefix) + "." + InstNode.name(component) + "\n");
() := match c
case Component.TYPED_COMPONENT(condition = condition, ty = ty)
algorithm
// Delete the component if it has a condition that's false.
if isDeletedComponent(condition, prefix) then
deleteComponent(component);
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, outerBinding, prefix, vars, sections);
else
(vars, sections) := flattenSimpleComponent(comp_node, c, vis, outerBinding,
Class.getTypeAttributes(cls), prefix, vars, sections);
end if;
then
();
case Component.DELETED_COMPONENT() then ();
else
algorithm
Error.assertion(false, getInstanceName() + " got unknown component", sourceInfo());
then
fail();
end match;
// print("<-" + stringAppendList(List.fill(" ", ComponentRef.depth(prefix))) + ComponentRef.toString(prefix) + "." + InstNode.name(component) + "\n");
end flattenComponent;
function isDeletedComponent
input Binding condition;
input ComponentRef prefix;
output Boolean isDeleted;
protected
Expression exp;
Binding cond;
algorithm
if Binding.isBound(condition) then
// TODO: Flattening the condition works as intended here, but we can't yet
// delete components inside array instances in a reliable way since
// the components share the same node. I.e. we can't delete a[1].x
// while keeping a[2].x. So for now we skip flattening the condition,
// so that we get an error message in that case instead (because then
// the expression will be an array instead of a scalar boolean).
cond := condition;
//cond := flattenBinding(condition, prefix);
exp := Binding.getTypedExp(cond);
exp := Ceval.evalExp(exp, Ceval.EvalTarget.CONDITION(Binding.getInfo(cond)));
exp := Expression.stripBindingInfo(exp);
// Hack to make arrays work when all elements have the same value.
if Expression.arrayAllEqual(exp) then
exp := Expression.arrayFirstScalar(exp);
end if;
isDeleted := match exp
case Expression.BOOLEAN() then not exp.value;
else
algorithm
Error.addSourceMessage(Error.CONDITIONAL_EXP_WITHOUT_VALUE,
{Expression.toString(exp)}, Binding.getInfo(cond));
then
fail();
end match;
else
isDeleted := false;
end if;
end isDeletedComponent;
function deleteComponent
"Recursively marks components as deleted."
input InstNode compNode;
protected
Component comp;
algorithm
// @adrpo: don't delete the inner/outer node, it doesn't work!
if InstNode.isInnerOuterNode(compNode) then
return;
end if;
if not InstNode.isEmpty(compNode) then
comp := InstNode.component(compNode);
InstNode.updateComponent(Component.DELETED_COMPONENT(comp), compNode);
deleteClassComponents(Component.classInstance(comp));
end if;
end deleteComponent;
function deleteClassComponents
input InstNode clsNode;
protected
Class cls = InstNode.getClass(clsNode);
array<InstNode> comps;
algorithm
() := match cls
case Class.INSTANCED_CLASS(elements = ClassTree.FLAT_TREE(components = comps))
guard not Restriction.isType(cls.restriction)
algorithm
for c in comps loop
deleteComponent(c);
end for;
then
();
case Class.TYPED_DERIVED()
algorithm
deleteClassComponents(cls.baseClass);
then
();
else ();
end match;
end deleteClassComponents;
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;
Variability var;
Boolean unfix;
algorithm
Component.TYPED_COMPONENT(ty = ty, binding = binding, attributes = comp_attr,
comment = cmt, info = info) := comp;
var := comp_attr.variability;
if isSome(outerBinding) then
SOME(binding) := outerBinding;
unfix := Binding.isUnbound(binding) and var == Variability.PARAMETER;
else
binding := flattenBinding(binding, prefix);
unfix := false;
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 not Flags.isSet(Flags.NF_API) then
if Type.isArray(ty) and Binding.isBound(binding) and var >= 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;
end if;
name := ComponentRef.prefixScope(comp_node, ty, {}, prefix);
ty_attrs := list(flattenTypeAttribute(m, name) for m in typeAttrs);
// Set fixed = true for parameters that are part of a record instance whose
// binding couldn't be split and was moved to an initial equation.
if unfix then
ty_attrs := List.removeOnTrue("fixed", isTypeAttributeNamed, ty_attrs);
ty_attrs := ("fixed", Binding.FLAT_BINDING(Expression.BOOLEAN(false), Variability.CONSTANT)) :: ty_attrs;
end if;
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 isTypeAttributeNamed
input String name;
input tuple<String, Binding> attr;
output Boolean isNamed;
protected
String attr_name;
algorithm
(attr_name, _) := attr;
isNamed := name == attr_name;
end isTypeAttributeNamed;
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 Option<Binding> outerBinding;
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, binding_var;
algorithm
dims := Type.arrayDims(ty);
binding := if isSome(outerBinding) then Util.getOption(outerBinding) else 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);
binding_var := Binding.variability(binding);
comp_var := Component.variability(comp);
if comp_var <= Variability.STRUCTURAL_PARAMETER or binding_var <= Variability.STRUCTURAL_PARAMETER then
binding_exp := Expression.stripBindingInfo(Ceval.evalExp(binding_exp));
elseif binding_var == Variability.PARAMETER and Component.isFinal(comp) then
try
binding_exp := Expression.stripBindingInfo(Ceval.evalExp(binding_exp));
else
end try;
else
binding_exp := SimplifyExp.simplify(binding_exp);
end if;
binding_exp := Expression.splitRecordCref(binding_exp);
// TODO: This will probably not work so well if the binding is an array that
// contains record non-literals. In that case we should probably
// create an equation for each non-literal in the array, and pass the
// rest on as usual.
if not Expression.isRecordOrRecordArray(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, isInitial = comp_var <= Variability.PARAMETER);
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;
list<Subscript> subs;
list<Variable> vrs;
Sections sects;
algorithm
// if we don't scalarize flatten the class and vectorize it
if not Flags.isSet(Flags.NF_SCALARIZE) then
(vrs, sects) := flattenClass(cls, prefix, visibility, binding, {}, Sections.SECTIONS({}, {}, {}, {}));
// add dimensions to the types
for v in vrs loop
v.ty := Type.liftArrayLeftList(v.ty, dimensions);
vars := v::vars;
end for;
// vectorize equations
() := match sects
case Sections.SECTIONS()
algorithm
for eqn in listReverse(sects.equations) loop
sections := Sections.prependEquation(vectorizeEquation(eqn, dimensions, prefix), sections);
end for;
for eqn in listReverse(sects.initialEquations) loop
sections := Sections.prependEquation(vectorizeEquation(eqn, dimensions, prefix), sections, true);
end for;
for alg in listReverse(sects.algorithms) loop
sections := Sections.prependAlgorithm(vectorizeAlgorithm(alg, dimensions, prefix), sections);
end for;
for alg in listReverse(sects.initialAlgorithms) loop
sections := Sections.prependAlgorithm(vectorizeAlgorithm(alg, dimensions, prefix), sections, true);
end for;
then ();
end match;
return;
end if;
if listEmpty(dimensions) then
subs := listReverse(subscripts);
sub_pre := ComponentRef.setSubscripts(subs, prefix);
(vars, sections) := flattenClass(cls, sub_pre, visibility,
subscriptBindingOpt(subs, 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 vectorizeEquation
input Equation eqn;
input list<Dimension> dimensions;
input ComponentRef prefix;
output Equation veqn;
algorithm
veqn := match eqn
local
InstNode prefix_node, iter;
Integer stop;
Expression range;
case Equation.EQUALITY(lhs = Expression.CREF(), rhs = Expression.CREF())
// convert simple equality of crefs to array equality
then Equation.ARRAY_EQUALITY(eqn.lhs, eqn.rhs, Type.liftArrayLeftList(eqn.ty, dimensions), eqn.source);
else
// wrap general equation into for loop
algorithm
iter := match ComponentRef.node(prefix)
case prefix_node as InstNode.COMPONENT_NODE()
then InstNode.COMPONENT_NODE(
"$i", prefix_node.visibility,
Pointer.create(Component.ITERATOR(Type.INTEGER(), Variability.IMPLICITLY_DISCRETE,
Component.info(Pointer.access(prefix_node.component)))),
prefix_node.parent, InstNodeType.NORMAL_COMP());
end match;
{Dimension.INTEGER(size = stop)} := dimensions;
range := Expression.RANGE(Type.INTEGER(), Expression.INTEGER(1), NONE(), Expression.INTEGER(stop));
veqn := Equation.mapExp(eqn, function addIterator(prefix = prefix, subscript = Subscript.INDEX(Expression.CREF(Type.INTEGER(), ComponentRef.makeIterator(iter, Type.INTEGER())))));
then
Equation.FOR(iter, SOME(range), {veqn}, Equation.source(eqn));
end match;
end vectorizeEquation;
function vectorizeAlgorithm
input Algorithm alg;
input list<Dimension> dimensions;
input ComponentRef prefix;
output Algorithm valg;
algorithm
valg := match alg
local
InstNode prefix_node, iter;
Integer stop;
Expression range;
list<Statement> body;
case Algorithm.ALGORITHM(statements = {Statement.ASSIGNMENT(lhs = Expression.CREF(), rhs = Expression.CREF())})
// let simple assignment as is
then alg;
else
// wrap general algorithm into for loop
algorithm
iter := match ComponentRef.node(prefix)
case prefix_node as InstNode.COMPONENT_NODE()
then InstNode.COMPONENT_NODE(
"$i", prefix_node.visibility,
Pointer.create(Component.ITERATOR(Type.INTEGER(), Variability.IMPLICITLY_DISCRETE,
Component.info(Pointer.access(prefix_node.component)))),
prefix_node.parent, InstNodeType.NORMAL_COMP());
end match;
{Dimension.INTEGER(size = stop)} := dimensions;
range := Expression.RANGE(Type.INTEGER(), Expression.INTEGER(1), NONE(), Expression.INTEGER(stop));
body := Statement.mapExpList(alg.statements, function addIterator(prefix = prefix, subscript = Subscript.INDEX(Expression.CREF(Type.INTEGER(), ComponentRef.makeIterator(iter, Type.INTEGER())))));
then
Algorithm.ALGORITHM({Statement.FOR(iter, SOME(range), body, alg.source)}, alg.source);
end match;
end vectorizeAlgorithm;
function addIterator
input output Expression exp;
input ComponentRef prefix;
input Subscript subscript;
algorithm
exp := Expression.map(exp, function addIterator_traverse(prefix = prefix, subscript = subscript));
end addIterator;
function addIterator_traverse
input output Expression exp;
input ComponentRef prefix;
input Subscript subscript;
protected
String restString, prefixString = ComponentRef.toString(prefix);
Integer prefixLength = stringLength(prefixString);
algorithm
exp := match exp
local
ComponentRef restCref;
case Expression.CREF(cref = ComponentRef.CREF(restCref = restCref))
algorithm
restString := ComponentRef.toString(restCref);
if prefixLength <= stringLength(restString) and prefixString == substring(restString, 1, prefixLength) then
exp.cref := ComponentRef.applySubscripts({subscript}, exp.cref);
end if;
then
exp;
else exp;
end match;
end addIterator_traverse;
function subscriptBindingOpt
input list<Subscript> subscripts;
input output Option<Binding> binding;
protected
Binding b;
Expression exp;
Type ty;
algorithm
if isSome(binding) then
SOME(b) := binding;
binding := match b
case Binding.TYPED_BINDING(bindingExp = exp, bindingType = ty)
algorithm
b.bindingExp := Expression.applySubscripts(subscripts, exp);
b.bindingType := Type.arrayElementType(ty);
then
SOME(b);
case Binding.FLAT_BINDING(bindingExp = exp)
algorithm
b.bindingExp := Expression.applySubscripts(subscripts, exp);
then
SOME(b);
else binding;
end match;
end if;
end subscriptBindingOpt;
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
if binding.isFlattened then
return;
end if;
binding.bindingExp := flattenBindingExp(binding.bindingExp, prefix, isTypeAttribute);
binding.isFlattened := true;
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;
case Binding.FLAT_BINDING() then binding;
case Binding.INVALID_BINDING()
algorithm
Error.addTotalMessages(binding.errors);
then
fail();
else
algorithm
Error.assertion(false, getInstanceName() + " got untyped binding.", sourceInfo());
then
fail();
end match;
end flattenBinding;
function flattenBindingExp
input Expression exp;
input ComponentRef prefix;
input Boolean isTypeAttribute = false;
output Expression outExp;
protected
list<Subscript> subs, accum_subs;
Integer binding_level;
list<InstNode> parents;
ComponentRef pre;
InstNode cr_node, par;
algorithm
outExp := match exp
case Expression.BINDING_EXP(exp = outExp)
algorithm
parents := listRest(exp.parents);
if not exp.isEach then
if isTypeAttribute and not listEmpty(parents) then
parents := listRest(parents);
end if;
if not listEmpty(parents) then
outExp := flattenBindingExp2(outExp, prefix, parents);
end if;
end if;
then
flattenExp(outExp, prefix);
else exp;
end match;
end flattenBindingExp;
function flattenBindingExp2
input Expression exp;
input ComponentRef prefix;
input list<InstNode> parents;
output Expression outExp = exp;
protected
Integer binding_level = 0;
list<Subscript> subs;
ComponentRef pre = prefix;
InstNode pre_node, par;
algorithm
par := listHead(parents);
if InstNode.isComponent(par) then
pre_node := ComponentRef.node(pre);
while not InstNode.refEqual(pre_node, par) loop
pre := ComponentRef.rest(pre);
if ComponentRef.isEmpty(pre) then
return;
end if;
pre_node := ComponentRef.node(pre);
end while;
end if;
for parent in parents loop
binding_level := binding_level + Type.dimensionCount(InstNode.getType(parent));
end for;
if binding_level > 0 then
// TODO: Optimize this, making a list of all subscripts in the prefix when
// only a few are needed is unnecessary.
subs := listAppend(listReverse(s) for s in ComponentRef.subscriptsAll(pre));
binding_level := min(binding_level, listLength(subs));
subs := List.firstN_reverse(subs, binding_level);
outExp := Expression.applySubscripts(subs, exp);
end if;
end flattenBindingExp2;
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;
case Expression.BINDING_EXP() then flattenBindingExp(exp, prefix);
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;
list<Equation> eql;
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()
algorithm
if Flags.isSet(Flags.NF_SCALARIZE) then
eql := unrollForLoop(eq, prefix, equations);
else
eql := splitForLoop(eq, prefix, equations);
end if;
then eql;
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, prefix, 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()