forked from OpenModelica/OpenModelica
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NFTyping.mo
3911 lines (3422 loc) · 128 KB
/
NFTyping.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 NFTyping
" file: NFTyping.mo
package: NFTyping
description: NFInst typing.
Functions used by NFInst for typing.
"
import Binding = NFBinding;
import Component = NFComponent;
import NFComponent.ComponentState;
import Dimension = NFDimension;
import Equation = NFEquation;
import Class = NFClass;
import Expression = NFExpression;
import NFInstNode.InstNode;
import NFModifier.Modifier;
import Statement = NFStatement;
import NFType.Type;
import Operator = NFOperator;
import NFPrefixes.{Variability, Purity, ConnectorType};
import Prefixes = NFPrefixes;
import Connector = NFConnector;
import Connection = NFConnection;
import Algorithm = NFAlgorithm;
import Record = NFRecord;
import InstContext = NFInstContext;
protected
import Attributes = NFAttributes;
import Builtin = NFBuiltin;
import BuiltinCall = NFBuiltinCall;
import Ceval = NFCeval;
import ComponentRef = NFComponentRef;
import Origin = NFComponentRef.Origin;
import ExecStat.execStat;
import Lookup = NFLookup;
import MatchKind = NFTypeCheck.MatchKind;
import Call = NFCall;
import NFClassTree.ClassTree;
import Subscript = NFSubscript;
import TypeCheck = NFTypeCheck;
import Types;
import NFSections.Sections;
import List;
import MetaModelica.Dangerous.listReverseInPlace;
import ComplexType = NFComplexType;
import Restriction = NFRestriction;
import NFModifier.ModTable;
import Package = NFPackage;
import NFFunction.Function;
import NFInstNode.CachedData;
import Direction = NFPrefixes.Direction;
import ElementSource;
import System;
import ErrorExt;
import ErrorTypes;
import OperatorOverloading = NFOperatorOverloading;
import Structural = NFStructural;
import Array;
public
uniontype TypingError
record NO_ERROR end NO_ERROR;
record OUT_OF_BOUNDS
Integer upperBound;
end OUT_OF_BOUNDS;
function isError
input TypingError error;
output Boolean isError;
algorithm
isError := match error
case NO_ERROR() then false;
else true;
end match;
end isError;
end TypingError;
// Used by typeDimension for catching cyclic dimension involving :
constant Expression WHOLEDIM_CREF = Expression.CREF(Type.UNKNOWN(), ComponentRef.STRING(":", ComponentRef.EMPTY()));
public
function typeClass
input InstNode cls;
input InstContext.Type context;
protected
InstContext.Type next_context;
algorithm
next_context := InstContext.set(context, NFInstContext.CLASS);
typeClassType(cls, NFBinding.EMPTY_BINDING, next_context, cls);
typeComponents(cls, next_context);
execStat("NFTyping.typeComponents");
typeBindings(cls, next_context);
execStat("NFTyping.typeBindings");
typeClassSections(cls, next_context);
execStat("NFTyping.typeClassSections");
end typeClass;
function typeComponents
input InstNode cls;
input InstContext.Type context;
input Boolean preserveDerived = false;
protected
Class c = InstNode.getClass(cls), c2;
ClassTree cls_tree;
InstNode ext_node, con, de;
algorithm
() := match c
case Class.INSTANCED_CLASS(restriction = Restriction.TYPE()) then ();
case Class.INSTANCED_CLASS(elements = cls_tree as ClassTree.FLAT_TREE())
algorithm
if InstContext.inInstanceAPI(context) then
for c in cls_tree.components loop
typeComponentTry(c, context);
end for;
else
for c in cls_tree.components loop
typeComponent(c, context);
end for;
end if;
() := match c.ty
case Type.COMPLEX(complexTy = ComplexType.RECORD(constructor = con))
algorithm
typeStructor(con);
then
();
else ();
end match;
then
();
// For derived types with dimensions we keep them as they are, because we
// need to preserve the dimensions.
case Class.TYPED_DERIVED()
guard preserveDerived or Type.isArray(c.ty)
algorithm
typeComponents(c.baseClass, context);
then
();
// Derived types without dimensions can be collapsed.
case Class.TYPED_DERIVED()
algorithm
typeComponents(c.baseClass, context);
// Only collapse for the normal instantiation, for the instance API we
// need the derived class chains.
if not InstContext.inInstanceAPI(context) then
c2 := InstNode.getClass(c.baseClass);
c2 := Class.setRestriction(c.restriction, c2);
InstNode.updateClass(c2, cls);
end if;
then
();
case Class.INSTANCED_BUILTIN(ty = Type.COMPLEX(complexTy =
ComplexType.EXTERNAL_OBJECT(constructor = con, destructor = de)))
algorithm
typeStructor(con);
typeStructor(de);
then
();
case Class.INSTANCED_BUILTIN() then ();
else
algorithm
Error.assertion(false, getInstanceName() + " got uninstantiated class " + InstNode.name(cls), sourceInfo());
then
fail();
end match;
end typeComponents;
function typeStructor
input InstNode node;
protected
CachedData cache;
list<Function> fnl;
InstContext.Type context;
algorithm
cache := InstNode.getFuncCache(node);
() := match cache
case CachedData.FUNCTION(funcs = fnl, typed = false)
algorithm
context := InstContext.set(NFInstContext.FUNCTION, NFInstContext.RELAXED);
fnl := list(Function.typeFunction(fn, context) for fn in fnl);
fnl := list(OperatorOverloading.patchOperatorRecordConstructorBinding(fn) for fn in fnl);
InstNode.setFuncCache(node, CachedData.FUNCTION(fnl, true, cache.specialBuiltin));
then
();
else ();
end match;
end typeStructor;
function typeClassType
input InstNode clsNode;
input Binding componentBinding;
input InstContext.Type context;
input InstNode instanceNode;
output Type ty;
protected
Class cls, ty_cls;
InstNode node, ty_node;
Function fn;
Boolean is_expandable;
algorithm
cls := InstNode.getClass(clsNode);
ty := match cls
case Class.INSTANCED_CLASS(restriction = Restriction.CONNECTOR(isExpandable = is_expandable))
algorithm
ty := Type.COMPLEX(clsNode, makeConnectorType(cls.elements, is_expandable));
cls.ty := ty;
InstNode.updateClass(cls, clsNode);
then
ty;
case Class.INSTANCED_CLASS(ty = Type.COMPLEX(cls = ty_node, complexTy = ComplexType.RECORD(constructor = node)))
algorithm
ty := Type.COMPLEX(ty_node, makeRecordType(node));
cls.ty := ty;
InstNode.updateClass(cls, clsNode);
then
ty;
// A long class declaration of a type extending from a type has the type of the base class.
case Class.INSTANCED_CLASS(ty = Type.COMPLEX(complexTy = ComplexType.EXTENDS_TYPE(node)))
algorithm
ty := typeClassType(node, componentBinding, context, instanceNode);
cls.ty := ty;
InstNode.updateClass(cls, clsNode);
then
ty;
// A component of function type, i.e. a functional input parameter.
case Class.INSTANCED_CLASS(restriction = Restriction.FUNCTION())
guard InstNode.isComponent(instanceNode)
algorithm
fn :: _ := Function.typeNodeCache(clsNode);
ty := Type.FUNCTION(fn, NFType.FunctionType.FUNCTIONAL_PARAMETER);
cls.ty := ty;
InstNode.updateClass(cls, clsNode);
then
ty;
case Class.INSTANCED_CLASS() then cls.ty;
case Class.EXPANDED_DERIVED()
algorithm
typeDimensions(cls.dims, clsNode, componentBinding, context, InstNode.info(clsNode));
ty := typeClassType(cls.baseClass, componentBinding, context, instanceNode);
ty := Type.liftArrayLeftList(ty, arrayList(cls.dims));
ty_cls := Class.TYPED_DERIVED(ty, cls.baseClass, cls.restriction);
InstNode.updateClass(ty_cls, clsNode);
then
ty;
case Class.INSTANCED_BUILTIN() then cls.ty;
case Class.TYPED_DERIVED() then cls.ty;
else
algorithm
Error.assertion(false, getInstanceName() + " got noninstantiated class " +
InstNode.name(clsNode), sourceInfo());
then
fail();
end match;
end typeClassType;
function makeConnectorType
input ClassTree ctree;
input Boolean isExpandable;
output ComplexType connectorTy;
protected
list<InstNode> pots = {}, flows = {}, streams = {}, exps = {};
ConnectorType.Type cty;
algorithm
if isExpandable then
for c in ClassTree.enumerateComponents(ctree) loop
cty := Component.connectorType(InstNode.component(InstNode.resolveInner(c)));
if intBitAnd(cty, ConnectorType.EXPANDABLE) > 0 then
exps := c :: exps;
else
pots := c :: pots;
end if;
end for;
connectorTy := ComplexType.EXPANDABLE_CONNECTOR(pots, exps);
else
for c in ClassTree.enumerateComponents(ctree) loop
cty := Component.connectorType(InstNode.component(InstNode.resolveInner(c)));
if intBitAnd(cty, ConnectorType.FLOW) > 0 then
flows := c :: flows;
elseif intBitAnd(cty, ConnectorType.STREAM) > 0 then
streams := c :: streams;
elseif intBitAnd(cty, ConnectorType.POTENTIAL) > 0 then
pots := c :: pots;
else
Error.addInternalError("Invalid connector type on component " + InstNode.name(c), InstNode.info(c));
fail();
end if;
end for;
connectorTy := ComplexType.CONNECTOR(pots, flows, streams);
if not listEmpty(streams) then
System.setHasStreamConnectors(true);
end if;
end if;
end makeConnectorType;
function checkConnectorTypeBalance
input InstNode component;
protected
Integer pots, flows, streams;
Boolean known_size;
Component comp;
InstNode parent;
algorithm
comp := InstNode.component(component);
if not ConnectorType.isConnector(Component.connectorType(comp)) then
return;
end if;
parent := InstNode.instanceParent(component);
if InstNode.isComponent(parent) and Component.isConnector(InstNode.component(parent)) then
return;
end if;
(pots, flows, streams, known_size) := Component.countConnectorVars(comp);
if not known_size then
return;
end if;
// Modelica 3.2 section 9.3.1:
// For each non-partial connector class the number of flow variables shall
// be equal to the number of variables that are neither parameter, constant,
// input, output, stream nor flow.
if pots <> flows and not Flags.isConfigFlagSet(Flags.ALLOW_NON_STANDARD_MODELICA, "unbalancedModel") then
Error.addStrictMessage(Error.UNBALANCED_CONNECTOR,
{InstNode.name(component), String(pots), String(flows)}, InstNode.info(component));
end if;
// Modelica 3.2 section 15.1:
// A stream connector must have exactly one scalar variable with the flow prefix.
if streams > 0 and flows <> 1 then
Error.addSourceMessage(Error.MISMATCHED_FLOW_IN_STREAM_CONNECTOR,
{InstNode.name(component), String(flows)}, InstNode.info(component));
fail();
end if;
end checkConnectorTypeBalance;
function makeRecordType
input InstNode constructor;
output ComplexType recordTy;
protected
CachedData cache;
Function fn;
array<Record.Field> fields;
UnorderedMap<String, Integer> indexMap;
algorithm
cache := InstNode.getFuncCache(constructor);
recordTy := match cache
case CachedData.FUNCTION(funcs = fn :: _)
algorithm
(fields, indexMap) := Record.collectRecordFields(fn.node);
then
ComplexType.RECORD(constructor, fields, indexMap);
else
algorithm
Error.assertion(false, getInstanceName() +
" got record type without constructor", sourceInfo());
then
fail();
end match;
end makeRecordType;
function typeComponent
input InstNode component;
input InstContext.Type context;
input Boolean typeChildren = true;
output Type ty;
protected
InstNode node = InstNode.resolveOuter(component);
Component c = InstNode.component(node);
Expression cond;
Boolean is_deleted;
array<Dimension> dims;
algorithm
if InstNode.isOnlyOuter(component) then
return;
end if;
ty := match c
// An untyped component, type it.
case Component.COMPONENT(ty = Type.UNTYPED(dimensions = dims))
algorithm
// Type the component's dimensions.
typeDimensions(dims, node, c.binding, context, c.info);
// Construct the type of the component and update the node with it.
if InstNode.isEmpty(c.classInst) then
ty := Type.UNKNOWN();
else
ty := typeClassType(c.classInst, c.binding, context, component);
end if;
ty := Type.liftArrayLeftList(ty, arrayList(dims));
if Binding.isBound(c.condition) then
c.condition := typeComponentCondition(c.condition, context, evaluate = true);
is_deleted := Expression.isFalse(Binding.getExp(c.condition));
else
is_deleted := false;
end if;
if typeChildren then
c.ty := ty;
c.state := ComponentState.Typed;
InstNode.updateComponent(c, node);
if not is_deleted and not InstNode.isEmpty(c.classInst) then
// Check that flow/stream variables are Real.
checkComponentStreamAttribute(c.attributes.connectorType, ty, component);
// Type the component's children.
typeComponents(c.classInst, context);
checkConnectorTypeBalance(node);
end if;
end if;
then
ty;
// A component that has already been typed, skip it.
case Component.COMPONENT() then c.ty;
case Component.ITERATOR() then c.ty;
case Component.ENUM_LITERAL(literal = Expression.ENUM_LITERAL(ty = ty)) then ty;
case Component.INVALID_COMPONENT() then Component.getType(c);
// Any other type of component shouldn't show up here.
else
algorithm
Error.assertion(false, getInstanceName() + " got noninstantiated component " + InstNode.name(component), sourceInfo());
then
fail();
end match;
end typeComponent;
function typeComponentTry
input InstNode componentNode;
input InstContext.Type context;
protected
Component comp;
algorithm
ErrorExt.setCheckpoint(getInstanceName());
try
typeComponent(componentNode, context);
else
comp := InstNode.component(componentNode);
comp := Component.INVALID_COMPONENT(comp, ErrorExt.printCheckpointMessagesStr());
InstNode.updateComponent(comp, componentNode);
end try;
ErrorExt.delCheckpoint(getInstanceName());
end typeComponentTry;
function checkComponentStreamAttribute
input ConnectorType.Type cty;
input Type ty;
input InstNode component;
protected
Type ety;
algorithm
if ConnectorType.isFlowOrStream(cty) then
ety := Type.arrayElementType(ty);
if not (Type.isReal(ety) or Type.isComplex(ety)) then
Error.addSourceMessageAndFail(Error.NON_REAL_FLOW_OR_STREAM,
{ConnectorType.toString(cty), InstNode.name(component)}, InstNode.info(component));
end if;
end if;
end checkComponentStreamAttribute;
function typeIterator
input InstNode iterator;
input Expression range;
input InstContext.Type context;
input Boolean structural "If the iteration range must be a parameter expression or not.";
output Expression outRange;
output Type ty;
output Variability var;
output Purity purity;
protected
Component c = InstNode.component(iterator);
Expression exp;
SourceInfo info;
algorithm
(outRange, ty, var) := match c
case Component.ITERATOR(info = info)
algorithm
(exp, ty, var, purity) := typeExp(range, InstContext.set(context, NFInstContext.ITERATION_RANGE), info);
// If the iteration range is structural, it must be a parameter expression.
if structural and var > Variability.PARAMETER then
Error.addSourceMessageAndFail(Error.NON_PARAMETER_ITERATOR_RANGE,
{Expression.toString(exp)}, info);
end if;
// The iteration range must be a vector expression.
if not Type.isVector(ty) then
Error.addSourceMessageAndFail(Error.FOR_EXPRESSION_TYPE_ERROR,
{Expression.toString(exp), Type.toString(ty)}, info);
end if;
// The type of the iterator is the element type of the range expression.
c := Component.ITERATOR(Type.arrayElementType(ty), var, info);
InstNode.updateComponent(c, iterator);
then
(exp, ty, var);
else
algorithm
Error.assertion(false, getInstanceName() + " got non-iterator " + InstNode.name(iterator), sourceInfo());
then
fail();
end match;
end typeIterator;
function typeDimensions
input output array<Dimension> dimensions;
input InstNode component;
input Binding binding;
input InstContext.Type context;
input SourceInfo info;
algorithm
for i in 1:arrayLength(dimensions) loop
typeDimension(dimensions, i, component, binding, context, info);
end for;
end typeDimensions;
function typeDimension
input array<Dimension> dimensions;
input Integer index;
input InstNode component;
input Binding binding;
input InstContext.Type context;
input SourceInfo info;
output Dimension dimension = dimensions[index];
algorithm
dimension := match dimension
local
Expression exp, dim_exp;
Option<Expression> oexp;
Variability var;
Dimension dim;
Binding b;
Type ty;
TypingError ty_err;
Integer parent_dims, dim_index;
Boolean evaluated;
// A dimension that we're already trying to type.
case Dimension.UNTYPED(isProcessing = true)
algorithm
if InstContext.inFunction(context) then
// If we are in a functions we allow e.g. size expression of unknown dimensions.
dim := Dimension.UNKNOWN();
arrayUpdate(dimensions, index, dim);
else
// Otherwise leave the dimension as it is, which is sometimes fine if
// the dimension isn't used or generates an error in typeCrefDim.
dim := dimension;
end if;
then
dim;
// If the dimension is not typed, type it.
case Dimension.UNTYPED()
algorithm
arrayUpdate(dimensions, index, Dimension.UNTYPED(dimension.dimension, true));
(exp, ty, var) := typeExp(dimension.dimension, InstContext.set(context, NFInstContext.DIMENSION), info);
TypeCheck.checkDimensionType(exp, ty, info);
evaluated := true;
if not InstContext.inFunction(context) then
// Dimensions must be parameter expressions in a non-function class.
if var <= Variability.PARAMETER then
if InstContext.inRelaxed(context) then
exp := Ceval.tryEvalExp(exp);
evaluated := Expression.isLiteral(exp);
else
exp := Ceval.evalExp(exp, Ceval.EvalTarget.DIMENSION(component, index, exp, info));
end if;
else
Error.addSourceMessage(Error.DIMENSION_NOT_KNOWN, {Expression.toString(exp)}, info);
fail();
end if;
else
// For functions, only evaluate constant and structural parameter expressions.
if var <= Variability.STRUCTURAL_PARAMETER and
not Expression.contains(exp, Expression.isFunctionInputCref) then
exp := Ceval.tryEvalExp(exp);
end if;
end if;
exp := subscriptDimExp(exp, component);
dim := Dimension.fromExp(exp, var);
arrayUpdate(dimensions, index, dim);
then
dim;
// Dimensions in a function can be flexible (non-input component with no
// binding) or determined by the call arguments (input component), keep the
// dimension unknown for these cases.
case Dimension.UNKNOWN() guard InstContext.inFunction(context) and
((Binding.isUnbound(binding) and InstNode.isOutput(component)) or
not InstNode.isOutput(component))
then dimension;
// A dimension of a function output parameter that depends on e.g. an input
// can't be determined here, leave it unknown and let the call typing handle it.
// TODO: This assumes any binding that contains crefs can't be evaluated to
// avoid e.g. using the default value of an input parameter, but some
// cases such as an output dimension depending on another output
// dimension could be fine.
case Dimension.UNKNOWN() guard InstContext.inFunction(context) and
Binding.hasExp(binding) and
Expression.contains(Binding.getExp(binding), Expression.isCref)
then dimension;
// If the dimension is unknown in a class, try to infer it from the components binding.
case Dimension.UNKNOWN()
algorithm
b := binding;
parent_dims := 0;
// Update the dimension as processing, using a : cref to get the correct
// error message if there are cycles.
arrayUpdate(dimensions, index, Dimension.UNTYPED(WHOLEDIM_CREF, true));
if Binding.isUnbound(binding) then
// If the component has no binding, try to use its parent's binding
// (i.e. for record fields where the record instance has a binding).
(b, parent_dims) := getRecordElementBinding(component, context);
if Binding.isUnbound(b) then
// If the component still doesn't have a binding, try to use the start attribute instead.
// TODO: Any attribute should actually be fine to use here.
parent_dims := 0;
b := Class.lookupAttributeBinding("start", InstNode.getClass(component));
b := Binding.mapExp(b, function Expression.filterSplitIndices(node = component));
end if;
end if;
(dim, ty_err) := match b
// Print an error if there's no binding.
case Binding.UNBOUND()
guard not InstContext.inRelaxed(context)
algorithm
Error.addSourceMessage(Error.FAILURE_TO_DEDUCE_DIMS_NO_MOD,
{String(index), InstNode.name(component)}, info);
then
fail();
case Binding.UNTYPED_BINDING()
then deduceDimensionFromExp(b.bindingExp, NONE(), index, parent_dims, component, context, info);
case Binding.TYPED_BINDING()
then deduceDimensionFromExp(b.bindingExp, SOME(b.bindingType), index, parent_dims, component, context, info);
else (dimension, TypingError.NO_ERROR());
end match;
() := match ty_err
case TypingError.OUT_OF_BOUNDS()
guard not InstContext.inRelaxed(context)
algorithm
Error.addSourceMessage(Error.DIMENSION_DEDUCTION_FROM_BINDING_FAILURE,
{String(index), InstNode.name(component), Binding.toString(b)}, info);
then
fail();
else ();
end match;
// Make sure the dimension is constant evaluated, and also mark it as structural.
dim := match dim
case Dimension.EXP(exp = exp)
algorithm
Structural.markExp(exp);
if InstContext.inRelaxed(context) then
exp := Ceval.tryEvalExp(exp);
else
exp := Ceval.evalExp(exp, Ceval.EvalTarget.DIMENSION(component, index, exp, info));
end if;
exp := subscriptDimExp(exp, component);
then
Dimension.fromExp(exp, dim.var);
case Dimension.UNKNOWN()
guard not InstContext.inRelaxed(context)
algorithm
Error.addInternalError(getInstanceName() + " returned unknown dimension in a non-function context", info);
then
fail();
else dim;
end match;
arrayUpdate(dimensions, index, dim);
then
dim;
// Other kinds of dimensions are already typed.
else dimension;
end match;
end typeDimension;
function deduceDimensionFromExp
input Expression exp;
input Option<Type> ty;
input Integer index;
input Integer parentDims;
input InstNode component;
input InstContext.Type context;
input SourceInfo info;
output Dimension dim;
output TypingError error;
protected
Option<Expression> oe;
Expression e;
Integer dim_index;
algorithm
// If the binding expression comes from a parent of the component rather than
// the component iself the dimension index needs to be offset by the number of
// dimensions of the parent(s).
dim_index := index + parentDims;
if isSome(ty) then
// If the type is known, take the dimension directly from it.
(dim, error) := nthDimensionBoundsChecked(Util.getOption(ty), dim_index);
oe := NONE();
else
// If the type is unknown, try to type the expression only as much as is
// needed to get the dimension we're looking for.
(dim, oe, error) := typeExpDim(exp, dim_index,
InstContext.set(context, NFInstContext.DIMENSION), info);
end if;
// If the deduced dimension is unknown, evaluate the binding and try again.
if Dimension.isUnknown(dim) and not TypingError.isError(error) then
// Use the typed expression from typeExpDim if it was returned.
e := if isSome(oe) then Util.getOption(oe) else exp;
if InstContext.inRelaxed(context) then
e := Ceval.tryEvalExp(e);
else
e := Ceval.evalExp(e, Ceval.EvalTarget.DIMENSION(component, index, e, info));
end if;
(dim, error) := nthDimensionBoundsChecked(Expression.typeOf(e), dim_index);
end if;
end deduceDimensionFromExp;
function subscriptDimExp
"Tries to fix dimension expressions that are lacking subscripts after having
been evaluated."
input output Expression dimExp;
input InstNode component;
protected
Integer exp_dims, parent_dims;
InstNode parent;
list<Subscript> subs;
algorithm
exp_dims := Expression.dimensionCount(dimExp);
if exp_dims == 0 then
// If the expression is a scalar like it should we don't need to do anything.
return;
end if;
// If the expression has too many dimensions, add split subscripts based on
// the component's parent's dimensions until we get a scalar expression.
subs := {};
parent := InstNode.instanceParent(component);
while exp_dims > 0 and not InstNode.isEmpty(parent) loop
parent_dims := InstNode.dimensionCount(parent);
for i in parent_dims:-1:1 loop
subs := Subscript.makeSplitIndex(parent, i) :: subs;
exp_dims := exp_dims - 1;
if exp_dims == 0 then
break;
end if;
end for;
parent := InstNode.instanceParent(parent);
end while;
dimExp := Expression.applySubscripts(subs, dimExp);
end subscriptDimExp;
function simplifyDimExp
input output Expression dimExp;
protected
Expression exp;
algorithm
dimExp := match dimExp
case Expression.ARRAY()
guard Expression.arrayAllEqual(dimExp)
then Expression.arrayFirstScalar(dimExp);
case Expression.SUBSCRIPTED_EXP(split = true)
guard Expression.isArray(dimExp.exp) and Expression.arrayAllEqual(dimExp.exp)
then Expression.arrayFirstScalar(dimExp.exp);
else dimExp;
end match;
end simplifyDimExp;
function makeDimension
input Expression dimExp;
input Expression unevaledExp;
input Variability variability;
output Dimension outDimension;
protected
Expression exp = dimExp;
algorithm
if Expression.isArray(exp) then
if Expression.arrayAllEqual(exp) then
exp := Expression.arrayFirstScalar(exp);
else
end if;
end if;
outDimension := Dimension.fromExp(exp, variability);
end makeDimension;
function getRecordElementBinding
"Tries to fetch the binding for a given record field by using the binding of
the record instance."
input InstNode component;
input InstContext.Type context;
output Binding binding;
output Integer parentDims = 0;
protected
InstNode parent;
Component comp;
Expression exp;
Binding parent_binding;
algorithm
parent := InstNode.instanceParent(component);
if InstNode.isComponent(parent) then
// Get the binding of the component's parent.
comp := InstNode.component(parent);
parent_binding := Component.getBinding(comp);
if Binding.isUnbound(parent_binding) then
// If the parent has no binding, try the parent's parent.
(binding, parentDims) := getRecordElementBinding(parent, context);
else
// Otherwise type the binding, so we can safely look up the field name.
binding := typeBinding(parent_binding, InstContext.set(context, NFInstContext.DIMENSION));
// If the binding wasn't typed before, update the parent component with it
// so we don't have to type it again.
if not referenceEq(parent_binding, binding) then
InstNode.componentApply(parent, Component.setBinding, binding);
end if;
end if;
parentDims := parentDims + Component.dimensionCount(comp);
// If we found a binding, get the binding for the field from it.
if Binding.isBound(binding) then
binding := Binding.recordFieldBinding(component, binding);
end if;
else
binding := NFBinding.EMPTY_BINDING;
end if;
end getRecordElementBinding;
function typeBindings
input InstNode cls;
input InstContext.Type context;
protected
Class c;
ClassTree cls_tree;
InstNode node;
algorithm
c := InstNode.getClass(cls);
() := match c
case Class.INSTANCED_CLASS(elements = cls_tree as ClassTree.FLAT_TREE())
algorithm
for c in cls_tree.components loop
typeComponentBinding(c, context);
end for;
then
();
case Class.INSTANCED_BUILTIN(elements = cls_tree as ClassTree.FLAT_TREE())
algorithm
for c in cls_tree.components loop
typeComponentBinding(c, context);
end for;
then
();
case Class.INSTANCED_BUILTIN() then ();
case Class.TYPED_DERIVED()
algorithm
typeBindings(c.baseClass, context);
then
();
else
algorithm
Error.assertion(false, getInstanceName() + " got uninstantiated class " + InstNode.name(cls), sourceInfo());
then
fail();
end match;
end typeBindings;
function typeComponentBinding
input InstNode component;
input InstContext.Type context;
input Boolean typeChildren = true;
protected
InstNode node = InstNode.resolveOuter(component);
Component c;
Binding binding;
InstNode cls;
MatchKind matchKind;
String name;
Variability comp_var, comp_eff_var, bind_var, bind_eff_var;
Attributes attrs;
Type ty;
algorithm
c := InstNode.component(node);
if InstNode.isOnlyOuter(component) then
return;
end if;