-
Notifications
You must be signed in to change notification settings - Fork 299
/
NFEvalFunction.mo
1530 lines (1344 loc) · 46.3 KB
/
NFEvalFunction.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-2014, Open Source Modelica Consortium (OSMC),
* c/o Linköpings universitet, 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 LICENSE OR
* THIS OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3,
* ACCORDING TO RECIPIENTS CHOICE.
*
* The OpenModelica software and the Open Source Modelica
* Consortium (OSMC) Public License (OSMC-PL) are obtained
* from OSMC, 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 NFEvalFunction
import Binding = NFBinding;
import Call = NFCall;
import Class = NFClass;
import Component = NFComponent;
import ComponentRef = NFComponentRef;
import Dimension = NFDimension;
import Expression = NFExpression;
import NFCeval.EvalTarget;
import NFClassTree.ClassTree;
import NFFunction.Function;
import NFInstNode.InstNode;
import NFInstNode.CachedData;
import Record = NFRecord;
import Sections = NFSections;
import Statement = NFStatement;
import Subscript = NFSubscript;
import Type = NFType;
protected
import Array;
import Autoconf;
import Ceval = NFCeval;
import DAE;
import ElementSource;
import ErrorExt;
import EvalFunctionExt = NFEvalFunctionExt;
import FFI;
import Flags;
import Global;
import MetaModelica.Dangerous.*;
import NFPrefixes.Variability;
import RangeIterator = NFRangeIterator;
import SCode;
import SCodeUtil;
import Settings;
import System;
import Testsuite;
import UnorderedMap;
type FlowControl = enumeration(NEXT, CONTINUE, BREAK, RETURN, ASSERTION);
type ArgumentMap = UnorderedMap<InstNode, Expression>;
public
function evaluate
input Function fn;
input list<Expression> args;
input EvalTarget target;
output Expression result;
algorithm
if Function.isExternal(fn) then
result := evaluateExternal(fn, args, target);
elseif Function.isPartialDerivative(fn) then
// Partial derivatives of functions are differentiated by the backend, so
// make sure we don't try to evaluate the non-differentiated function body.
fail();
else
result := evaluateNormal(fn, args);
end if;
end evaluate;
function evaluateNormal
input Function fn;
input list<Expression> args;
output Expression result;
protected
list<Statement> fn_body;
list<Binding> bindings;
ArgumentMap arg_map;
Integer call_count, limit;
Pointer<Integer> call_counter = fn.callCounter;
FlowControl ctrl;
algorithm
// Functions contain a mutable call counter that's increased by one at the
// start of each evaluation, and decreased by one when the evalution is
// finished. This is used to limit the number of recursive functions calls.
call_count := Pointer.access(call_counter) + 1;
limit := Flags.getConfigInt(Flags.EVAL_RECURSION_LIMIT);
if call_count > limit then
Pointer.update(call_counter, 0);
Error.addSourceMessage(Error.EVAL_RECURSION_LIMIT_REACHED,
{String(limit), AbsynUtil.pathString(Function.name(fn))}, InstNode.info(fn.node));
fail();
end if;
Pointer.update(call_counter, call_count);
try
fn_body := Function.getBody(fn);
arg_map := createArgumentMap(fn.inputs, fn.outputs, fn.locals, args, mutableParams = true);
// TODO: Also apply replacements to the replacements themselves, i.e. the
// bindings of the function parameters. But they probably need to be
// sorted by dependencies first.
fn_body := applyReplacements(arg_map, fn_body);
fn_body := optimizeBody(fn_body);
ctrl := evaluateStatements(fn_body);
if ctrl <> FlowControl.ASSERTION then
result := createResult(arg_map, fn.outputs);
else
fail();
end if;
else
// Make sure we always decrease the call counter even if the evaluation fails.
Pointer.update(call_counter, call_count - 1);
fail();
end try;
if Flags.isSet(Flags.EVAL_FUNC_DUMP) then
print(AbsynUtil.pathString(Function.name(fn)) + " => ");
print(Expression.toString(result));
print("\nArguments:\n");
print(UnorderedMap.toString(arg_map, InstNode.name, Expression.toString));
print("\n");
end if;
Pointer.update(call_counter, call_count - 1);
end evaluateNormal;
function evaluateExternal
input Function fn;
input list<Expression> args;
input EvalTarget target;
output Expression result;
protected
String name, lang;
ComponentRef output_ref;
Option<SCode.Annotation> ann;
list<Expression> ext_args;
algorithm
Sections.EXTERNAL(name = name, args = ext_args, outputRef = output_ref, language = lang, ann = ann) :=
Class.getSections(InstNode.getClass(fn.node));
result := matchcontinue lang
case "builtin"
// Functions defined as 'external "builtin"', delegate to Ceval.
then Ceval.evalBuiltinCall(fn, args, EvalTarget.IGNORE_ERRORS());
case "FORTRAN 77"
// This had better be a Lapack function.
then evaluateExternal2(name, fn, args, ext_args);
case _
// For anything else, try to call the function via FFI.
then callExternalFunction(name, fn, args, ext_args, output_ref, ann);
else
algorithm
if EvalTarget.hasInfo(target) then
Error.addSourceMessage(Error.FAILED_TO_EVALUATE_FUNCTION,
{AbsynUtil.pathString(fn.path)}, EvalTarget.getInfo(target));
end if;
then
fail();
end matchcontinue;
end evaluateExternal;
function evaluateRecordConstructor
"Evaluates a default record constructor call by replacing any field references
with the given arguments, optionally constant evaluating the resulting expression.
Example:
record R
Real x;
constant Real y = x / 2.0;
Real z;
end R;
CALL(R, {1.0, 2.0}) => RECORD(R, {1.0, 0.5, 2.0});
"
input Function fn;
input Type ty;
input list<Expression> args;
input Boolean evaluate = true;
output Expression result;
protected
ArgumentMap arg_map;
list<Expression> expl = {};
InstNode node, out_ty;
algorithm
// Map the record fields to the arguments of the constructor.
arg_map := createArgumentMap(fn.inputs, {}, fn.locals, args, mutableParams = false);
// Use the node of the return type to determine the order of the variables,
// since they might be reordered in the record constructor.
Type.COMPLEX(cls = out_ty) := fn.returnType;
// Fetch the new binding expressions for all the variables, both inputs and locals.
for c in ClassTree.getComponents(Class.classTree(InstNode.getClass(out_ty))) loop
expl := UnorderedMap.getOrFail(c, arg_map) :: expl;
end for;
// Create a new record expression from the mapped arguments.
result := Expression.makeRecord(Function.name(fn), ty, listReverseInPlace(expl));
// Constant evaluate the expression if requested.
if evaluate then
result := Ceval.evalExp(result);
end if;
end evaluateRecordConstructor;
protected
function createArgumentMap
input list<InstNode> inputs;
input list<InstNode> outputs;
input list<InstNode> locals;
input list<Expression> args;
input Boolean mutableParams;
input Boolean buildArrayBinding = true;
output ArgumentMap map;
protected
Expression arg;
list<Expression> rest_args = args;
Function fn;
CachedData cache;
algorithm
map := UnorderedMap.new<Expression>(InstNode.hash, InstNode.refEqual);
// Add inputs to the argument map. Inputs are never mutable.
for i in inputs loop
arg :: rest_args := rest_args;
UnorderedMap.add(i, arg, map);
// If the argument is a function partial application, also add the function
// node to the map so we can replace calls to it with the correct function.
if Expression.isFunctionPointer(arg) then
for fn in Function.getCachedFuncs(i) loop
UnorderedMap.add(fn.node, arg, map);
end for;
end if;
end for;
// Add outputs and local variables to the argument map.
// They sometimes need to be mutable and sometimes not.
if mutableParams then
List.fold(outputs, function addMutableArgument(buildArrayBinding = buildArrayBinding), map);
List.fold(locals, function addMutableArgument(buildArrayBinding = buildArrayBinding), map);
else
List.fold(outputs, function addImmutableArgument(buildArrayBinding = buildArrayBinding), map);
List.fold(locals, function addImmutableArgument(buildArrayBinding = buildArrayBinding), map);
end if;
// Apply the arguments to the arguments themselves. This is done after
// building the map to make sure all the arguments are available.
UnorderedMap.apply(map, function applyBindingReplacement(map = map));
// Evaluate the values of outputs and local variables.
UnorderedMap.apply(map, evaluateReplacement);
end createArgumentMap;
function addMutableArgument
input InstNode node;
input output ArgumentMap map;
input Boolean buildArrayBinding;
protected
Expression exp;
algorithm
exp := getBindingExp(node, map, mutableParams = true, buildArrayBinding = buildArrayBinding);
exp := Expression.makeMutable(exp);
UnorderedMap.add(node, exp, map);
end addMutableArgument;
function addImmutableArgument
input InstNode node;
input output ArgumentMap map;
input Boolean buildArrayBinding;
protected
Expression exp;
algorithm
exp := getBindingExp(node, map, mutableParams = false, buildArrayBinding = buildArrayBinding);
UnorderedMap.add(node, exp, map);
end addImmutableArgument;
function getBindingExp
input InstNode node;
input ArgumentMap map;
input Boolean mutableParams;
input Boolean buildArrayBinding;
output Expression bindingExp;
protected
Component comp;
Binding binding;
Type ty;
algorithm
comp := InstNode.component(node);
binding := Component.getBinding(comp);
if Binding.isBound(binding) then
bindingExp := Binding.getExp(binding);
bindingExp := Expression.map(bindingExp, Expression.clone);
else
bindingExp := buildBinding(node, map, mutableParams, buildArrayBinding);
end if;
end getBindingExp;
function buildBinding
input InstNode node;
input ArgumentMap map;
input Boolean mutableParams;
input Boolean buildArrayBinding;
output Expression result;
protected
Type ty;
algorithm
ty := InstNode.getType(node);
ty := Type.mapDims(ty, function applyReplacementsDim(map = map));
result := match ty
case Type.ARRAY() guard buildArrayBinding and Type.hasKnownSize(ty)
then Expression.fillType(ty, Expression.EMPTY(Type.arrayElementType(ty)));
case Type.COMPLEX() then buildRecordBinding(node, map, mutableParams);
else Expression.EMPTY(ty);
end match;
end buildBinding;
function applyReplacementsDim
input ArgumentMap map;
input output Dimension dim;
algorithm
dim := match dim
local
Expression exp;
case Dimension.EXP()
algorithm
exp := Expression.map(dim.exp, function applyReplacements2(map = map));
exp := Ceval.evalExp(exp);
then
Dimension.fromExp(exp, Variability.CONSTANT);
else dim;
end match;
end applyReplacementsDim;
function buildRecordBinding
"Builds a binding for a record instance that doesn't have an explicit binding.
Binding expressions will be taken from the record fields when available, and
filled with empty expressions when not."
input InstNode recordNode;
input ArgumentMap map;
input Boolean mutableParams;
output Expression result;
protected
InstNode cls_node = InstNode.classScope(recordNode);
Class cls = InstNode.getClass(cls_node);
array<InstNode> comps;
list<Expression> bindings;
Expression exp;
ArgumentMap local_map;
algorithm
result := match cls
case Class.INSTANCED_CLASS(elements = ClassTree.FLAT_TREE(components = comps))
algorithm
bindings := {};
// Create a replacement tree for just the record instance. This is
// needed for records that contain local references such as:
// record R
// Real x;
// Real y = x;
// end R;
// In that case we need to replace the 'x' in the binding of 'y' with
// the binding expression of 'x'.
local_map := UnorderedMap.new<Expression>(InstNode.hash, InstNode.refEqual);
for comp in comps loop
exp := getBindingExp(comp, map, mutableParams, buildArrayBinding = true);
if mutableParams then
exp := Expression.makeMutable(exp);
end if;
UnorderedMap.add(comp, exp, local_map);
end for;
// Replace references to record fields with those fields' bindings in the tree.
UnorderedMap.apply(local_map, function applyBindingReplacement(map = local_map));
bindings := UnorderedMap.valueList(local_map);
then
Expression.makeRecord(InstNode.fullPath(cls_node), cls.ty, bindings);
case Class.TYPED_DERIVED() then buildRecordBinding(cls.baseClass, map, mutableParams);
end match;
end buildRecordBinding;
function applyBindingReplacement
input Expression exp;
input ArgumentMap map;
output Expression outExp;
algorithm
outExp := Expression.map(exp, function applyReplacements2(map = map));
end applyBindingReplacement;
function applyReplacements
input ArgumentMap map;
input output list<Statement> fnBody;
algorithm
fnBody := Statement.mapExpList(fnBody,
function Expression.map(func = function applyReplacements2(map = map)));
end applyReplacements;
function applyReplacements2
input ArgumentMap map;
input output Expression exp;
algorithm
exp := match exp
case Expression.CREF() then applyReplacementCref(map, exp.cref, exp);
case Expression.CALL() then applyReplacementCall(map, exp.call, exp);
case Expression.UNBOX() then exp.exp;
else exp;
end match;
end applyReplacements2;
function applyReplacementCref
input ArgumentMap map;
input ComponentRef cref;
input Expression exp;
output Expression outExp;
protected
list<ComponentRef> cref_parts;
Option<Expression> repl_exp;
InstNode parent, node;
algorithm
// Explode the cref into a list of parts in reverse order.
cref_parts := ComponentRef.toListReverse(cref, includeScope = false);
// If the list is empty it's probably an iterator or _, which shouldn't be replaced.
if listEmpty(cref_parts) then
outExp := exp;
else
// Look up the replacement for the first part in the replacement tree.
parent := ComponentRef.node(listHead(cref_parts));
repl_exp := UnorderedMap.get(parent, map);
if isSome(repl_exp) then
SOME(outExp) := repl_exp;
else
outExp := exp;
return;
end if;
outExp := Expression.applySubscripts(ComponentRef.getSubscripts(listHead(cref_parts)), outExp);
cref_parts := listRest(cref_parts);
if not listEmpty(cref_parts) then
try
// If the cref consists of more than one identifier we need to look up
// the corresponding record field in the expression.
for cr in cref_parts loop
node := ComponentRef.node(cr);
outExp := Expression.makeImmutable(outExp);
outExp := Expression.recordElement(InstNode.name(node), outExp);
outExp := Expression.applySubscripts(ComponentRef.getSubscripts(cr), outExp);
end for;
else
Error.assertion(false, getInstanceName() + " could not find replacement for " +
ComponentRef.toString(cref), sourceInfo());
end try;
end if;
outExp := Expression.map(outExp, function applyReplacements2(map = map));
end if;
end applyReplacementCref;
function applyReplacementCall
"Checks if a function call refers to a function pointer given as a function
partial application expression, and if so replaces the call."
input ArgumentMap map;
input Call call;
input Expression exp;
output Expression outExp;
protected
InstNode repl_node;
Option<Expression> repl_oexp;
Expression repl_exp;
list<Expression> args;
list<String> names;
Function fn;
algorithm
outExp := match call
case Call.TYPED_CALL()
algorithm
repl_oexp := UnorderedMap.get(call.fn.node, map);
if isSome(repl_oexp) then
SOME(repl_exp) := repl_oexp;
outExp := match repl_exp
case Expression.CREF(ty = Type.FUNCTION(fn = fn))
algorithm
// A function pointer is just a function partial application without any extra arguments.
call.arguments := mergeFunctionApplicationArgs(call.fn, call.arguments, fn, {}, {});
call.fn := fn;
then
Expression.CALL(call);
case Expression.PARTIAL_FUNCTION_APPLICATION()
algorithm
fn := listHead(Function.getCachedFuncs(ComponentRef.node(repl_exp.fn)));
// Merge the arguments from the original call with the ones in the function partial application.
call.arguments := mergeFunctionApplicationArgs(call.fn, call.arguments, fn, repl_exp.args, repl_exp.argNames);
// Replace the function with the one in the function partial application.
call.fn := fn;
then
Expression.CALL(call);
else exp;
end match;
else
outExp := exp;
end if;
then
outExp;
else exp;
end match;
end applyReplacementCall;
function evaluateReplacement
"Evaluates the values of mutable variables."
input output Expression exp;
algorithm
() := match exp
case Expression.MUTABLE()
algorithm
Expression.applyMutable(exp, evaluateReplacement2);
then
();
else ();
end match;
end evaluateReplacement;
function evaluateReplacement2
input output Expression exp;
algorithm
exp := match exp
// A mutable expression, only evaluate the expression it contains.
case Expression.MUTABLE()
algorithm
Expression.applyMutable(exp, evaluateReplacement2);
then
exp;
// A record expression, evaluate the fields but keep them mutable if they are.
case Expression.RECORD()
algorithm
exp.elements := list(evaluateReplacement2(e) for e in exp.elements);
then
exp;
else if Expression.contains(exp, Expression.isEmpty) then exp else Ceval.evalExp(exp);
end match;
end evaluateReplacement2;
function mergeFunctionApplicationArgs
input Function oldFn;
input list<Expression> oldArgs;
input Function newFn;
input list<Expression> newArgs;
input list<String> argNames;
output list<Expression> outArgs = {};
protected
UnorderedMap<String, Expression> arg_map;
list<Expression> args;
algorithm
arg_map := UnorderedMap.new<Expression>(stringHashDjb2, stringEq);
// Add default arguments from the slots.
for s in newFn.slots loop
if isSome(s.default) then
UnorderedMap.add(InstNode.name(s.node), Expression.unbox(Util.getOption(s.default)), arg_map);
end if;
end for;
// Add arguments from the function call we're replacing.
args := oldArgs;
for i in oldFn.inputs loop
UnorderedMap.add(InstNode.name(i), Expression.unbox(listHead(args)), arg_map);
args := listRest(args);
end for;
// Add arguments from the function partial application expression.
args := newArgs;
for n in argNames loop
UnorderedMap.add(n, Expression.unbox(listHead(args)), arg_map);
args := listRest(args);
end for;
for i in newFn.inputs loop
outArgs := UnorderedMap.getOrFail(InstNode.name(i), arg_map) :: outArgs;
end for;
outArgs := listReverseInPlace(outArgs);
end mergeFunctionApplicationArgs;
function optimizeBody
input output list<Statement> body;
algorithm
body := list(Statement.map(s, optimizeStatement) for s in body);
end optimizeBody;
function optimizeStatement
input output Statement stmt;
algorithm
() := match stmt
local
Expression iter_exp;
// Replace iterators in for loops with mutable expressions, so we don't need
// to do it each time we enter a for loop during evaluation.
case Statement.FOR()
algorithm
// Make a mutable expression with a placeholder value.
iter_exp := Expression.makeMutable(Expression.EMPTY(InstNode.getType(stmt.iterator)));
// Replace the iterator with the expression in the body of the for loop.
stmt.body := Statement.replaceIteratorList(stmt.body, stmt.iterator, iter_exp);
// Replace the iterator node with the mutable expression too.
stmt.iterator := InstNode.ITERATOR_NODE(iter_exp);
then
();
else ();
end match;
end optimizeStatement;
function createResult
input ArgumentMap map;
input list<InstNode> outputs;
output Expression exp;
protected
list<Expression> expl;
list<Type> types;
Expression e;
algorithm
if listLength(outputs) == 1 then
exp := Ceval.evalExp(UnorderedMap.getOrFail(listHead(outputs), map));
assertAssignedOutput(listHead(outputs), exp);
else
expl := {};
types := {};
for o in outputs loop
e := Ceval.evalExp(UnorderedMap.getOrFail(o, map));
assertAssignedOutput(o, e);
expl := e :: expl;
end for;
expl := listReverseInPlace(expl);
types := list(Expression.typeOf(e) for e in expl);
exp := Expression.TUPLE(Type.TUPLE(types, NONE()), expl);
end if;
end createResult;
function assertAssignedOutput
input InstNode outputNode;
input Expression value;
algorithm
() := match value
case Expression.EMPTY()
algorithm
Error.addSourceMessageAsError(Error.UNASSIGNED_FUNCTION_OUTPUT,
{InstNode.name(outputNode)}, InstNode.info(outputNode));
then
fail();
else ();
end match;
end assertAssignedOutput;
function evaluateStatements
input list<Statement> stmts;
output FlowControl ctrl = FlowControl.NEXT;
algorithm
for s in stmts loop
ctrl := evaluateStatement(s);
if ctrl <> FlowControl.NEXT then
if ctrl == FlowControl.CONTINUE then
ctrl := FlowControl.NEXT;
end if;
break;
end if;
end for;
end evaluateStatements;
function evaluateStatement
input Statement stmt;
output FlowControl ctrl;
algorithm
// adrpo: we really need some error handling here to detect which statement cannot be evaluated
// try
ctrl := match stmt
case Statement.ASSIGNMENT() then evaluateAssignment(stmt.lhs, stmt.rhs, stmt.source);
case Statement.FOR() then evaluateFor(stmt.iterator, stmt.range, stmt.body, stmt.source);
case Statement.IF() then evaluateIf(stmt.branches, stmt.source);
case Statement.ASSERT() then evaluateAssert(stmt.condition, stmt);
case Statement.NORETCALL() then evaluateNoRetCall(stmt.exp, stmt.source);
case Statement.WHILE() then evaluateWhile(stmt.condition, stmt.body, stmt.source);
case Statement.RETURN() then FlowControl.RETURN;
case Statement.BREAK() then FlowControl.BREAK;
else
algorithm
Error.assertion(false, getInstanceName() + " failed on " + anyString(stmt) + "\n", sourceInfo());
then
fail();
end match;
//else
// Error.assertion(false, getInstanceName() + " failed to evaluate statement " + Statement.toString(stmt) + "\n", sourceInfo());
// fail();
//end try;
end evaluateStatement;
function evaluateAssignment
input Expression lhsExp;
input Expression rhsExp;
input DAE.ElementSource source;
output FlowControl ctrl = FlowControl.NEXT;
algorithm
assignVariable(lhsExp, Ceval.evalExp(rhsExp, EvalTarget.STATEMENT(source)));
end evaluateAssignment;
public
function assignVariable
input Expression variable;
input Expression value;
algorithm
() := match (variable, value)
local
Expression var, val;
list<Expression> vals;
Mutable<Expression> var_ptr;
// variable := value
case (Expression.MUTABLE(exp = var_ptr), _)
algorithm
Mutable.update(var_ptr, assignExp(Mutable.access(var_ptr), value));
then
();
// (var1, var2, ...) := (value1, value2, ...)
case (Expression.TUPLE(), Expression.TUPLE(elements = vals))
algorithm
for var in variable.elements loop
val :: vals := vals;
assignVariable(var, val);
end for;
then
();
// variable[subscript1, subscript2, ...] := value
case (Expression.SUBSCRIPTED_EXP(exp = Expression.MUTABLE(exp = var_ptr)), _)
algorithm
assignSubscriptedVariable(var_ptr, variable.subscripts, value);
then
();
// _ := value
case (Expression.CREF(cref = ComponentRef.WILD()), _)
then ();
else
algorithm
Error.assertion(false, getInstanceName() + " failed on " +
Expression.toString(variable) + " := " + Expression.toString(value), sourceInfo());
then
fail();
end match;
end assignVariable;
protected
function assignSubscriptedVariable
input Mutable<Expression> variable;
input list<Subscript> subscripts;
input Expression value;
protected
list<Subscript> subs;
algorithm
subs := list(Subscript.eval(s) for s in subscripts);
Mutable.update(variable, assignArrayElement(Mutable.access(variable), subs, value));
end assignSubscriptedVariable;
function assignArrayElement
input Expression arrayExp;
input list<Subscript> subscripts;
input Expression value;
output Expression result;
protected
Expression sub, val;
list<Subscript> rest_subs;
Integer idx;
array<Expression> subs, vals;
algorithm
result := match (arrayExp, subscripts)
case (Expression.ARRAY(), Subscript.INDEX(sub) :: rest_subs) guard Expression.isScalarLiteral(sub)
algorithm
idx := Expression.toInteger(sub);
if listEmpty(rest_subs) then
arrayUpdate(arrayExp.elements, idx, value);
else
arrayUpdate(arrayExp.elements, idx,
assignArrayElement(arrayGet(arrayExp.elements, idx), rest_subs, value));
end if;
then
arrayExp;
case (Expression.ARRAY(), Subscript.SLICE(sub) :: rest_subs)
algorithm
subs := Expression.arrayElements(sub);
vals := Expression.arrayElements(value);
if arrayLength(subs) > arrayLength(vals) then
fail();
end if;
if listEmpty(rest_subs) then
for i in 1:arrayLength(subs) loop
sub := arrayGetNoBoundsChecking(subs, i);
val := arrayGetNoBoundsChecking(vals, i);
idx := Expression.toInteger(sub);
arrayUpdate(arrayExp.elements, idx, val);
end for;
else
for i in 1:arrayLength(subs) loop
sub := arrayGetNoBoundsChecking(subs, i);
val := arrayGetNoBoundsChecking(vals, i);
idx := Expression.toInteger(sub);
arrayUpdate(arrayExp.elements, idx,
assignArrayElement(arrayGet(arrayExp.elements, idx), rest_subs, val));
end for;
end if;
then
arrayExp;
case (Expression.ARRAY(), Subscript.WHOLE() :: rest_subs)
algorithm
if listEmpty(rest_subs) then
arrayExp.elements := arrayCopy(Expression.arrayElements(value));
else
arrayExp.elements := listArray(list(assignArrayElement(e, rest_subs, v) threaded for
e in arrayExp.elements, v in Expression.arrayElements(value)));
end if;
then
arrayExp;
else
algorithm
Error.assertion(false, getInstanceName() + ": unimplemented case for " +
Expression.toString(arrayExp) +
Subscript.toStringList(subscripts) + " = " +
Expression.toString(value), sourceInfo());
then
fail();
end match;
end assignArrayElement;
function assignExp
input Expression lhs;
input Expression rhs;
output Expression result;
algorithm
result := match lhs
case Expression.RECORD()
then assignRecord(lhs, rhs);
// TODO: Handle arrays.
else rhs;
end match;
end assignExp;
function assignRecord
input Expression lhs;
input Expression rhs;
output Expression result;
algorithm
result := match rhs
local
list<Expression> elems;
Expression e, val;
ClassTree cls_tree;
array<InstNode> comps;
Option<Expression> binding_exp;
Type ty;
case Expression.RECORD()
algorithm
Expression.RECORD(elements = elems) := lhs;
for v in rhs.elements loop
e :: elems := elems;
assignVariable(e, v);
end for;
then
lhs;
case Expression.CREF()
algorithm
Expression.RECORD(elements = elems) := lhs;
cls_tree := Class.classTree(InstNode.getClass(ComponentRef.node(rhs.cref)));
comps := ClassTree.getComponents(cls_tree);
for c in comps loop
e :: elems := elems;
ty := InstNode.getType(c);
val := Expression.CREF(Type.liftArrayLeftList(ty, Type.arrayDims(rhs.ty)),
ComponentRef.prefixCref(c, ty, {}, rhs.cref));
assignVariable(e, val);
end for;
then
lhs;
else rhs;
end match;
end assignRecord;
function evaluateFor
input InstNode iterator;
input Option<Expression> range;
input list<Statement> forBody;
input DAE.ElementSource source;
output FlowControl ctrl = FlowControl.NEXT;
protected
RangeIterator range_iter;
Mutable<Expression> iter_exp;
Expression range_exp, value;
list<Statement> body = forBody;
Integer i = 0, limit = Flags.getConfigInt(Flags.EVAL_LOOP_LIMIT);
algorithm
range_exp := Ceval.evalExp(Util.getOption(range), EvalTarget.STATEMENT(source));
range_iter := RangeIterator.fromExp(range_exp);
if RangeIterator.hasNext(range_iter) then
InstNode.ITERATOR_NODE(exp = Expression.MUTABLE(exp = iter_exp)) := iterator;
// Loop through each value in the iteration range.
while RangeIterator.hasNext(range_iter) loop
(range_iter, value) := RangeIterator.next(range_iter);
// Update the mutable expression with the iteration value and evaluate the statement.
Mutable.update(iter_exp, value);
ctrl := evaluateStatements(body);
if ctrl <> FlowControl.NEXT then
if ctrl == FlowControl.BREAK then
ctrl := FlowControl.NEXT;
end if;
break;
end if;
i := i + 1;
if i > limit then
Error.addSourceMessage(Error.EVAL_LOOP_LIMIT_REACHED, {String(limit)},
ElementSource.getInfo(source));
fail();
end if;
end while;
end if;
end evaluateFor;
function evaluateIf
input list<tuple<Expression, list<Statement>>> branches;
input DAE.ElementSource source;