/
Inst.mo
5589 lines (5012 loc) · 232 KB
/
Inst.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 Inst
" file: Inst.mo
package: Inst
description: Model instantiation
This module is responsible for instantiation of Modelica models.
The instantation is the process of instantiating model components,
flattening inheritance and generating equations from connect statements.
The instantiation process takes Modelica AST as defined in SCode and
produces variables and equations and algorithms, etc. as defined in DAE.
This module uses Lookup to lookup classes and variables from the
environment defined in Env. It uses Connect for generating equations from
connect statements. The type system defined in Types is used for
variable instantiation and type. DAE.Mod is used for modifiers and
merging of modifiers.
The extends language feature is performed by InstExtends. Instantiation of
algorithm sections and equation sections (including connections) is done
by InstSection.
There are basically four different ways/granularities of instantiation.
1. Using partialInstClassIn which only instantiates class definitions.
This function is used for looking up class definitions in e.g. packages.
For example, if looking up the class A.B.C, a new scope is opened and
A is partially instantiated in that scope using partialInstClassIn.
2. Function implicit instantiation. is the last argument of type bool to
instClassIn. It is needed since instantiation of functions is needed
to generate code for functions and there are cases where such
instantiations differ
from standard function instantiation. For example
function foo
input Real x{:};
...
end foo;
should be possible to instantiate even though the dimension size of x is
not known.
3. Implicit instantiation controlled by the next last argument to
instClassIn.
This is also needed, when a DAE should not be generated.
It is not clear when this is needed, perhaps it can be removed in the
future.
4. ???"
// public imports
public import Absyn;
public import ClassInf;
public import Connect;
public import ConnectionGraph;
public import DAE;
public import FCore;
public import InnerOuter;
public import InstTypes;
public import Mod;
public import Prefix;
public import SCode;
public import UnitAbsyn;
// **
// These type aliases are introduced to make the code a little more readable.
// **
protected type Ident = DAE.Ident "an identifier";
protected type InstanceHierarchy = InnerOuter.InstHierarchy "an instance hierarchy";
protected type InstDims = list<list<DAE.Dimension>>
"Changed from list<Subscript> to list<list<Subscript>>. One list for each scope.
This so when instantiating classes extending from primitive types can collect the dimension of -one- surrounding scope to create type.
E.g. RealInput p[3]; gives the list {3} for this scope and other lists for outer (in instance hierachy) scopes";
protected partial function BasicTypeAttrTyper
input String inAttrName;
input DAE.Type inClassType;
input SourceInfo inInfo;
output DAE.Type outType;
end BasicTypeAttrTyper;
// protected imports
protected
import BaseHashTable;
import Builtin;
import Ceval;
import ConnectUtil;
import ComponentReference;
import Config;
import DAEUtil;
import Debug;
import Dump;
import ElementSource;
import Error;
import ErrorExt;
import ExecStat;
import Expression;
import ExpressionDump;
import Flags;
import FGraph;
import FGraphBuildEnv;
import FNode;
import GC;
import Global;
import HashTable;
import HashTable5;
import InstSection;
import InstBinding;
import InstVar;
import InstFunction;
import InstUtil;
import InstExtends;
import List;
import Lookup;
import MetaUtil;
import OperatorOverloading;
import PrefixUtil;
import SCodeUtil;
import StringUtil;
import Static;
import Types;
import UnitParserExt;
import Util;
import Values;
import ValuesUtil;
import System;
import SCodeDump;
import UnitAbsynBuilder;
import InstStateMachineUtil;
import NFUnitCheck;
import DAEDump; // BTH
protected function instantiateClass_dispatch
" instantiate a class.
if this function fails with stack overflow, it will be caught in the caller"
input FCore.Cache inCache;
input InnerOuter.InstHierarchy inIH;
input SCode.Program inProgram;
input SCode.Path inPath;
input Boolean doSCodeDep "Do SCode dependency (if the debug flag is also enabled)";
output FCore.Cache outCache;
output FCore.Graph outEnv;
output InnerOuter.InstHierarchy outIH;
output DAE.DAElist outDAElist;
algorithm
(outCache,outEnv,outIH,outDAElist) := match (inCache,inIH,inProgram,inPath)
local
Absyn.Path path;
FCore.Graph env,env_1,env_2;
DAE.DAElist dae1,dae,dae2;
list<SCode.Element> cdecls;
String name2,n,pathstr,name;
SCode.Element cdef;
FCore.Cache cache;
InstanceHierarchy ih;
ConnectionGraph.ConnectionGraph graph;
DAE.ElementSource source "the origin of the element";
list<DAE.Element> daeElts;
Option<SCode.Comment> cmt;
// top level class
case (cache,ih,(cdecls as (_ :: _)),(path as Absyn.IDENT()))
equation
cache = FCore.setCacheClassName(cache,path);
if doSCodeDep then
cdecls = InstUtil.scodeFlatten(cdecls, inPath);
ExecStat.execStat("FrontEnd - scodeFlatten");
end if;
(cache,env) = Builtin.initialGraph(cache);
env_1 = FGraphBuildEnv.mkProgramGraph(cdecls, FCore.USERDEFINED(), env);
// set the source of this element
source = ElementSource.addElementSourcePartOfOpt(DAE.emptyElementSource, FGraph.getScopePath(env));
if Flags.isSet(Flags.GC_PROF) then
print(GC.profStatsStr(GC.getProfStats(), head="GC stats after pre-frontend work (building graphs):") + "\n");
end if;
ExecStat.execStat("FrontEnd - mkProgramGraph");
(cache,env_2,ih,dae2) = instClassInProgram(cache, env_1, ih, cdecls, path, source);
// check the models for balancing
//Debug.fcall2(Flags.CHECK_MODEL_BALANCE, checkModelBalancing, SOME(path), dae1);
//Debug.fcall2(Flags.CHECK_MODEL_BALANCE, checkModelBalancing, SOME(path), dae2);
// let the GC collect these as they are used only by Inst!
releaseInstHashTable();
then
(cache,env_2,ih,dae2);
// class in package
case (cache,ih,(cdecls as (_ :: _)),(path as Absyn.QUALIFIED()))
equation
cache = FCore.setCacheClassName(cache,path);
if doSCodeDep then
cdecls = InstUtil.scodeFlatten(cdecls, inPath);
ExecStat.execStat("FrontEnd - scodeFlatten");
end if;
pathstr = Absyn.pathString(path);
//System.startTimer();
//print("\nBuiltinMaking");
(cache,env) = Builtin.initialGraph(cache);
//System.stopTimer();
//print("\nBuiltinMaking: " + realString(System.getTimerIntervalTime()));
//System.startTimer();
//print("\nInstClassDecls");
env_1 = FGraphBuildEnv.mkProgramGraph(cdecls, FCore.USERDEFINED(), env);
//System.stopTimer();
//print("\nInstClassDecls: " + realString(System.getTimerIntervalTime()));
//System.startTimer();
//print("\nLookupClass");
(cache,(cdef as SCode.CLASS(name = n)),env_2) = Lookup.lookupClass(cache, env_1, path, SOME(Absyn.dummyInfo));
//System.stopTimer();
//print("\nLookupClass: " + realString(System.getTimerIntervalTime()));
//System.startTimer();
//print("\nInstClass");
if Flags.isSet(Flags.GC_PROF) then
print(GC.profStatsStr(GC.getProfStats(), head="GC stats after pre-frontend work (building graphs):") + "\n");
end if;
ExecStat.execStat("FrontEnd - mkProgramGraph");
(cache,env_2,ih,_,dae,_,_,_,_,_) = instClass(cache,env_2,ih,
UnitAbsynBuilder.emptyInstStore(),DAE.NOMOD(), makeTopComponentPrefix(env_2, n), cdef,
{}, false, InstTypes.TOP_CALL(), ConnectionGraph.EMPTY, Connect.emptySet) "impl";
//System.stopTimer();
//print("\nInstClass: " + realString(System.getTimerIntervalTime()));
//System.startTimer();
//print("\nReEvaluateIf");
//print(" ********************** backpatch 1 **********************\n");
dae = InstUtil.reEvaluateInitialIfEqns(cache,env_2,dae,true);
//System.stopTimer();
//print("\nReEvaluateIf: " + realString(System.getTimerIntervalTime()));
// check the model for balancing
// Debug.fcall2(Flags.CHECK_MODEL_BALANCE, checkModelBalancing, SOME(path), dae);
//System.startTimer();
//print("\nSetSource+DAE");
// set the source of this element
source = ElementSource.addElementSourcePartOfOpt(DAE.emptyElementSource, FGraph.getScopePath(env));
daeElts = DAEUtil.daeElements(dae);
cmt = SCode.getElementComment(cdef);
dae = DAE.DAE({DAE.COMP(pathstr,daeElts,source,cmt)});
//System.stopTimer();
//print("\nSetSource+DAE: " + realString(System.getTimerIntervalTime()));
// let the GC collect these as they are used only by Inst!
releaseInstHashTable();
then
(cache, env_2, ih, dae);
end match;
end instantiateClass_dispatch;
public function instantiateClass
"To enable interactive instantiation, an arbitrary class in the program
needs to be possible to instantiate. This function performs the same
action as instProgram, but given a specific class to instantiate.
First, all the class definitions are added to the environment without
modifications, and then the specified class is instantiated in the
function instClassInProgram"
input FCore.Cache inCache;
input InnerOuter.InstHierarchy inIH;
input SCode.Program inProgram;
input SCode.Path inPath;
input Boolean doSCodeDep=true "Do SCode dependency (if the debug flag is also enabled)";
output FCore.Cache outCache;
output FCore.Graph outEnv;
output InnerOuter.InstHierarchy outIH;
output DAE.DAElist outDAElist;
algorithm
(outCache,outEnv,outIH,outDAElist) := matchcontinue (inCache,inIH,inProgram,inPath)
local
Absyn.Path cr,path;
list<SCode.Element> cdecls;
String cname_str;
FCore.Cache cache;
InstanceHierarchy ih;
Boolean stackOverflow;
case (_,_,{},_)
equation
Error.addMessage(Error.NO_CLASSES_LOADED, {});
then
fail();
// instantiate a class
case (cache,ih,cdecls as _::_,path)
equation
(outCache,outEnv,outIH,outDAElist) = instantiateClass_dispatch(cache,ih,cdecls,path,doSCodeDep);
if Flags.isSet(Flags.NF_UNITCHECK) then
NFUnitCheck.unitChecking(outDAElist,outCache);
end if;
then
(outCache,outEnv,outIH,outDAElist);
// error instantiating
case (_,_,_::_,path)
equation
// if we got a stack overflow remove the stack-overflow flag
// adrpo: NOTE THAT THE NEXT FUNCTION CALL MUST BE THE FIRST IN THIS CASE, otherwise the stack overflow will not be caught!
stackOverflow = setStackOverflowSignal(false);
cname_str = Absyn.pathString(path) + (if stackOverflow then ". The compiler got into Stack Overflow!" else "");
if not Config.getGraphicsExpMode() then
Error.addMessage(Error.ERROR_FLATTENING, {cname_str});
end if;
// let the GC collect these as they are used only by Inst!
releaseInstHashTable();
then
fail();
end matchcontinue;
end instantiateClass;
public function instantiatePartialClass
"Author: BZ, 2009-07
This is a function for instantiating partial 'top' classes.
It does so by converting the partial class into a non partial class.
Currently used by: MathCore.modelEquations, CevalScript.checkModel"
input FCore.Cache inCache;
input InnerOuter.InstHierarchy inIH;
input SCode.Program inProgram;
input SCode.Path inPath;
output FCore.Cache outCache;
output FCore.Graph outEnv;
output InnerOuter.InstHierarchy outIH;
output DAE.DAElist outDAElist;
algorithm
(outCache,outEnv,outIH,outDAElist) := matchcontinue (inCache,inIH,inProgram,inPath)
local
Absyn.Path cr,path;
FCore.Graph env,env_1,env_2;
DAE.DAElist dae1,dae;
list<SCode.Element> cdecls;
String name2,n,pathstr,name,cname_str;
SCode.Element cdef;
FCore.Cache cache;
InstanceHierarchy ih;
DAE.ElementSource source "the origin of the element";
list<DAE.Element> daeElts;
DAE.FunctionTree funcs;
Option<SCode.Comment> cmt;
case (_,_,{},_)
equation
Error.addMessage(Error.NO_CLASSES_LOADED, {});
then
fail();
case (cache,ih,(cdecls as (_ :: _)),(path as Absyn.IDENT())) /* top level class */
equation
(cache,env) = Builtin.initialGraph(cache);
env_1 = FGraphBuildEnv.mkProgramGraph(cdecls, FCore.USERDEFINED(), env);
cdecls = List.map1(cdecls,SCode.classSetPartial,SCode.NOT_PARTIAL());
source = ElementSource.addElementSourcePartOfOpt(DAE.emptyElementSource, FGraph.getScopePath(env));
(cache,env_2,ih,dae) = instClassInProgram(cache, env_1, ih, cdecls, path, source);
then
(cache,env_2,ih,dae);
case (cache,ih,(cdecls as (_ :: _)),(path as Absyn.QUALIFIED())) /* class in package */
equation
(cache,env) = Builtin.initialGraph(cache);
env_1 = FGraphBuildEnv.mkProgramGraph(cdecls, FCore.USERDEFINED(), env);
(cache,(cdef as SCode.CLASS(name = n)),env_2) = Lookup.lookupClass(cache,env_1, path, SOME(Absyn.dummyInfo));
cdef = SCode.classSetPartial(cdef, SCode.NOT_PARTIAL());
(cache,env_2,ih,_,dae,_,_,_,_,_) =
instClass(cache, env_2, ih, UnitAbsynBuilder.emptyInstStore(),DAE.NOMOD(), makeTopComponentPrefix(env_2, n),
cdef, {}, false, InstTypes.TOP_CALL(), ConnectionGraph.EMPTY, Connect.emptySet) "impl" ;
pathstr = Absyn.pathString(path);
// set the source of this element
source = ElementSource.addElementSourcePartOfOpt(DAE.emptyElementSource, FGraph.getScopePath(env));
daeElts = DAEUtil.daeElements(dae);
cmt = SCode.getElementComment(cdef);
dae = DAE.DAE({DAE.COMP(pathstr,daeElts,source,cmt)});
then
(cache,env_2,ih,dae);
case (_,_,_,path) /* error instantiating */
guard not Config.getGraphicsExpMode()
equation
cname_str = Absyn.pathString(path);
//print(" Error flattening partial, errors: " + ErrorExt.printMessagesStr() + "\n");
Error.addMessage(Error.ERROR_FLATTENING, {cname_str});
then
fail();
end matchcontinue;
end instantiatePartialClass;
protected function makeTopComponentPrefix
input FGraph.Graph inGraph;
input Absyn.Ident inName;
output Prefix.Prefix outPrefix;
protected
Absyn.Path p;
algorithm
//p := FGraph.joinScopePath(inGraph, Absyn.IDENT(inName));
//outPrefix := Prefix.PREFIX(Prefix.PRE("$i", {}, {}, Prefix.NOCOMPPRE(), ClassInf.MODEL(p)), Prefix.CLASSPRE(SCode.VAR()));
outPrefix := Prefix.NOPRE();
end makeTopComponentPrefix;
protected function instClassInProgram
"Instantiates a specific top level class in a Program."
input FCore.Cache inCache;
input FCore.Graph inEnv;
input InnerOuter.InstHierarchy inIH;
input SCode.Program inProgram;
input SCode.Path inPath;
input DAE.ElementSource inSource;
output FCore.Cache outCache;
output FCore.Graph outEnv;
output InnerOuter.InstHierarchy outIH;
output DAE.DAElist outDae;
algorithm
(outCache, outEnv, outIH, outDae) :=
matchcontinue(inCache, inEnv, inIH, inProgram, inPath, inSource)
local
String name;
SCode.Element cls;
FCore.Cache cache;
FCore.Graph env;
InstanceHierarchy ih;
DAE.DAElist dae;
list<DAE.Element> elts;
Option<SCode.Comment> cmt;
case (_, _, _, {}, _, _)
then (inCache, inEnv, inIH, DAE.emptyDae);
case (_, _, _, _, Absyn.IDENT(name = ""), _)
then (inCache, inEnv, inIH, DAE.emptyDae);
case (_, _, _, _, Absyn.IDENT(name = name), _)
equation
cls = InstUtil.lookupTopLevelClass(name, inProgram, true);
(cache, env, ih, _, dae, _, _, _, _, _) = instClass(inCache, inEnv,
inIH, UnitAbsynBuilder.emptyInstStore(), DAE.NOMOD(), makeTopComponentPrefix(inEnv, name),
cls, {}, false, InstTypes.TOP_CALL(), ConnectionGraph.EMPTY, Connect.emptySet);
dae = InstUtil.reEvaluateInitialIfEqns(cache, env, dae, true);
elts = DAEUtil.daeElements(dae);
cmt = SCode.getElementComment(cls);
dae = DAE.DAE({DAE.COMP(name, elts, inSource, cmt)});
then
(cache, env, ih, dae);
else
equation
true = Flags.isSet(Flags.FAILTRACE);
Debug.trace("Inst.instClassInProgram failed\n");
then
fail();
end matchcontinue;
end instClassInProgram;
public function instClass
"Instantiation of a class can be either implicit or normal.
This function is used in both cases. When implicit instantiation
is performed, the last argument is true, otherwise it is false.
Instantiating a class consists of the following steps:
o Create a new frame on the environment
o Initialize the class inference state machine
o Instantiate all the elements and equations
o Generate equations from the connection sets built during instantiation"
input FCore.Cache inCache;
input FCore.Graph inEnv;
input InnerOuter.InstHierarchy inIH;
input UnitAbsyn.InstStore inStore;
input DAE.Mod inMod;
input Prefix.Prefix inPrefix;
input SCode.Element inClass;
input list<list<DAE.Dimension>> inInstDims;
input Boolean inBoolean;
input InstTypes.CallingScope inCallingScope;
input ConnectionGraph.ConnectionGraph inGraph;
input Connect.Sets inSets;
output FCore.Cache cache;
output FCore.Graph outEnv;
output InnerOuter.InstHierarchy outIH;
output UnitAbsyn.InstStore outStore;
output DAE.DAElist outDae;
output Connect.Sets outSets;
output DAE.Type outType;
output ClassInf.State outState;
output Option<SCode.Attributes> optDerAttr;
output ConnectionGraph.ConnectionGraph outGraph;
algorithm
(cache,outEnv,outIH,outStore,outDae,outSets,outType,outState,optDerAttr,outGraph):=
matchcontinue (inCache,inEnv,inIH,inStore,inMod,inPrefix,inClass,inInstDims,inBoolean,inCallingScope,inGraph,inSets)
local
FCore.Graph env,env_1,env_3;
DAE.Mod mod;
Prefix.Prefix pre;
Connect.Sets csets;
String n,scopeName,strDepth;
Boolean impl,callscope_1,isFn,notIsPartial,isPartialFn,recursionDepthReached;
SCode.Partial partialPrefix;
SCode.Encapsulated encflag;
ClassInf.State ci_state,ci_state_1;
DAE.DAElist dae1,dae1_1,dae;
list<DAE.Var> tys;
Option<DAE.Type> bc_ty;
Absyn.Path fq_class;
DAE.Type ty;
SCode.Element c;
SCode.Restriction r;
InstDims inst_dims;
InstTypes.CallingScope callscope;
Option<SCode.Attributes> oDA;
ConnectionGraph.ConnectionGraph graph;
InstanceHierarchy ih;
DAE.EqualityConstraint equalityConstraint;
SourceInfo info;
UnitAbsyn.InstStore store;
// adrpo: ONLY when running checkModel we should be able to instantiate partial classes
case (cache,_,_,store,_,_,
SCode.CLASS(name=n, partialPrefix = SCode.PARTIAL(), restriction = r, info = info),
_,_,_,_,_)
equation
true = Flags.getConfigBool(Flags.CHECK_MODEL);
false = SCode.isFunctionRestriction(r); // Partial functions are handled below (used for partially evaluated functions; do not want the checkModel warning)
c = SCode.setClassPartialPrefix(SCode.NOT_PARTIAL(), inClass);
// add a warning
if not Config.getGraphicsExpMode() then
Error.addSourceMessage(Error.INST_PARTIAL_CLASS_CHECK_MODEL_WARNING, {n}, info);
end if;
// call normal instantiation
(cache,env,ih,store,dae,csets,ty,ci_state_1,oDA,graph) =
instClass(inCache, inEnv, inIH, store, inMod, inPrefix, c, inInstDims, inBoolean, inCallingScope, inGraph, inSets);
then
(cache,env,ih,store,dae,csets,ty,ci_state_1,oDA,graph);
// Instantiation of a class. Create new scope and call instClassIn.
// Then generate equations from connects.
case (cache,env,ih,store,mod,pre,
(c as SCode.CLASS(name = n,encapsulatedPrefix = encflag,restriction = r, partialPrefix = partialPrefix, info = info)),
inst_dims,impl,callscope,graph,_)
equation
recursionDepthReached = listLength(FGraph.currentScope(env)) < Global.recursionDepthLimit;
if not recursionDepthReached then
scopeName = FGraph.printGraphPathStr(env);
strDepth = intString(Global.recursionDepthLimit);
Error.addSourceMessage(Error.RECURSION_DEPTH_REACHED,{strDepth, scopeName},info);
fail();
end if;
//print("---- CLASS: "); print(n);print(" ----\n"); print(SCodeDump.printClassStr(c)); //Print out the input SCode class
//str = SCodeDump.printClassStr(c); print("------------------- CLASS instClass-----------------\n");print(str);print("\n===============================================\n");
// First check if the class is non-partial or a partial function
isFn = SCode.isFunctionRestriction(r);
notIsPartial = not SCode.partialBool(partialPrefix);
isPartialFn = isFn and SCode.partialBool(partialPrefix);
true = notIsPartial or isPartialFn;
env_1 = FGraph.openScope(env, encflag, n, FGraph.restrictionToScopeType(r));
ci_state = ClassInf.start(r,FGraph.getGraphName(env_1));
csets = ConnectUtil.newSet(pre, inSets);
(cache,env_3,ih,store,dae1,csets,ci_state_1,tys,bc_ty,oDA,equalityConstraint, graph)
= instClassIn(cache, env_1, ih, store, mod, pre, ci_state, c, SCode.PUBLIC(), inst_dims, impl, callscope, graph, csets, NONE());
csets = ConnectUtil.addSet(inSets, csets);
(cache,fq_class) = makeFullyQualifiedIdent(cache, env, n);
// is top level?
callscope_1 = InstUtil.isTopCall(callscope);
dae1_1 = DAEUtil.addComponentType(dae1, fq_class);
InstUtil.reportUnitConsistency(callscope_1,store);
(csets, _, graph) = InnerOuter.retrieveOuterConnections(cache,env_3,ih,pre,csets,callscope_1, graph);
//System.startTimer();
//print("\nConnect equations and the OverConstrained graph in one step");
dae = ConnectUtil.equations(callscope_1, csets, dae1_1, graph, Absyn.pathString(Absyn.makeNotFullyQualified(fq_class)));
//System.stopTimer();
//print("\nConnect and Overconstrained: " + realString(System.getTimerIntervalTime()) + "\n");
ty = InstUtil.mktype(fq_class, ci_state_1, tys, bc_ty, equalityConstraint, c);
dae = InstUtil.updateDeducedUnits(callscope_1,store,dae);
// Fixes partial functions.
ty = InstUtil.fixInstClassType(ty,isPartialFn);
// env_3 = FGraph.updateScope(env_3);
then
(cache,env_3,ih,store,dae,csets,ty,ci_state_1,oDA,graph);
// Classes with the keyword partial can not be instantiated. They can only be inherited
case (cache,_,_,_,_,_,SCode.CLASS(name = n,partialPrefix = SCode.PARTIAL(), info = info),_,(false),_,_,_)
equation
if not Config.getGraphicsExpMode() then
Error.addSourceMessage(Error.INST_PARTIAL_CLASS, {n}, info);
end if;
then
fail();
case (_,env,_,_,_,_,SCode.CLASS(name = n),_,_,_,_,_)
equation
true = Flags.isSet(Flags.FAILTRACE);
Debug.trace("- Inst.instClass: " + n + " in env: " + FGraph.printGraphPathStr(env) + " failed\n");
then
fail();
end matchcontinue;
end instClass;
protected function instClassBasictype
"author: PA
This function instantiates a basictype class, e.g. Real, Integer, Real[2],
etc. This function has the same functionality as instClass except that
it will create array types when needed. (instClass never creates array
types). This is needed because this function is used to instantiate classes
extending from basic types. See instBasictypeBaseclass.
NOTE: This function should only be called from instBasictypeBaseclass.
This is new functionality in Modelica v 2.2."
input FCore.Cache inCache;
input FCore.Graph inEnv;
input InnerOuter.InstHierarchy inIH;
input UnitAbsyn.InstStore inStore;
input DAE.Mod inMod;
input Prefix.Prefix inPrefix;
input SCode.Element inClass;
input list<list<DAE.Dimension>> inInstDims;
input Boolean inImplicit;
input InstTypes.CallingScope inCallingScope;
input Connect.Sets inSets;
output FCore.Cache outCache;
output FCore.Graph outEnv;
output InnerOuter.InstHierarchy outIH;
output UnitAbsyn.InstStore outStore;
output DAE.DAElist outDae;
output Connect.Sets outSets;
output DAE.Type outType;
output list<DAE.Var> outTypeVars "attributes of builtin types";
output ClassInf.State outState;
algorithm
(outCache,outEnv,outIH,outStore,outDae,outSets,outType,outTypeVars,outState):=
match (inCache,inEnv,inIH,inStore,inMod,inPrefix,inClass,inInstDims,inImplicit,inCallingScope,inSets)
local
FCore.Graph env_1,env_3,env;
ClassInf.State ci_state,ci_state_1;
SCode.Element c_1,c;
DAE.DAElist dae1,dae1_1,dae;
Connect.Sets csets;
list<DAE.Var> tys;
Option<DAE.Type> bc_ty;
Absyn.Path fq_class;
SCode.Encapsulated encflag;
Boolean impl;
DAE.Type ty;
DAE.Mod mod;
Prefix.Prefix pre;
String n;
SCode.Restriction r;
InstDims inst_dims;
InstTypes.CallingScope callscope;
FCore.Cache cache;
InstanceHierarchy ih;
UnitAbsyn.InstStore store;
case (cache,env,ih,store,mod,pre,(c as SCode.CLASS(name = n,encapsulatedPrefix = encflag,restriction = r)),inst_dims,impl,_,_) /* impl */
equation
env_1 = FGraph.openScope(env, encflag, n, FGraph.restrictionToScopeType(r));
ci_state = ClassInf.start(r, FGraph.getGraphName(env_1));
c_1 = SCode.classSetPartial(c, SCode.NOT_PARTIAL());
(cache,env_3,ih,store,dae1,csets,ci_state_1,tys,bc_ty,_,_,_)
= instClassIn(cache, env_1, ih, store, mod, pre, ci_state, c_1, SCode.PUBLIC(), inst_dims, impl, InstTypes.INNER_CALL(), ConnectionGraph.EMPTY, inSets, NONE());
(cache,fq_class) = makeFullyQualifiedIdent(cache,env_3, n);
dae1_1 = DAEUtil.addComponentType(dae1, fq_class);
dae = dae1_1;
ty = InstUtil.mktypeWithArrays(fq_class, ci_state_1, tys, bc_ty, c);
then
(cache,env_3,ih,store,dae,csets,ty,tys,ci_state_1);
case (_,_,_,_,_,_,SCode.CLASS(),_,_,_,_)
equation
//fprintln(Flags.FAILTRACE, "- Inst.instClassBasictype: " + n + " failed");
then
fail();
end match;
end instClassBasictype;
public function instClassIn "
This rule instantiates the contents of a class definition, with a new
environment already setup.
The *implicitInstantiation* boolean indicates if the class should be
instantiated implicit, i.e. without generating DAE.
The last option is a even stronger indication of implicit instantiation,
used when looking up variables in packages. This must be used because
generation of functions in implicit instanitation (according to
*implicitInstantiation* boolean) can cause circular dependencies
(e.g. if a function uses a constant in its body)"
input FCore.Cache inCache;
input FCore.Graph inEnv;
input InnerOuter.InstHierarchy inIH;
input UnitAbsyn.InstStore inStore;
input DAE.Mod inMod;
input Prefix.Prefix inPrefix;
input ClassInf.State inState;
input SCode.Element inClass;
input SCode.Visibility inVisibility;
input list<list<DAE.Dimension>> inInstDims;
input Boolean implicitInstantiation;
input InstTypes.CallingScope inCallingScope;
input ConnectionGraph.ConnectionGraph inGraph;
input Connect.Sets inSets;
input Option<DAE.ComponentRef> instSingleCref;
output FCore.Cache outCache;
output FCore.Graph outEnv;
output InnerOuter.InstHierarchy outIH;
output UnitAbsyn.InstStore outStore;
output DAE.DAElist outDae;
output Connect.Sets outSets;
output ClassInf.State outState;
output list<DAE.Var> outVars;
output Option<DAE.Type> outType;
output Option<SCode.Attributes> optDerAttr;
output DAE.EqualityConstraint outEqualityConstraint;
output ConnectionGraph.ConnectionGraph outGraph;
algorithm
(outCache,outEnv,outIH,outStore,outDae,outSets,outState,outVars,outType,optDerAttr,outEqualityConstraint,outGraph):=
matchcontinue inClass
local
Option<DAE.Type> bc;
FCore.Graph env;
ClassInf.State ci_state;
SCode.Element c;
SCode.Restriction r;
String n;
DAE.DAElist dae;
Connect.Sets csets;
list<DAE.Var> tys;
FCore.Cache cache;
Option<SCode.Attributes> oDA;
DAE.EqualityConstraint equalityConstraint;
ConnectionGraph.ConnectionGraph graph;
InstanceHierarchy ih;
String s1, s2;
UnitAbsyn.InstStore store;
Absyn.InnerOuter io;
SourceInfo info;
SCode.Encapsulated encflag;
// if the class is no outer: regular, or inner
case SCode.CLASS(prefixes = SCode.PREFIXES(innerOuter = io))
equation
true = boolOr(Absyn.isNotInnerOuter(io), Absyn.isOnlyInner(io));
(cache,env,ih,store,ci_state,graph,csets,dae,tys,bc,oDA,equalityConstraint) =
instClassIn2(inCache,inEnv,inIH,inStore,inMod,inPrefix,inState,inClass,inVisibility,inInstDims,implicitInstantiation,inCallingScope,inGraph,inSets,instSingleCref);
then
(cache,env,ih,store,dae,csets,ci_state,tys,bc,oDA,equalityConstraint,graph);
// if the class is inner or innerouter and an instance, use the original name and original scope
case SCode.CLASS(name = n, restriction=r, encapsulatedPrefix = encflag, prefixes = SCode.PREFIXES(innerOuter = io))
equation
true = boolOr(Absyn.isInnerOuter(io), Absyn.isOnlyOuter(io));
FCore.CL(status = FCore.CLS_INSTANCE(n)) = FNode.refData(FGraph.lastScopeRef(inEnv));
(env, _) = FGraph.stripLastScopeRef(inEnv);
env = FGraph.openScope(env, encflag, n, FGraph.restrictionToScopeType(r));
ci_state = ClassInf.start(r,FGraph.getGraphName(env));
// lookup in IH
InnerOuter.INST_INNER(innerElement = SOME(c)) =
InnerOuter.lookupInnerVar(inCache, env, inIH, inPrefix, n, io);
(cache,env,ih,store,ci_state,graph,csets,dae,tys,bc,oDA,equalityConstraint) =
instClassIn2(inCache,env,inIH,inStore,inMod,inPrefix,ci_state,c,inVisibility,inInstDims,implicitInstantiation,inCallingScope,inGraph,inSets,instSingleCref);
then
(cache,env,ih,store,dae,csets,ci_state,tys,bc,oDA,equalityConstraint,graph);
// if the class is inner or innerouter we need to instantiate the inner!
case SCode.CLASS(name = n, prefixes = SCode.PREFIXES(innerOuter = io))
equation
true = boolOr(Absyn.isInnerOuter(io), Absyn.isOnlyOuter(io));
n = FGraph.getInstanceOriginalName(inEnv, n);
// lookup in IH
InnerOuter.INST_INNER(innerElement = SOME(c)) =
InnerOuter.lookupInnerVar(inCache, inEnv, inIH, inPrefix, n, io);
(cache,env,ih,store,ci_state,graph,csets,dae,tys,bc,oDA,equalityConstraint) =
instClassIn2(inCache,inEnv,inIH,inStore,inMod,inPrefix,inState,c,inVisibility,inInstDims,implicitInstantiation,inCallingScope,inGraph,inSets,instSingleCref);
then
(cache,env,ih,store,dae,csets,ci_state,tys,bc,oDA,equalityConstraint,graph);
// we could not find the inner, use the outer as it is!
case SCode.CLASS(name = n, prefixes = SCode.PREFIXES(innerOuter = io), info = info)
equation
true = boolOr(Absyn.isInnerOuter(io), Absyn.isOnlyOuter(io));
if not Config.getGraphicsExpMode() then
s1 = n;
s2 = Dump.unparseInnerouterStr(io);
Error.addSourceMessage(Error.MISSING_INNER_CLASS,{s1, s2}, info);
end if;
(cache,env,ih,store,ci_state,graph,csets,dae,tys,bc,oDA,equalityConstraint) =
instClassIn2(inCache,inEnv,inIH,inStore,inMod,inPrefix,inState,inClass,inVisibility,inInstDims,implicitInstantiation,inCallingScope,inGraph,inSets,instSingleCref);
then
(cache,env,ih,store,dae,csets,ci_state,tys,bc,oDA,equalityConstraint,graph);
end matchcontinue;
end instClassIn;
public function instClassIn2
"This rule instantiates the contents of a class definition, with a new
environment already setup.
The *implicitInstantiation* boolean indicates if the class should be
instantiated implicit, i.e. without generating DAE.
The last option is a even stronger indication of implicit instantiation,
used when looking up variables in packages. This must be used because
generation of functions in implicit instanitation (according to
*implicitInstantiation* boolean) can cause circular dependencies
(e.g. if a function uses a constant in its body)"
input output FCore.Cache cache;
input output FCore.Graph env;
input output InnerOuter.InstHierarchy ih;
input output UnitAbsyn.InstStore store;
input DAE.Mod mod;
input Prefix.Prefix prefix;
input output ClassInf.State state;
input SCode.Element cls;
input SCode.Visibility visibility;
input list<list<DAE.Dimension>> instDims;
input Boolean implicitInst;
input InstTypes.CallingScope callingScope;
input output ConnectionGraph.ConnectionGraph graph;
input output Connect.Sets sets;
input Option<DAE.ComponentRef> instSingleCref;
output DAE.DAElist dae;
output list<DAE.Var> vars;
output Option<DAE.Type> ty;
output Option<SCode.Attributes> optDerAttr;
output DAE.EqualityConstraint equalityConstraint;
protected
Absyn.Path cache_path;
InstHashTable inst_hash;
CachedInstItemInputs inputs;
CachedInstItemOutputs outputs;
tuple<InstDims, Boolean, DAE.Mod, Connect.Sets, ClassInf.State, SCode.Element, Option<DAE.ComponentRef>> bbx, bby;
DAE.Mod m;
Prefix.Prefix pre;
Connect.Sets csets;
ClassInf.State st;
SCode.Element e;
InstDims dims;
Boolean impl;
Option<DAE.ComponentRef> scr;
InstTypes.CallingScope cs;
ConnectionGraph.ConnectionGraph cached_graph;
algorithm
// Packages derived from partial packages should do partialInstClass, since it
// filters out a lot of things.
if SCode.isPackage(cls) and SCode.isPartial(cls) then
(cache, env, ih, state) := partialInstClassIn(cache, env, ih, mod, prefix,
state, cls, visibility, instDims, 0);
dae := DAE.emptyDae;
vars := {};
ty := NONE();
optDerAttr := NONE();
equalityConstraint := NONE();
return;
end if;
cache_path := generateCachePath(env, cls, prefix, callingScope);
// See if we have it in the cache.
if Flags.isSet(Flags.CACHE) then
inst_hash := getGlobalRoot(Global.instHashIndex);
try
{SOME(FUNC_instClassIn(inputs, outputs)), _} := BaseHashTable.get(cache_path, inst_hash);
(m, pre, csets, st, e as SCode.CLASS(), dims, impl, scr, cs) := inputs;
// Are the important inputs the same?
InstUtil.prefixEqualUnlessBasicType(prefix, pre, cls);
if (valueEq(dims,instDims) and (impl==implicitInst) and valueEq(m, mod) and valueEq(csets, sets) and valueEq(st, state) and valueEq(e, cls) and valueEq(scr, instSingleCref) and callingScopeCacheEq(cs, callingScope)) then
(env, dae, sets, state, vars, ty, optDerAttr, equalityConstraint, cached_graph) := outputs;
graph := ConnectionGraph.merge(graph, cached_graph);
showCacheInfo("Full Inst Hit: ", cache_path);
return;
end if;
else
// Not found in cache, continue.
end try;
end if;
// If not found in the cache, instantiate the class and add it to the cache.
try
inputs := (mod, prefix, sets, state, cls, instDims, implicitInst, instSingleCref, callingScope);
(cache, env, ih, store, dae, sets, state, vars, ty, optDerAttr, equalityConstraint, graph) :=
instClassIn_dispatch(cache, env, ih, store, mod, prefix, state, cls,
visibility, instDims, implicitInst, callingScope, graph, sets, instSingleCref);
outputs := (env, dae, sets, state, vars, ty, optDerAttr, equalityConstraint, graph);
showCacheInfo("Full Inst Add: ", cache_path);
addToInstCache(cache_path, SOME(FUNC_instClassIn(inputs, outputs)), NONE());
else
true := Flags.isSet(Flags.FAILTRACE);
Debug.traceln("- Inst.instClassIn2 failed on class: " + SCode.elementName(cls) +
" in environment: " + FGraph.printGraphPathStr(env));
fail();
end try;
end instClassIn2;
protected function callingScopeCacheEq
input InstTypes.CallingScope inCallingScope1;
input InstTypes.CallingScope inCallingScope2;
output Boolean outIsEq;
algorithm
outIsEq := match(inCallingScope1, inCallingScope2)
case (InstTypes.TYPE_CALL(), InstTypes.TYPE_CALL()) then true;
case (InstTypes.TYPE_CALL(), _) then false;
case (_, InstTypes.TYPE_CALL()) then false;
else true;
end match;
end callingScopeCacheEq;
public function instClassIn_dispatch
"This rule instantiates the contents of a class definition, with a new
environment already setup.
The *implicitInstantiation* boolean indicates if the class should be
instantiated implicit, i.e. without generating DAE.
The last option is a even stronger indication of implicit instantiation,
used when looking up variables in packages. This must be used because
generation of functions in implicit instanitation (according to
*implicitInstantiation* boolean) can cause circular dependencies
(e.g. if a function uses a constant in its body)"
input FCore.Cache inCache;
input FCore.Graph inEnv;
input InnerOuter.InstHierarchy inIH;
input UnitAbsyn.InstStore inStore;
input DAE.Mod inMod;
input Prefix.Prefix inPrefix;
input ClassInf.State inState;
input SCode.Element inClass;
input SCode.Visibility inVisibility;
input list<list<DAE.Dimension>> inInstDims;
input Boolean implicitInstantiation;
input InstTypes.CallingScope inCallingScope;
input ConnectionGraph.ConnectionGraph inGraph;
input Connect.Sets inSets;
input Option<DAE.ComponentRef> instSingleCref;
output FCore.Cache outCache;
output FCore.Graph outEnv;
output InnerOuter.InstHierarchy outIH;
output UnitAbsyn.InstStore outStore;
output DAE.DAElist outDae;
output Connect.Sets outSets;
output ClassInf.State outState;
output list<DAE.Var> outTypesVarLst;
output Option<DAE.Type> outTypesTypeOption;