This repository has been archived by the owner on May 18, 2019. It is now read-only.
/
NFFunction.mo
2095 lines (1848 loc) · 64.8 KB
/
NFFunction.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 NFFunction
import Absyn;
import Expression = NFExpression;
import Pointer;
import NFInstNode.InstNode;
import Type = NFType;
import NFPrefixes.*;
import List;
import FunctionDerivative = NFFunctionDerivative;
import NFModifier.Modifier;
protected
import ErrorExt;
import Inst = NFInst;
import NFBinding.Binding;
import Config;
import DAE;
import DAEDump;
import Error;
import InstUtil;
import NFClass.Class;
import NFComponent.Component;
import NFComponent.Component.Attributes;
import Typing = NFTyping;
import TypeCheck = NFTypeCheck;
import Util;
import ComponentRef = NFComponentRef;
import NFInstNode.CachedData;
import Lookup = NFLookup;
import ClassTree = NFClassTree.ClassTree;
import Prefixes = NFPrefixes;
import NFLookupState.LookupState;
import Record = NFRecord;
import NFTyping.ClassScope;
import MatchKind = NFTypeCheck.MatchKind;
import Restriction = NFRestriction;
import NFTyping.ExpOrigin;
import Dimension = NFDimension;
import Statement = NFStatement;
import Sections = NFSections;
import Algorithm = NFAlgorithm;
import OperatorOverloading = NFOperatorOverloading;
import MetaModelica.Dangerous.listReverseInPlace;
import Array;
import ElementSource;
public
type NamedArg = tuple<String, Expression>;
type TypedArg = tuple<Expression, Type, Variability>;
type TypedNamedArg = tuple<String, Expression, Type, Variability>;
public
type SlotType = enumeration(
POSITIONAL "Only accepts positional arguments.",
NAMED "Only accepts named argument.",
GENERIC "Accepts both positional and named arguments."
) "Determines which type of argument a slot accepts.";
type SlotEvalStatus = enumeration(NOT_EVALUATED, EVALUATING, EVALUATED);
uniontype Slot
record SLOT
String name;
SlotType ty;
Option<Expression> default;
Option<TypedArg> arg;
Integer index;
SlotEvalStatus evalStatus;
end SLOT;
function positional
input Slot slot;
output Boolean pos;
algorithm
pos := match slot.ty
case SlotType.POSITIONAL then true;
case SlotType.GENERIC then true;
else false;
end match;
end positional;
function named
input Slot slot;
output Boolean pos;
algorithm
pos := match slot.ty
case SlotType.NAMED then true;
case SlotType.GENERIC then true;
else false;
end match;
end named;
function hasName
input String name;
input Slot slot;
output Boolean hasName = name == slot.name;
end hasName;
end Slot;
public
encapsulated
uniontype FunctionMatchKind
import Dimension = NFDimension;
record EXACT "Exact match." end EXACT;
record CAST "Matched by casting one or more arguments. e.g. Integer to Real" end CAST;
record GENERIC "Matched with a generic type on one or more arguments e.g. function F<T> input T i; end F; F(1)"
end GENERIC;
record VECTORIZED "Matched by vectorization"
list<Dimension> vect_dims;
// When vectorizing a call exact argument matches are allowed to not be vectorized
// Instead they are added to each call as is.
// This list represents which args should be vectorized.
list<Boolean> is_vectorized;
FunctionMatchKind baseMatch;
end VECTORIZED;
record NOT_COMPATIBLE end NOT_COMPATIBLE;
function isValid
input FunctionMatchKind mk;
output Boolean b;
algorithm
b := match mk
case NOT_COMPATIBLE() then false;
else true;
end match;
end isValid;
function isExact
input FunctionMatchKind mk;
output Boolean b;
algorithm
b := match mk
case EXACT() then true;
else false;
end match;
end isExact;
function isVectorized
input FunctionMatchKind mk;
output Boolean b;
algorithm
b := match mk
case VECTORIZED() then true;
else false;
end match;
end isVectorized;
function isExactVectorized
input FunctionMatchKind mk;
output Boolean b;
algorithm
b := match mk
case VECTORIZED(baseMatch = EXACT()) then true;
else false;
end match;
end isExactVectorized;
end FunctionMatchKind;
constant FunctionMatchKind EXACT_MATCH = FunctionMatchKind.EXACT();
constant FunctionMatchKind CAST_MATCH = FunctionMatchKind.CAST();
constant FunctionMatchKind GENERIC_MATCH = FunctionMatchKind.GENERIC();
constant FunctionMatchKind NO_MATCH = FunctionMatchKind.NOT_COMPATIBLE();
encapsulated
uniontype MatchedFunction
import NFFunction.Function;
import NFFunction.TypedArg;
import NFFunction.FunctionMatchKind;
record MATCHED_FUNC
Function func;
list<TypedArg> args;
FunctionMatchKind mk;
end MATCHED_FUNC;
function getExactMatches
input list<MatchedFunction> matchedFunctions;
output list<MatchedFunction> outFuncs = list(mf for mf guard(FunctionMatchKind.isExact(mf.mk)) in matchedFunctions);
end getExactMatches;
function getExactVectorizedMatches
input list<MatchedFunction> matchedFunctions;
output list<MatchedFunction> outFuncs =
list(mf for mf guard(FunctionMatchKind.isExactVectorized(mf.mk)) in matchedFunctions);
end getExactVectorizedMatches;
function isVectorized
input MatchedFunction mf;
output Boolean b = FunctionMatchKind.isVectorized(mf.mk);
end isVectorized;
end MatchedFunction;
type FunctionStatus = enumeration(
BUILTIN "A builtin function.",
INITIAL "The initial status.",
EVALUATED "Constants in the function has been evaluated by EvalConstants.",
SIMPLIFIED "The function has been simplified by SimplifyModel.",
COLLECTED "The function has been added to the function tree."
);
uniontype Function
record FUNCTION
Absyn.Path path;
InstNode node;
list<InstNode> inputs;
list<InstNode> outputs;
list<InstNode> locals;
list<Slot> slots;
Type returnType;
DAE.FunctionAttributes attributes;
list<FunctionDerivative> derivatives;
Pointer<FunctionStatus> status;
Pointer<Integer> callCounter "Used during function evaluation to limit recursion.";
end FUNCTION;
function new
input Absyn.Path path;
input InstNode node;
output Function fn;
protected
Class cls;
list<InstNode> inputs, outputs, locals;
list<Slot> slots;
DAE.FunctionAttributes attr;
FunctionStatus status;
algorithm
(inputs, outputs, locals) := collectParams(node);
attr := makeAttributes(node, inputs, outputs);
// Make sure builtin functions aren't added to the function tree.
status := if isBuiltinAttr(attr) then FunctionStatus.COLLECTED else FunctionStatus.INITIAL;
fn := FUNCTION(path, node, inputs, outputs, locals, {}, Type.UNKNOWN(),
attr, {}, Pointer.create(status), Pointer.create(0));
end new;
function lookupFunctionSimple
input String functionName;
input InstNode scope;
output ComponentRef functionRef;
protected
InstNode found_scope;
LookupState state;
Absyn.Path functionPath;
ComponentRef prefix;
algorithm
(functionRef, found_scope) :=
Lookup.lookupFunctionNameSilent(Absyn.CREF_IDENT(functionName, {}), scope);
prefix := ComponentRef.fromNodeList(InstNode.scopeList(found_scope));
functionRef := ComponentRef.append(functionRef, prefix);
end lookupFunctionSimple;
function lookupFunction
input Absyn.ComponentRef functionName;
input InstNode scope;
input SourceInfo info;
output ComponentRef functionRef;
protected
InstNode found_scope;
LookupState state;
Absyn.Path functionPath;
ComponentRef prefix;
Boolean is_class;
algorithm
try
// Make sure the name is a path.
functionPath := Absyn.crefToPath(functionName);
else
Error.addSourceMessageAndFail(Error.SUBSCRIPTED_FUNCTION_CALL,
{Dump.printComponentRefStr(functionName)}, info);
end try;
(functionRef, found_scope) := Lookup.lookupFunctionName(functionName, scope, info);
// If we found a function class we include the root in the prefix, but if we
// instead found a component (i.e. a functional parameter) we don't.
is_class := InstNode.isClass(ComponentRef.node(functionRef));
prefix := ComponentRef.fromNodeList(InstNode.scopeList(InstNode.classScope(found_scope), includeRoot = is_class));
functionRef := ComponentRef.append(functionRef, prefix);
end lookupFunction;
function instFunction
input Absyn.ComponentRef functionName;
input InstNode scope;
input SourceInfo info;
output ComponentRef fn_ref;
output InstNode fn_node;
output Boolean specialBuiltin;
protected
CachedData cache;
algorithm
fn_ref := lookupFunction(functionName, scope, info);
(fn_ref, fn_node, specialBuiltin) := instFunctionRef(fn_ref, info);
end instFunction;
function instFunctionRef
input output ComponentRef fn_ref;
input SourceInfo info;
output InstNode fn_node;
output Boolean specialBuiltin;
protected
CachedData cache;
algorithm
fn_node := InstNode.classScope(ComponentRef.node(fn_ref));
cache := InstNode.getFuncCache(fn_node);
// Check if a cached instantiation of this function already exists.
(fn_node, specialBuiltin) := match cache
case CachedData.FUNCTION() then (fn_node, cache.specialBuiltin);
else instFunction2(ComponentRef.toPath(fn_ref), fn_node, info);
end match;
end instFunctionRef;
function instFunctionNode
"Instantiates the given InstNode as a function."
input output InstNode node;
protected
CachedData cache;
algorithm
cache := InstNode.getFuncCache(node);
() := match cache
case CachedData.FUNCTION() then ();
else
algorithm
node := instFunction2(InstNode.scopePath(node), node, InstNode.info(node));
then
();
end match;
end instFunctionNode;
function instFunction2
input Absyn.Path fnPath;
input output InstNode fnNode;
input SourceInfo info;
output Boolean specialBuiltin;
protected
SCode.Element def = InstNode.definition(fnNode);
algorithm
(fnNode, specialBuiltin) := match def
local
SCode.ClassDef cdef;
Function fn;
Absyn.ComponentRef cr;
InstNode sub_fnNode;
list<Function> funcs;
list<FunctionDerivative> fn_ders;
case SCode.CLASS() guard SCode.isOperatorRecord(def)
algorithm
fnNode := instFunction3(fnNode);
fnNode := OperatorOverloading.instConstructor(fnPath, fnNode, info);
then
(fnNode, false);
case SCode.CLASS() guard SCode.isRecord(def)
algorithm
fnNode := instFunction3(fnNode);
fnNode := Record.instDefaultConstructor(fnPath, fnNode, info);
then
(fnNode, false);
case SCode.CLASS(restriction = SCode.R_OPERATOR(), classDef = cdef as SCode.PARTS())
algorithm
fnNode := instFunction3(fnNode);
fnNode := OperatorOverloading.instOperatorFunctions(fnNode, info);
then
(fnNode, false);
case SCode.CLASS(classDef = cdef as SCode.OVERLOAD())
algorithm
for p in cdef.pathLst loop
cr := Absyn.pathToCref(p);
(_,sub_fnNode,specialBuiltin) := instFunction(cr,fnNode,info);
for f in getCachedFuncs(sub_fnNode) loop
fnNode := InstNode.cacheAddFunc(fnNode, f, specialBuiltin);
end for;
end for;
then
(fnNode, false);
case SCode.CLASS()
algorithm
if SCode.isOperator(def) then
OperatorOverloading.checkOperatorRestrictions(fnNode);
end if;
fnNode := InstNode.setNodeType(NFInstNode.InstNodeType.ROOT_CLASS(), fnNode);
fnNode := instFunction3(fnNode);
fn := new(fnPath, fnNode);
specialBuiltin := isSpecialBuiltin(fn);
fn.derivatives := FunctionDerivative.instDerivatives(fnNode, fn);
fnNode := InstNode.cacheAddFunc(fnNode, fn, specialBuiltin);
then
(fnNode, specialBuiltin);
end match;
end instFunction2;
function instFunction3
input output InstNode fnNode;
algorithm
fnNode := Inst.instantiate(fnNode);
// Set up an empty function cache to signal that this function is
// currently being instantiated, so recursive functions can be handled.
InstNode.cacheInitFunc(fnNode);
Inst.instExpressions(fnNode);
end instFunction3;
function getCachedFuncs
input InstNode inNode;
output list<Function> outFuncs;
protected
CachedData cache;
algorithm
cache := InstNode.getFuncCache(InstNode.classScope(inNode));
outFuncs := match cache
case CachedData.FUNCTION() then cache.funcs;
else fail();
end match;
end getCachedFuncs;
function isEvaluated
input Function fn;
output Boolean evaluated;
algorithm
evaluated := match Pointer.access(fn.status)
case FunctionStatus.BUILTIN then true;
case FunctionStatus.EVALUATED then true;
else false;
end match;
end isEvaluated;
function markEvaluated
input Function fn;
algorithm
if Pointer.access(fn.status) <> FunctionStatus.BUILTIN then
Pointer.update(fn.status, FunctionStatus.EVALUATED);
end if;
end markEvaluated;
function isSimplified
input Function fn;
output Boolean simplified;
algorithm
simplified := match Pointer.access(fn.status)
case FunctionStatus.BUILTIN then true;
case FunctionStatus.SIMPLIFIED then true;
else false;
end match;
end isSimplified;
function markSimplified
input Function fn;
algorithm
if Pointer.access(fn.status) <> FunctionStatus.BUILTIN then
Pointer.update(fn.status, FunctionStatus.SIMPLIFIED);
end if;
end markSimplified;
function isCollected
"Returns true if this function has already been added to the function tree
(or shouldn't be added, e.g. if it's builtin), otherwise false."
input Function fn;
output Boolean collected;
algorithm
collected := match Pointer.access(fn.status)
case FunctionStatus.BUILTIN then true;
case FunctionStatus.COLLECTED then true;
else false;
end match;
end isCollected;
function collect
"Marks this function as collected for addition to the function tree."
input Function fn;
algorithm
// The pointer might be immutable, check before assigning to it.
if Pointer.access(fn.status) <> FunctionStatus.BUILTIN then
Pointer.update(fn.status, FunctionStatus.COLLECTED);
end if;
end collect;
function name
input Function fn;
output Absyn.Path path = fn.path;
end name;
function setName
input Absyn.Path name;
input output Function fn;
algorithm
fn.path := name;
end setName;
function nameConsiderBuiltin "Handles the DAE.mo structure where builtin calls are replaced by their simpler name"
input Function fn;
output Absyn.Path path;
algorithm
path := match fn.attributes.isBuiltin
local
String name;
case DAE.FUNCTION_BUILTIN(name=SOME(name)) then Absyn.IDENT(name);
case DAE.FUNCTION_BUILTIN() then Absyn.pathLast(fn.path);
else fn.path;
end match;
end nameConsiderBuiltin;
function signatureString
"Constructs a signature string for a function, e.g. Real func(Real x, Real y)"
input Function fn;
input Boolean printTypes = true;
output String str;
protected
Absyn.Path fn_name;
String input_str, output_str, var_s;
list<String> inputs_strl = {};
list<InstNode> inputs = fn.inputs;
Component c;
Expression def_exp;
Type ty;
algorithm
for s in fn.slots loop
input_str := "";
c := InstNode.component(listHead(inputs));
inputs := listRest(inputs);
// Add the default expression if it has any.
if isSome(s.default) then
SOME(def_exp) := s.default;
input_str := " = " + Expression.toString(def_exp);
end if;
// Add the name from the slot and not the node, since some builtin
// functions don't bother using proper names for the nodes.
input_str := s.name + input_str;
// Add a $ in front of the name if the parameter only takes positional
// arguments.
input_str := match s.ty
case SlotType.POSITIONAL then "$" + input_str;
else input_str;
end match;
// Add the type if the parameter has been typed.
if printTypes and Component.isTyped(c) then
ty := Component.getType(c);
var_s := Prefixes.unparseVariability(Component.variability(c), ty);
input_str := var_s + Type.toString(ty) + " " + input_str;
end if;
inputs_strl := input_str :: inputs_strl;
end for;
input_str := stringDelimitList(listReverse(inputs_strl), ", ");
output_str := if printTypes and isTyped(fn) then " => " + Type.toString(fn.returnType) else "";
fn_name := nameConsiderBuiltin(fn);
// if isSome(display_name) then Util.getOption(display_name) else fn.path;
str := Absyn.pathString(fn_name) + "(" + input_str + ")" + output_str;
end signatureString;
function candidateFuncListString
input list<Function> fns;
output String s = stringDelimitList(list(Function.signatureString(fn, true) for fn in fns), "\n ");
end candidateFuncListString;
function callString
"Constructs a string representing a call, for use in error messages."
input Function fn;
input list<Expression> posArgs;
input list<NamedArg> namedArgs;
output String str;
algorithm
str := stringDelimitList(list(Expression.toString(arg) for arg in posArgs), ", ");
if not listEmpty(namedArgs) then
str := str + ", " + stringDelimitList(
list(Util.tuple21(arg) + " = " + Expression.toString(Util.tuple22(arg))
for arg in namedArgs), ", ");
end if;
str := Absyn.pathString(fn.path) + "(" + str + ")";
end callString;
function typeString
"Constructs a string representing the type of the function, on the form
function_name<function>(input types) => output type"
input Function fn;
output String str;
algorithm
str := List.toString(fn.inputs, paramTypeString,
Absyn.pathString(name(fn)) + "<function>",
"(", ", ", ") => " + Type.toString(fn.returnType), true);
end typeString;
function paramTypeString
input InstNode param;
output String str = Type.toString(InstNode.getType(param));
end paramTypeString;
function instance
input Function fn;
output InstNode node = fn.node;
end instance;
function returnType
input Function fn;
output Type ty = fn.returnType;
end returnType;
function setReturnType
input Type ty;
input output Function fn;
algorithm
fn.returnType := ty;
end setReturnType;
function getSlots
input Function fn;
output list<Slot> slots = fn.slots;
end getSlots;
function fillArgs
"Matches the given arguments to the slots in a function, and returns the
arguments sorted in the order of the function parameters."
input list<TypedArg> posArgs;
input list<TypedNamedArg> namedArgs;
input Function fn;
input SourceInfo info;
output list<TypedArg> args = posArgs;
output Boolean matching;
protected
Slot slot;
list<Slot> slots, remaining_slots;
list<TypedArg> filled_named_args;
array<Slot> slots_arr;
Integer pos_arg_count, slot_count, index = 1;
algorithm
slots := fn.slots;
pos_arg_count := listLength(posArgs);
slot_count := listLength(slots);
if pos_arg_count > slot_count then
// If we have too many positional arguments it can't possibly match.
matching := false;
return;
elseif pos_arg_count == slot_count and listEmpty(namedArgs) then
// If we have exactly as many positional arguments as slots and no named
// arguments we can just return the list of arguments as it is.
matching := true;
return;
end if;
slots_arr := listArray(slots);
for arg in args loop
slot := slots_arr[index];
if not Slot.positional(slot) then
// Slot doesn't allow positional arguments (used for some builtin functions).
matching := false;
return;
end if;
slot.arg := SOME(arg);
arrayUpdate(slots_arr, index, slot);
index := index + 1;
end for;
for narg in namedArgs loop
(slots_arr, matching) := fillNamedArg(narg, slots_arr, fn, info);
if not matching then
return;
end if;
end for;
(args, matching) := collectArgs(slots_arr, info);
end fillArgs;
function fillNamedArg
"Looks up a slot with the given name and tries to fill it with the given
argument expression."
input TypedNamedArg inArg;
input output array<Slot> slots;
input Function fn "For error reporting";
input SourceInfo info;
output Boolean matching = true;
protected
Slot s;
String argName;
Type ty;
Expression argExp;
Variability var;
algorithm
// Try to find a slot and fill it with the argument expression.
// Positional arguments fill the slots from the start of the array, so
// searching backwards will generally be a bit more efficient.
for i in arrayLength(slots):-1:1 loop
s := slots[i];
(argName, argExp, ty, var) := inArg;
if s.name == argName then
if not Slot.named(s) then
// Slot doesn't allow named argument (used for some builtin functions).
matching := false;
elseif isNone(s.arg) then
s.arg := SOME((argExp,ty,var));
slots[i] := s;
else
// TODO: Improve the error message, should mention function name.
Error.addSourceMessage(Error.FUNCTION_SLOT_ALREADY_FILLED,
{argName, ""}, info);
matching := false;
end if;
return;
end if;
end for;
// No slot could be found.
matching := false;
// A slot with the given name couldn't be found. This means it doesn't
// exist, or we removed it when handling positional argument. We need to
// search through all slots to be sure.
for s in fn.slots loop
if argName == s.name then
// We found a slot, so it must have already been filled.
Error.addSourceMessage(Error.FUNCTION_SLOT_ALREADY_FILLED,
{argName, ""}, info);
return;
end if;
// No slot could be found, so it doesn't exist.
Error.addSourceMessage(Error.NO_SUCH_PARAMETER,
{InstNode.name(instance(fn)), argName}, info);
end for;
end fillNamedArg;
function collectArgs
"Collects the arguments from the given slots."
input array<Slot> slots;
input SourceInfo info;
output list<TypedArg> args = {};
output Boolean matching = true;
protected
Option<Expression> default;
Expression e;
Option<TypedArg> arg;
TypedArg a;
String name;
algorithm
for s in slots loop
SLOT(name = name, default = default, arg = arg) := s;
args := matchcontinue arg
// Use the argument from the call if one was given.
case SOME(a) then a :: args;
// Otherwise, try to fill the slot with its default argument.
case _ then fillDefaultSlot(s, slots, info) :: args;
else
algorithm
matching := false;
then
args;
end matchcontinue;
end for;
args := listReverse(args);
end collectArgs;
function fillDefaultSlot
input Slot slot;
input array<Slot> slots;
input SourceInfo info;
output TypedArg outArg;
algorithm
outArg := match slot
// Slot already filled by function argument.
case SLOT(arg = SOME(outArg)) then outArg;
// Slot not filled by function argument, but has default value.
case SLOT(default = SOME(_))
then fillDefaultSlot2(slot, slots, info);
// Give an error if no argument was given and there's no default argument.
else
algorithm
Error.addSourceMessage(Error.UNFILLED_SLOT, {slot.name}, info);
then
fail();
end match;
end fillDefaultSlot;
function fillDefaultSlot2
input Slot slot;
input array<Slot> slots;
input SourceInfo info;
output TypedArg outArg;
algorithm
outArg := match slot.evalStatus
local
Expression exp;
// An already evaluated slot, return its binding.
case SlotEvalStatus.EVALUATED
then Util.getOption(slot.arg);
// A slot in the process of being evaluated => cyclic bindings.
case SlotEvalStatus.EVALUATING
algorithm
Error.addSourceMessage(Error.CYCLIC_DEFAULT_VALUE, {slot.name}, info);
then
fail();
// A slot with a not evaluated binding, evaluate the binding and return it.
case SlotEvalStatus.NOT_EVALUATED
algorithm
slot.evalStatus := SlotEvalStatus.EVALUATING;
arrayUpdate(slots, slot.index, slot);
exp := evaluateSlotExp(Util.getOption(slot.default), slots, info);
outArg := (exp, Expression.typeOf(exp), Expression.variability(exp));
slot.arg := SOME(outArg);
slot.evalStatus := SlotEvalStatus.EVALUATED;
arrayUpdate(slots, slot.index, slot);
then
outArg;
end match;
end fillDefaultSlot2;
function evaluateSlotExp
input Expression exp;
input array<Slot> slots;
input SourceInfo info;
output Expression outExp;
algorithm
outExp := Expression.map(exp,
function evaluateSlotExp_traverser(slots = slots, info = info));
end evaluateSlotExp;
function evaluateSlotExp_traverser
input Expression exp;
input array<Slot> slots;
input SourceInfo info;
output Expression outExp;
algorithm
outExp := match exp
local
ComponentRef cref;
Option<Slot> slot;
case Expression.CREF(cref = cref as ComponentRef.CREF(restCref = ComponentRef.EMPTY()))
algorithm
slot := lookupSlotInArray(ComponentRef.firstName(cref), slots);
then
if isSome(slot) then Util.tuple31(fillDefaultSlot(Util.getOption(slot), slots, info)) else exp;
else exp;
end match;
end evaluateSlotExp_traverser;
function lookupSlotInArray
input String slotName;
input array<Slot> slots;
output Option<Slot> outSlot;
protected
Slot slot;
algorithm
try
slot := Array.getMemberOnTrue(slotName, slots, Slot.hasName);
outSlot := SOME(slot);
else
outSlot := NONE();
end try;
end lookupSlotInArray;
function matchArgsVectorize
input Function func;
input output list<TypedArg> args;
input SourceInfo info;
output Boolean correct;
output FunctionMatchKind funcMatchKind = EXACT_MATCH;
protected
Component comp;
InstNode inputnode;
list<InstNode> inputs;
Expression argexp, margexp, vect_arg;
Type argty, compty, tmpty, mty;
Variability var;
list<TypedArg> checked_args;
Integer idx;
TypeCheck.MatchKind matchKind;
list<Dimension> argdims, compdims, vectdims, tmpdims, outvectdims;
Boolean has_cast;
list<Boolean> vectorized;
FunctionMatchKind base_mk = EXACT_MATCH;
algorithm
checked_args := {};
idx := 1;
inputs := func.inputs;
outvectdims := {};
vectorized := {};
has_cast := false;
vect_arg := Expression.INTEGER(0);
for arg in args loop
(argexp,argty,var) := arg;
inputnode :: inputs := inputs;
comp := InstNode.component(inputnode);
compty := Component.getType(comp);
compdims := Type.arrayDims(compty);
argdims := Type.arrayDims(argty);
correct := false;
if listLength(argdims) == listLength(compdims) then
// We have unvectorized match. Keep it.
(margexp, mty, matchKind) := TypeCheck.matchTypes(argty, compty, argexp, false);
correct := TypeCheck.isValidArgumentMatch(matchKind);
vectorized := false::vectorized;
elseif listLength(argdims) > listLength(compdims) then
// Try vectorized matching since we have more dims in the actual argument.
(vectdims, tmpdims) := List.split(argdims, listLength(argdims)-listLength(compdims));
// make sure the vectorization dims are consistent.
if listEmpty(outvectdims) then
outvectdims := vectdims;
vect_arg := argexp;
elseif not List.isEqualOnTrue(outvectdims, vectdims, Dimension.isEqual) then
Error.addSourceMessage(Error.VECTORIZE_CALL_DIM_MISMATCH,
{"", Expression.toString(vect_arg), "", Expression.toString(argexp),
Dimension.toStringList(outvectdims), Dimension.toStringList(vectdims)}, info);
fail();
end if;
tmpty := Type.arrayElementType(argty);
if not listEmpty(tmpdims) then
tmpty := Type.ARRAY(tmpty, tmpdims);
end if;
(margexp, mty, matchKind) := TypeCheck.matchTypes(tmpty, compty, argexp, false);
correct := TypeCheck.isValidArgumentMatch(matchKind);
vectorized := true::vectorized;
end if;
// Type mismatch, print an error.
if not correct then
Error.addSourceMessage(Error.ARG_TYPE_MISMATCH, {
intString(idx), Absyn.pathString(func.path), InstNode.name(inputnode), Expression.toString(argexp),
Type.toString(argty), Type.toString(compty)
}, info);
funcMatchKind := NO_MATCH;
return;