-
Notifications
You must be signed in to change notification settings - Fork 298
/
NFInst.mo
3590 lines (3131 loc) · 117 KB
/
NFInst.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 NFInst
" file: NFInst.mo
package: NFInst
description: Instantiation
New instantiation, enable with -d=newInst.
"
import Absyn;
import AbsynUtil;
import SCode;
import DAE;
import Builtin = NFBuiltin;
import Binding = NFBinding;
import Component = NFComponent;
import ComponentRef = NFComponentRef;
import Dimension = NFDimension;
import Expression = NFExpression;
import Class = NFClass;
import NFInstNode.InstNode;
import NFInstNode.InstNodeType;
import NFModifier.Modifier;
import NFModifier.ModifierScope;
import Operator = NFOperator;
import Equation = NFEquation;
import Statement = NFStatement;
import Type = NFType;
import Subscript = NFSubscript;
import Connector = NFConnector;
import Connection = NFConnection;
import Algorithm = NFAlgorithm;
import ExpOrigin = NFTyping.ExpOrigin;
protected
import Array;
import Error;
import FlagsUtil;
import Flatten = NFFlatten;
import InstUtil = NFInstUtil;
import List;
import Lookup = NFLookup;
import MetaModelica.Dangerous;
import Typing = NFTyping;
import ExecStat.{execStat,execStatReset};
import SCodeDump;
import SCodeUtil;
import System;
import Call = NFCall;
import Absyn.Path;
import NFClassTree.ClassTree;
import NFSections.Sections;
import NFInstNode.CachedData;
import NFInstNode.NodeTree;
import UnitCheck = NFUnitCheck;
import NFPrefixes.*;
import Prefixes = NFPrefixes;
import NFFlatten.FunctionTree;
import ConvertDAE = NFConvertDAE;
import Scalarize = NFScalarize;
import Restriction = NFRestriction;
import ComplexType = NFComplexType;
import Package = NFPackage;
import NFFunction.Function;
import FlatModel = NFFlatModel;
import ElementSource;
import SimplifyModel = NFSimplifyModel;
import Record = NFRecord;
import Variable = NFVariable;
import OperatorOverloading = NFOperatorOverloading;
import EvalConstants = NFEvalConstants;
import VerifyModel = NFVerifyModel;
import Structural = NFStructural;
public
function instClassInProgram
"Instantiates a class given by its fully qualified path, with the result being
a DAE."
input Absyn.Path classPath;
input SCode.Program program;
input Boolean dumpFlat = false;
output FlatModel flatModel;
output FunctionTree functions;
output String flatString "The flat model as a string if dumpFlat = true.";
protected
InstNode top, cls, inst_cls;
String name;
algorithm
// gather here all the flags to disable expansion
// and scalarization if -d=-nfScalarize is on
if not Flags.isSet(Flags.NF_SCALARIZE) then
// make sure we don't expand anything
FlagsUtil.set(Flags.NF_EXPAND_OPERATIONS, false);
FlagsUtil.set(Flags.NF_EXPAND_FUNC_ARGS, false);
end if;
System.setUsesCardinality(false);
System.setHasOverconstrainedConnectors(false);
System.setHasStreamConnectors(false);
// Create a root node from the given top-level classes.
top := makeTopNode(program);
name := AbsynUtil.pathString(classPath);
// Look up the class to instantiate and mark it as the root class.
cls := Lookup.lookupClassName(classPath, top, AbsynUtil.dummyInfo, checkAccessViolations = false);
cls := InstNode.setNodeType(InstNodeType.ROOT_CLASS(InstNode.EMPTY_NODE()), cls);
// Initialize the storage for automatically generated inner elements.
top := InstNode.setInnerOuterCache(top, CachedData.TOP_SCOPE(NodeTree.new(), cls));
// Instantiate the class.
inst_cls := instantiate(cls, instPartial = Flags.getConfigBool(Flags.CHECK_MODEL));
checkPartialClass(cls);
insertGeneratedInners(inst_cls, top);
execStat("NFInst.instantiate(" + name + ")");
// Instantiate expressions (i.e. anything that can contains crefs, like
// bindings, dimensions, etc). This is done as a separate step after
// instantiation to make sure that lookup is able to find the correct nodes.
instExpressions(inst_cls);
execStat("NFInst.instExpressions");
// Mark structural parameters.
updateImplicitVariability(inst_cls, Flags.isSet(Flags.EVAL_PARAM));
execStat("NFInst.updateImplicitVariability");
// Type the class.
Typing.typeClass(inst_cls);
// Flatten the model and evaluate constants in it.
flatModel := Flatten.flatten(inst_cls, name);
flatModel := EvalConstants.evaluate(flatModel);
// Do unit checking
flatModel := UnitCheck.checkUnits(flatModel);
// Apply simplifications to the model.
flatModel := SimplifyModel.simplify(flatModel);
// Collect a tree of all functions that are still used in the flat model.
functions := Flatten.collectFunctions(flatModel);
// Collect package constants that couldn't be substituted with their values
// (e.g. because they where used with non-constant subscripts), and add them
// to the model.
flatModel := Package.collectConstants(flatModel, functions);
// Dump the flat model to a stream if dumpFlat = true.
flatString := if dumpFlat then
FlatModel.toFlatString(flatModel, FunctionTree.listValues(functions)) else "";
// Scalarize array components in the flat model.
if Flags.isSet(Flags.NF_SCALARIZE) then
flatModel := Scalarize.scalarize(flatModel);
else
// Remove empty arrays from variables
flatModel.variables := List.filterOnFalse(flatModel.variables, Variable.isEmptyArray);
end if;
VerifyModel.verify(flatModel);
if Flags.isSet(Flags.NF_DUMP_FLAT) then
print("FlatModel:\n" + FlatModel.toString(flatModel) + "\n");
end if;
end instClassInProgram;
function instantiate
input output InstNode node;
input InstNode parent = InstNode.EMPTY_NODE();
input Boolean instPartial = false "Whether to instantiate a partial class or not.";
algorithm
node := expand(node);
if instPartial or not InstNode.isPartial(node) then
node := instClass(node, Modifier.NOMOD(), NFComponent.DEFAULT_ATTR, true, 0, parent);
end if;
end instantiate;
function expand
input output InstNode node;
algorithm
node := partialInstClass(node);
node := expandClass(node);
end expand;
function makeTopNode
"Creates an instance node from the given list of top-level classes."
input list<SCode.Element> topClasses;
output InstNode topNode;
protected
SCode.Element cls_elem;
Class cls;
ClassTree elems;
algorithm
// Create a fake SCode.Element for the top scope, so we don't have to make the
// definition in InstNode an Option only because of this node.
cls_elem := SCode.CLASS("<top>", SCode.defaultPrefixes, SCode.NOT_ENCAPSULATED(),
SCode.NOT_PARTIAL(), SCode.R_PACKAGE(),
SCode.PARTS(topClasses, {}, {}, {}, {}, {}, {}, NONE()),
SCode.COMMENT(NONE(), NONE()), AbsynUtil.dummyInfo);
// Make an InstNode for the top scope, to use as the parent of the top level elements.
topNode := InstNode.newClass(cls_elem, InstNode.EMPTY_NODE(), InstNodeType.TOP_SCOPE());
// Create a new class from the elements, and update the inst node with it.
cls := Class.fromSCode(topClasses, false, topNode, NFClass.DEFAULT_PREFIXES);
// The class needs to be expanded to allow lookup in it. The top scope will
// only contain classes, so we can do this instead of the whole expandClass.
cls := Class.initExpandedClass(cls);
// Set the correct InstNodeType for classes with builtin annotation. This
// could also be done when creating InstNodes, but only top-level classes
// should have this annotation anyway.
elems := Class.classTree(cls);
ClassTree.mapClasses(elems, markBuiltinTypeNodes);
cls := Class.setClassTree(elems, cls);
topNode := InstNode.updateClass(cls, topNode);
end makeTopNode;
function markBuiltinTypeNodes
input output InstNode node;
algorithm
if SCodeUtil.hasBooleanNamedAnnotationInClass(InstNode.definition(node), "__OpenModelica_builtin") then
node := InstNode.setNodeType(InstNodeType.BUILTIN_CLASS(), node);
end if;
end markBuiltinTypeNodes;
function partialInstClass
input output InstNode node;
protected
Class c;
algorithm
() := match InstNode.getClass(node)
case Class.NOT_INSTANTIATED()
algorithm
c := partialInstClass2(InstNode.definition(node), node);
node := InstNode.updateClass(c, node);
then
();
else ();
end match;
end partialInstClass;
function partialInstClass2
input SCode.Element definition;
input InstNode scope;
output Class cls;
protected
SCode.ClassDef cdef, ce_cdef;
Type ty;
Class.Prefixes prefs;
algorithm
Error.assertion(SCodeUtil.elementIsClass(definition), getInstanceName() + " got non-class element", sourceInfo());
SCode.CLASS(classDef = cdef) := definition;
prefs := instClassPrefixes(definition);
cls := match cdef
// A long class definition, add its elements to a new scope.
case SCode.PARTS()
then Class.fromSCode(cdef.elementLst, false, scope, prefs);
// A class extends, add its elements to a new scope.
case SCode.CLASS_EXTENDS(composition = ce_cdef as SCode.PARTS())
algorithm
// Give a warning if the class extends is not declared as a redeclare.
// This was not clarified until Modelica 3.4, so for now we just treat
// all class extends like redeclares and give a warning about it.
if not SCodeUtil.isElementRedeclare(definition) then
Error.addSourceMessage(Error.CLASS_EXTENDS_MISSING_REDECLARE,
{SCodeUtil.elementName(definition)}, SCodeUtil.elementInfo(definition));
end if;
then
Class.fromSCode(ce_cdef.elementLst, true, scope, prefs);
// An enumeration definition, add the literals to a new scope.
case SCode.ENUMERATION()
algorithm
ty := makeEnumerationType(cdef.enumLst, scope);
then
Class.fromEnumeration(cdef.enumLst, ty, prefs, scope);
else Class.PARTIAL_CLASS(NFClassTree.EMPTY, Modifier.NOMOD(), prefs);
end match;
end partialInstClass2;
function instClassPrefixes
input SCode.Element cls;
output Class.Prefixes prefixes;
protected
SCode.Prefixes prefs;
algorithm
prefixes := match cls
case SCode.CLASS(
encapsulatedPrefix = SCode.Encapsulated.NOT_ENCAPSULATED(),
partialPrefix = SCode.Partial.NOT_PARTIAL(),
prefixes = SCode.Prefixes.PREFIXES(
finalPrefix = SCode.Final.NOT_FINAL(),
innerOuter = Absyn.InnerOuter.NOT_INNER_OUTER(),
replaceablePrefix = SCode.NOT_REPLACEABLE()))
then NFClass.DEFAULT_PREFIXES;
case SCode.CLASS(prefixes = prefs)
then Class.Prefixes.PREFIXES(
cls.encapsulatedPrefix,
cls.partialPrefix,
prefs.finalPrefix,
prefs.innerOuter,
prefs.replaceablePrefix);
end match;
end instClassPrefixes;
function makeEnumerationType
input list<SCode.Enum> literals;
input InstNode scope;
output Type ty;
protected
list<String> lits;
Absyn.Path path;
algorithm
path := InstNode.scopePath(scope);
lits := list(e.literal for e in literals);
ty := Type.ENUMERATION(path, lits);
end makeEnumerationType;
function expandClass
input output InstNode node;
algorithm
node := match InstNode.getClass(node)
case Class.PARTIAL_CLASS() then expandClass2(node);
else node;
end match;
end expandClass;
function expandClass2
input output InstNode node;
protected
SCode.Element def = InstNode.definition(node);
SCode.ClassDef cdef;
SourceInfo info;
algorithm
SCode.CLASS(classDef = cdef, info = info) := def;
node := match cdef
case SCode.PARTS() then expandClassParts(def, node, info);
case SCode.CLASS_EXTENDS() then expandClassParts(def, node, info);
// A short class definition, e.g. class A = B.
case SCode.DERIVED() then expandClassDerived(def, cdef, node, info);
else
algorithm
Error.assertion(false, getInstanceName() + " got unknown class:\n" + SCodeDump.unparseElementStr(def), sourceInfo());
then
fail();
end match;
end expandClass2;
function expandClassParts
input SCode.Element def;
input output InstNode node;
input SourceInfo info;
protected
Class cls;
ClassTree cls_tree;
Modifier mod;
InstNode builtin_ext;
Class.Prefixes prefs;
Restriction res;
algorithm
cls := InstNode.getClass(node);
// Change the class to an empty expanded class, to avoid instantiation loops.
cls := Class.initExpandedClass(cls);
node := InstNode.updateClass(cls, node);
Class.EXPANDED_CLASS(elements = cls_tree, modifier = mod, prefixes = prefs) := cls;
builtin_ext := ClassTree.mapFoldExtends(cls_tree, expandExtends, InstNode.EMPTY_NODE());
if InstNode.name(builtin_ext) == "ExternalObject" then
node := expandExternalObject(cls_tree, node);
else
if not InstNode.isEmpty(builtin_ext) then
checkBuiltinTypeExtends(builtin_ext, cls_tree, node);
end if;
cls_tree := ClassTree.expand(cls_tree);
res := Restriction.fromSCode(SCodeUtil.getClassRestriction(def));
cls := Class.EXPANDED_CLASS(cls_tree, mod, prefs, res);
node := InstNode.updateClass(cls, node);
end if;
end expandClassParts;
function expandExtends
input output InstNode ext;
input output InstNode builtinExt = InstNode.EMPTY_NODE();
protected
SCode.Element def;
Absyn.Path base_path;
list<InstNode> base_nodes;
InstNode scope, base_node;
SCode.Visibility vis;
SCode.Mod smod;
Option<SCode.Annotation> ann;
SourceInfo info;
algorithm
if InstNode.isEmpty(ext) then
return;
end if;
def := InstNode.definition(ext);
() := match def
case SCode.Element.EXTENDS(base_path, vis, smod, ann, info)
algorithm
// Look up the base class and expand it.
scope := InstNode.parent(ext);
base_nodes as (base_node :: _) := Lookup.lookupBaseClassName(base_path, scope, info);
checkExtendsLoop(base_node, base_path, info);
checkReplaceableBaseClass(base_nodes, base_path, info);
base_node := expand(base_node);
ext := InstNode.setNodeType(InstNodeType.BASE_CLASS(scope, def), base_node);
// If the extended class is a builtin class, like Real or any type derived
// from Real, then return it so we can handle it properly in expandClass.
// We don't care if builtinExt is already SOME, since that's not legal and
// will be caught by expandBuiltinExtends.
if InstNode.isBuiltin(base_node) or Class.isBuiltin(InstNode.getClass(base_node)) then
builtinExt := ext;
end if;
then
();
else ();
end match;
end expandExtends;
function checkExtendsLoop
"Gives an error if a base node is in the process of being expanded itself,
since that means we have an extends loop in the model."
input InstNode node;
input Absyn.Path path;
input SourceInfo info;
algorithm
() := match InstNode.getClass(node)
// expand begins by changing the class to an EXPANDED_CLASS, but keeps the
// class tree. So finding a PARTIAL_TREE here means the class is in the
// process of being expanded.
case Class.EXPANDED_CLASS(elements = ClassTree.PARTIAL_TREE())
algorithm
Error.addSourceMessage(Error.EXTENDS_LOOP,
{AbsynUtil.pathString(path)}, info);
then
fail();
else ();
end match;
end checkExtendsLoop;
function checkReplaceableBaseClass
"Checks that all parts of a name used as a base class are transitively
non-replaceable."
input list<InstNode> baseClasses;
input Absyn.Path basePath;
input SourceInfo info;
protected
Integer i = 0, pos;
String name;
list<InstNode> rest;
algorithm
for base in baseClasses loop
i := i + 1;
if SCodeUtil.isElementReplaceable(InstNode.definition(base)) then
// The path might contain several classes with the same name, so mark the
// class in the path string to make it clear which one we mean.
if listLength(baseClasses) > 1 then
rest := baseClasses;
name := "";
for j in 1:i-1 loop
name := "." + InstNode.name(listHead(rest)) + name;
rest := listRest(rest);
end for;
name := "<" + InstNode.name(listHead(rest)) + ">" + name;
rest := listRest(rest);
for n in rest loop
name := InstNode.name(n) + "." + name;
end for;
else
name := AbsynUtil.pathString(basePath);
end if;
Error.addMultiSourceMessage(Error.REPLACEABLE_BASE_CLASS,
{InstNode.name(base), name}, {InstNode.info(base), info});
fail();
end if;
end for;
end checkReplaceableBaseClass;
function expandExternalObject
input ClassTree clsTree;
input output InstNode node;
protected
ComplexType eo_ty;
Class c;
algorithm
// Construct the ComplexType for the external object.
eo_ty := makeExternalObjectType(clsTree, node);
// Construct the Class for the external object. We use an empty class
// tree here, since the constructor and destructor is embedded in the
// ComplexType instead. Using an empty class tree makes sure it's not
// possible to call the constructor or destructor explicitly.
c := Class.PARTIAL_BUILTIN(Type.COMPLEX(node, eo_ty), NFClassTree.EMPTY_FLAT,
Modifier.NOMOD(), NFClass.DEFAULT_PREFIXES, Restriction.EXTERNAL_OBJECT());
node := InstNode.updateClass(c, node);
end expandExternalObject;
function checkBuiltinTypeExtends
input InstNode builtinExtends;
input ClassTree tree;
input InstNode node;
algorithm
// A class extending from a builtin type may not have other components or baseclasses.
if ClassTree.componentCount(tree) > 0 or ClassTree.extendsCount(tree) > 1 then
// ***TODO***: Find the invalid element and use its info to make the error
// message more accurate.
Error.addSourceMessage(Error.BUILTIN_EXTENDS_INVALID_ELEMENTS,
{InstNode.name(builtinExtends)}, InstNode.info(node));
fail();
end if;
end checkBuiltinTypeExtends;
function makeExternalObjectType
"Constructs a ComplexType for an external object, and also checks that the
external object declaration is valid."
input ClassTree tree;
input InstNode node;
output ComplexType ty;
protected
Absyn.Path base_path;
InstNode constructor = InstNode.EMPTY_NODE(), destructor = InstNode.EMPTY_NODE();
algorithm
ty := match tree
case ClassTree.PARTIAL_TREE()
algorithm
// An external object may not contain components.
for comp in tree.components loop
if InstNode.isComponent(comp) then
Error.addSourceMessage(Error.EXTERNAL_OBJECT_INVALID_ELEMENT,
{InstNode.name(node), InstNode.name(comp)}, InstNode.info(comp));
fail();
end if;
end for;
// An external object may not contain extends other than the ExternalObject one.
if arrayLength(tree.exts) > 1 then
for ext in tree.exts loop
if InstNode.name(ext) <> "ExternalObject" then
InstNode.CLASS_NODE(nodeType = InstNodeType.BASE_CLASS(definition =
SCode.EXTENDS(baseClassPath = base_path))) := ext;
Error.addSourceMessage(Error.EXTERNAL_OBJECT_INVALID_ELEMENT,
{InstNode.name(node), "extends " + AbsynUtil.pathString(base_path)}, InstNode.info(ext));
fail();
end if;
end for;
end if;
// An external object must have exactly two functions called constructor and
// destructor.
for cls in tree.classes loop
() := match InstNode.name(cls)
case "constructor" guard SCodeUtil.isFunction(InstNode.definition(cls))
algorithm
constructor := cls;
then
();
case "destructor" guard SCodeUtil.isFunction(InstNode.definition(cls))
algorithm
destructor := cls;
then
();
else
algorithm
// Found some other element => error.
Error.addSourceMessage(Error.EXTERNAL_OBJECT_INVALID_ELEMENT,
{InstNode.name(node), InstNode.name(cls)}, InstNode.info(cls));
then
fail();
end match;
end for;
if InstNode.isEmpty(constructor) then
// The constructor is missing.
Error.addSourceMessage(Error.EXTERNAL_OBJECT_MISSING_STRUCTOR,
{InstNode.name(node), "constructor"}, InstNode.info(node));
fail();
end if;
if InstNode.isEmpty(destructor) then
// The destructor is missing.
Error.addSourceMessage(Error.EXTERNAL_OBJECT_MISSING_STRUCTOR,
{InstNode.name(node), "destructor"}, InstNode.info(node));
fail();
end if;
then
ComplexType.EXTERNAL_OBJECT(constructor, destructor);
end match;
end makeExternalObjectType;
function expandClassDerived
input SCode.Element element;
input SCode.ClassDef definition;
input output InstNode node;
input SourceInfo info;
protected
Absyn.TypeSpec ty;
InstNode ext_node;
Class cls;
Class.Prefixes prefs;
SCode.Attributes sattrs;
Component.Attributes attrs;
list<Dimension> dims;
Modifier mod;
Restriction res;
algorithm
SCode.DERIVED(typeSpec = ty, attributes = sattrs) := definition;
// Look up the class that's being derived from and expand it.
ext_node :: _ := Lookup.lookupBaseClassName(AbsynUtil.typeSpecPath(ty), InstNode.parent(node), info);
// Check that the class isn't extending itself, i.e. class A = A.
if referenceEq(ext_node, node) then
Error.addSourceMessage(Error.RECURSIVE_SHORT_CLASS_DEFINITION,
{InstNode.name(node), Dump.unparseTypeSpec(ty)}, info);
fail();
end if;
ext_node := expand(ext_node);
ext_node := InstNode.clone(ext_node);
// Fetch the needed information from the class definition and construct a EXPANDED_DERIVED.
cls := InstNode.getClass(node);
prefs := Class.getPrefixes(cls);
// A short class definition deriving from a partial class is itself partial.
if not Class.Prefixes.isPartial(prefs) and InstNode.isPartial(ext_node) then
prefs.partialPrefix := SCode.Partial.PARTIAL();
end if;
attrs := instDerivedAttributes(sattrs);
dims := list(Dimension.RAW_DIM(d) for d in AbsynUtil.typeSpecDimensions(ty));
mod := Class.getModifier(cls);
res := Restriction.fromSCode(SCodeUtil.getClassRestriction(element));
cls := Class.EXPANDED_DERIVED(ext_node, mod, listArray(dims), prefs, attrs, res);
node := InstNode.updateClass(cls, node);
end expandClassDerived;
function instDerivedAttributes
input SCode.Attributes scodeAttr;
output Component.Attributes attributes;
protected
ConnectorType.Type cty;
Variability var;
Direction dir;
algorithm
attributes := match scodeAttr
case SCode.Attributes.ATTR(
connectorType = SCode.ConnectorType.POTENTIAL(),
variability = SCode.Variability.VAR(),
direction = Absyn.Direction.BIDIR())
then NFComponent.DEFAULT_ATTR;
else
algorithm
cty := ConnectorType.fromSCode(scodeAttr.connectorType);
var := Prefixes.variabilityFromSCode(scodeAttr.variability);
dir := Prefixes.directionFromSCode(scodeAttr.direction);
then
Component.Attributes.ATTRIBUTES(cty, Parallelism.NON_PARALLEL,
var, dir, InnerOuter.NOT_INNER_OUTER, false, false, Replaceable.NOT_REPLACEABLE());
end match;
end instDerivedAttributes;
function instClass
input output InstNode node;
input Modifier modifier;
input output Component.Attributes attributes = NFComponent.DEFAULT_ATTR;
input Boolean useBinding;
input Integer instLevel;
input InstNode parent = InstNode.EMPTY_NODE();
protected
Class cls;
Modifier outer_mod;
algorithm
cls := InstNode.getClass(node);
outer_mod := Class.getModifier(cls);
// Give an error for modifiers such as (A = B), i.e. attempting to replace a
// class without using redeclare.
if Modifier.hasBinding(outer_mod) then
Error.addSourceMessage(Error.MISSING_REDECLARE_IN_CLASS_MOD,
{InstNode.name(node)}, Binding.getInfo(Modifier.binding(outer_mod)));
fail();
end if;
(attributes, node) := instClassDef(cls, modifier, attributes, useBinding, node, parent, instLevel);
end instClass;
function instClassDef
input Class cls;
input Modifier outerMod;
input output Component.Attributes attributes;
input Boolean useBinding;
input output InstNode node;
input InstNode parent;
input Integer instLevel;
protected
InstNode par, base_node;
Class inst_cls;
ClassTree cls_tree;
Modifier mod, outer_mod;
Restriction res;
Type ty;
Component.Attributes attrs;
algorithm
() := match cls
case Class.EXPANDED_CLASS(restriction = res)
algorithm
// Skip instantiating the class tree if the class is a base class,
// it has (hopefully) already been instantiated in that case.
if InstNode.isBaseClass(node) then
par := parent;
else
(node, par) := ClassTree.instantiate(node, parent);
end if;
updateComponentType(parent, node);
attributes := updateClassConnectorType(res, attributes);
inst_cls as Class.EXPANDED_CLASS(elements = cls_tree) := InstNode.getClass(node);
// Fetch modification on the class definition (for class extends).
mod := Modifier.fromElement(InstNode.definition(node), {}, par);
// Merge with any outer modifications.
outer_mod := Modifier.merge(outerMod, cls.modifier);
mod := Modifier.merge(outer_mod, mod);
// Apply the modifiers of extends nodes.
ClassTree.mapExtends(cls_tree, function modifyExtends(scope = par));
// Apply the modifiers of this scope.
applyModifier(mod, cls_tree, InstNode.name(node));
// Apply element redeclares.
ClassTree.mapRedeclareChains(cls_tree, function redeclareElements(instLevel = instLevel));
// Redeclare classes with redeclare modifiers. Redeclared components could
// also be handled here, but since each component is only instantiated once
// it's more efficient to apply the redeclare when instantiating them instead.
redeclareClasses(cls_tree);
// Instantiate the extends nodes.
ClassTree.mapExtends(cls_tree,
function instExtends(attributes = attributes, useBinding = useBinding,
visibility = ExtendsVisibility.PUBLIC, instLevel = instLevel + 1));
// Instantiate local components.
ClassTree.applyLocalComponents(cls_tree,
function instComponent(attributes = attributes, innerMod = Modifier.NOMOD(),
originalAttr = NONE(), useBinding = useBinding, instLevel = instLevel + 1));
// Remove duplicate elements.
cls_tree := ClassTree.replaceDuplicates(cls_tree);
ClassTree.checkDuplicates(cls_tree);
InstNode.updateClass(Class.setClassTree(cls_tree, inst_cls), node);
then
();
case Class.EXPANDED_DERIVED()
algorithm
(node, par) := ClassTree.instantiate(node, parent);
node := InstNode.setNodeType(InstNodeType.DERIVED_CLASS(InstNode.nodeType(node)), node);
Class.EXPANDED_DERIVED(baseClass = base_node) := InstNode.getClass(node);
// Merge outer modifiers and attributes.
mod := Modifier.fromElement(InstNode.definition(node), {node}, InstNode.rootParent(node));
outer_mod := Modifier.merge(outerMod, Modifier.addParent(node, cls.modifier));
mod := Modifier.merge(outer_mod, mod);
attrs := updateClassConnectorType(cls.restriction, cls.attributes);
attributes := mergeDerivedAttributes(attrs, attributes, parent);
// Instantiate the base class and update the nodes.
(base_node, attributes) := instClass(base_node, mod, attributes, useBinding, instLevel, par);
cls.baseClass := base_node;
cls.attributes := attributes;
cls.dims := arrayCopy(cls.dims);
// Update the parent's type with the new class instance.
node := InstNode.updateClass(cls, node);
updateComponentType(parent, node);
then
();
case Class.PARTIAL_BUILTIN(restriction = Restriction.EXTERNAL_OBJECT())
algorithm
inst_cls := Class.INSTANCED_BUILTIN(cls.ty, cls.elements, cls.restriction);
node := InstNode.replaceClass(inst_cls, node);
updateComponentType(parent, node);
instExternalObjectStructors(cls.ty, parent);
then
();
case Class.PARTIAL_BUILTIN(ty = ty, restriction = res)
algorithm
(node, par) := ClassTree.instantiate(node, parent);
updateComponentType(parent, node);
cls_tree := Class.classTree(InstNode.getClass(node));
mod := Modifier.fromElement(InstNode.definition(node), {node}, InstNode.parent(node));
outer_mod := Modifier.merge(outerMod, Modifier.addParent(node, cls.modifier));
mod := Modifier.merge(outer_mod, mod);
applyModifier(mod, cls_tree, InstNode.name(node));
inst_cls := Class.INSTANCED_BUILTIN(ty, cls_tree, res);
node := InstNode.updateClass(inst_cls, node);
then
();
// If a class has an instance of a encapsulating class, then the encapsulating
// class will have been fully instantiated to allow lookup in it. This is a
// rather uncommon case hopefully, so in that case just reinstantiate the class.
case Class.INSTANCED_CLASS()
algorithm
node := InstNode.replaceClass(Class.NOT_INSTANTIATED(), node);
node := InstNode.setNodeType(InstNodeType.NORMAL_CLASS(), node);
node := expand(node);
node := instClass(node, outerMod, attributes, useBinding, instLevel, parent);
updateComponentType(parent, node);
then
();
else
algorithm
Error.assertion(false, getInstanceName() + " got unknown class.", sourceInfo());
then
();
end match;
end instClassDef;
function updateComponentType
"Sets the class instance of a component node."
input output InstNode component;
input InstNode cls;
algorithm
if InstNode.isComponent(component) then
component := InstNode.componentApply(component, Component.setClassInstance, cls);
end if;
end updateComponentType;
function updateClassConnectorType
input Restriction res;
input output Component.Attributes attrs;
algorithm
if Restriction.isExpandableConnector(res) then
attrs.connectorType := ConnectorType.setExpandable(attrs.connectorType);
elseif Restriction.isConnector(res) then
attrs.connectorType := ConnectorType.setConnector(attrs.connectorType);
end if;
end updateClassConnectorType;
function instExternalObjectStructors
"Instantiates the constructor and destructor for an ExternalObject class."
input Type ty;
input InstNode parent;
protected
InstNode constructor, destructor, par;
SourceInfo info;
algorithm
// The constructor and destructor have function parameters that are instances
// of the external object class, and we instantiate the structors when we
// instantiate such instances. To break that loop we check that we're not
// inside the external object class before instantiating the structors.
par := InstNode.parent(InstNode.parent(parent));
if not (InstNode.isClass(par) and Class.isExternalObject(InstNode.getClass(par))) then
Type.COMPLEX(complexTy = ComplexType.EXTERNAL_OBJECT(constructor, destructor)) := ty;
info := InstNode.info(parent);
Function.instFunctionNode(constructor, info);
Function.instFunctionNode(destructor, info);
end if;
end instExternalObjectStructors;
function instPackage
"This function instantiates a package given a package node. If the package has
already been instantiated, then the cached instance from the node is
returned. Otherwise the node is fully instantiated, the instance is added to
the node's cache, and the instantiated node is returned."
input output InstNode node;
protected
CachedData cache;
InstNode inst;
algorithm
cache := InstNode.getPackageCache(node);
node := match cache
case CachedData.PACKAGE() then cache.instance;
case CachedData.NO_CACHE()
algorithm
// Cache the package node itself first, to avoid instantiation loops if
// the package uses itself somehow.
InstNode.setPackageCache(node, CachedData.PACKAGE(node));
// Instantiate the node.
inst := instantiate(node);
// Cache the instantiated node and instantiate expressions in it too.
if not InstNode.isPartial(inst) then
InstNode.setPackageCache(node, CachedData.PACKAGE(inst));
instExpressions(inst);
end if;
then
inst;
else
algorithm
Error.assertion(false, getInstanceName() + " got invalid instance cache", sourceInfo());
then
fail();
end match;
end instPackage;
function modifyExtends
input output InstNode extendsNode;
input InstNode scope;
protected
SCode.Element elem;
Modifier ext_mod;
InstNode ext_node;
SourceInfo info;
Class cls;
ClassTree cls_tree;
algorithm
cls := InstNode.getClass(extendsNode);
cls_tree := Class.classTree(cls);
// Create a modifier from the extends.
InstNodeType.BASE_CLASS(definition = elem) := InstNode.nodeType(extendsNode);
ext_mod := Modifier.fromElement(elem, {}, scope);
ext_mod := Modifier.merge(InstNode.getModifier(extendsNode), ext_mod);
if not Class.isBuiltin(cls) then
ClassTree.mapExtends(cls_tree, function modifyExtends(scope = extendsNode));
() := match elem
case SCode.EXTENDS()