-
Notifications
You must be signed in to change notification settings - Fork 296
/
Interactive.mo
15557 lines (14428 loc) · 550 KB
/
Interactive.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 Interactive
" file: Interactive.mo
package: Interactive
description: This module contain functionality for model management,
expression evaluation, etc. in the interactive environment.
$Id: Interactive.mo 25580 2015-04-16 14:04:16Z jansilar $
This module contain functionality for model management, expression evaluation, etc.
in the interactive environment.
The module defines a symboltable used in the interactive environment containing:
- Modelica models (described using Absyn AST)
- GlobalScript.Variable bindings
- Compiled functions (so they do not need to be recompiled)
- Instantiated classes (that can be reused, not impl. yet)
- Modelica models in SCode form (to speed up instantiation. not impl. yet)"
//public imports
import Absyn;
import AbsynUtil;
import ConnectionGraph;
import DAE;
import FCore;
import Global;
import SCode;
import AbsynToSCode;
import Settings;
import Values;
// protected imports
protected
import Ceval;
import CevalScript;
import ClassInf;
import ClockIndexes;
import Config;
import DAE.Connect;
import DAEDump;
import DAEUtil;
import Debug;
import Dump;
import Error;
import ErrorExt;
import ExpressionDump;
import ExpressionSimplify;
import FGraph;
import Flags;
import FlagsUtil;
import GC;
import GlobalScriptDump;
import InnerOuter;
import Inst;
import InstHashTable;
import InstTypes;
import InstUtil;
import InteractiveUtil;
import List;
import Lookup;
import MetaUtil;
import Mod;
import NFApi;
import Parser;
import Print;
import Refactor;
import SCodeUtil;
import StackOverflow;
import Static;
import StaticScript;
import StringUtil;
import SymbolTable;
import System;
import Testsuite;
import Types;
import UnitAbsyn;
import Util;
import ValuesUtil;
import MetaModelica.Dangerous;
public uniontype AnnotationType
record ICON_ANNOTATION end ICON_ANNOTATION;
record DIAGRAM_ANNOTATION end DIAGRAM_ANNOTATION;
end AnnotationType;
public uniontype GraphicEnvCache
"Used by buildEnvForGraphicProgram to avoid excessive work."
record GRAPHIC_ENV_NO_CACHE
Absyn.Program program;
Absyn.Path modelPath;
end GRAPHIC_ENV_NO_CACHE;
record GRAPHIC_ENV_PARTIAL_CACHE
Absyn.Program program;
Absyn.Path modelPath;
FCore.Cache cache;
FCore.Graph env;
end GRAPHIC_ENV_PARTIAL_CACHE;
record GRAPHIC_ENV_FULL_CACHE
Absyn.Program program;
Absyn.Path modelPath;
FCore.Cache cache;
FCore.Graph env;
end GRAPHIC_ENV_FULL_CACHE;
end GraphicEnvCache;
public function evaluate
"This function evaluates expressions or statements feed interactively to the compiler.
inputs: (GlobalScript.Statements, bool /* verbose */)
outputs: string:
The resulting string after evaluation. If an error has occurred, this string
will be empty. The error messages can be retrieved by calling print_messages_str()
in Error.mo."
input GlobalScript.Statements inStatements;
input Boolean inBoolean;
output String outString;
algorithm
outString := matchcontinue (inStatements,inBoolean)
local
String res,res_1,res2,res_2;
Boolean echo,semicolon,verbose;
GlobalScript.Statement x;
list<GlobalScript.Statement> xs;
case (GlobalScript.ISTMTS(interactiveStmtLst = {x},semicolon = semicolon),verbose)
equation
showStatement(x, semicolon, true);
res = evaluate2(GlobalScript.ISTMTS({x},verbose));
echo = getEcho();
res_1 = selectResultstr(res, semicolon, verbose, echo);
showStatement(x, semicolon, false);
then res_1;
case (GlobalScript.ISTMTS(interactiveStmtLst = (x :: xs),semicolon = semicolon),verbose)
equation
showStatement(x, semicolon, true);
res = evaluate2(GlobalScript.ISTMTS({x},semicolon));
echo = getEcho();
res_1 = selectResultstr(res, semicolon, verbose, echo);
showStatement(x, semicolon, false);
res2 = evaluate(GlobalScript.ISTMTS(xs,semicolon), verbose);
res_2 = stringAppendList({res_1,res2});
then res_2;
end matchcontinue;
end evaluate;
public function evaluateToStdOut
"This function evaluates expressions or statements feed interactively to the compiler.
The resulting string after evaluation is printed.
If an error has occurred, this string will be empty.
The error messages can be retrieved by calling print_messages_str() in Error.mo."
input GlobalScript.Statements statements;
input Boolean verbose;
protected
GlobalScript.Statement x;
list<GlobalScript.Statement> xs;
Boolean semicolon;
String res;
algorithm
xs := statements.interactiveStmtLst;
semicolon := statements.semicolon;
while not listEmpty(xs) loop
x::xs := xs;
showStatement(x, semicolon, true);
res := evaluate2(GlobalScript.ISTMTS({x},if listEmpty(xs) then verbose else semicolon));
print(selectResultstr(res, semicolon, verbose, getEcho()));
showStatement(x, semicolon, false);
end while;
end evaluateToStdOut;
public function evaluateFork
"As evaluateToStdOut, but takes the inputs as a tuple of mos-script file and symbol table.
As it is supposed to work in a thread without output, it also flushes the error-buffer since that will otherwise be lost to the void."
input tuple<String,SymbolTable> inTpl;
output Boolean b;
algorithm
b := matchcontinue inTpl
local
String mosfile;
GlobalScript.Statements statements;
SymbolTable st;
Absyn.Program ast;
Option<SCode.Program> explodedAst;
case ((mosfile,st))
equation
SymbolTable.reset();
SymbolTable.setAbsyn(st.ast);
SymbolTable.setSCode(st.explodedAst);
setGlobalRoot(Global.instOnlyForcedFunctions, NONE()); // thread-local root that has to be set!
statements = Parser.parseexp(mosfile);
evaluateToStdOut(statements,true);
print(Error.printMessagesStr(false));
then true;
else
equation
print(Error.printMessagesStr(false));
then false;
end matchcontinue;
end evaluateFork;
protected function showStatement
input GlobalScript.Statement s;
input Boolean semicolon;
input Boolean start;
protected
Boolean testsuite;
algorithm
if not Flags.isSet(Flags.SHOW_STATEMENT) then
return;
end if;
testsuite := Testsuite.isRunning();
_ := matchcontinue(start, testsuite)
// running testsuite
case (true, true)
equation
print("Evaluating: " + printIstmtStr(GlobalScript.ISTMTS({s}, semicolon)) + "\n");
System.fflush();
then
();
case (false, true) then ();
// not running testsuite, show more!
case (true, false)
equation
System.realtimeTick(ClockIndexes.RT_CLOCK_SHOW_STATEMENT);
print("Evaluating: > " + printIstmtStr(GlobalScript.ISTMTS({s}, semicolon)) + "\n");
System.fflush();
then
();
case (false, false)
equation
print("Evaluated: < " + realString(System.realtimeTock(ClockIndexes.RT_CLOCK_SHOW_STATEMENT)) + " / " + printIstmtStr(GlobalScript.ISTMTS({s}, semicolon)) + "\n");
System.fflush();
then
();
else ();
end matchcontinue;
end showStatement;
protected function selectResultstr
"Returns result string depending on three boolean variables
- semicolon
- verbose
- echo"
input String inString;
input Boolean inSemicolon "semicolon";
input Boolean inVerbose "verbose";
input Boolean inEcho "echo";
output String outString;
algorithm
outString := match (inString,inSemicolon,inVerbose,inEcho)
local String str;
case (_,_,_,false) then ""; // echo off always empty string
case (str,_,true,_) then str; // .. verbose on always return str
case (_,true,_,_) then ""; // ... semicolon, no resultstr
case (str,false,_,_) then str; // no semicolon
end match;
end selectResultstr;
protected function getEcho
"Return echo variable, which determines
if result should be printed or not."
output Boolean outBoolean;
algorithm
outBoolean := 0 <> Settings.getEcho();
end getEcho;
public function evaluate2
"Helper function to evaluate."
input GlobalScript.Statements inStatements;
output String outString;
protected
GlobalScript.Statement stmt;
String str, str_1;
algorithm
GlobalScript.ISTMTS(interactiveStmtLst = {stmt}) := inStatements;
try /* Stack overflow */
outString := matchcontinue stmt
local
Absyn.AlgorithmItem algitem;
Boolean outres;
Absyn.Exp exp;
Boolean partialInst, gen, evalfunc, keepArrays;
SourceInfo info;
// evaluate graphical API
case GlobalScript.IEXP(exp = Absyn.CALL())
equation
// adrpo: always evaluate the graphicalAPI with these options so instantiation is faster!
partialInst = System.getPartialInstantiation();
System.setPartialInstantiation(true);
gen = FlagsUtil.set(Flags.GEN, false);
evalfunc = FlagsUtil.set(Flags.EVAL_FUNC, false);
keepArrays = Flags.getConfigBool(Flags.KEEP_ARRAYS);
FlagsUtil.setConfigBool(Flags.KEEP_ARRAYS, false);
InstHashTable.init();
str = evaluateGraphicalApi(stmt, partialInst, gen, evalfunc, keepArrays);
str_1 = stringAppend(str, "\n");
then str_1;
// Evaluate algorithm statements in evaluateAlgStmt()
case GlobalScript.IALG(algItem = (algitem as Absyn.ALGORITHMITEM()))
equation
InstHashTable.init();
str = evaluateAlgStmt(algitem);
str_1 = stringAppend(str, "\n");
then str_1;
// Evaluate expressions in evaluate_exprToStr()
case GlobalScript.IEXP(exp = exp, info = info)
equation
InstHashTable.init();
str = evaluateExprToStr(exp, info);
str_1 = stringAppend(str, "\n");
then str_1;
end matchcontinue;
else
str := "";
str_1 := "";
GC.gcollect();
str := StackOverflow.getReadableMessage();
if Testsuite.isRunning() then
/* It's useful to print the name of the component we failed on.
* But we crash in different places, so for the testsuite we skip this.
*/
Error.clearCurrentComponent();
end if;
Error.addMessage(Error.STACK_OVERFLOW_DETAILED, {GlobalScriptDump.printIstmtStr(stmt), str});
Error.clearCurrentComponent();
outString := "\n";
end try annotation(__OpenModelica_stackOverflowCheckpoint=true);
end evaluate2;
protected function evaluateAlgStmt
"This function takes an AlgorithmItem, i.e. a statement located in an
algorithm section, and a symboltable as input arguments. The statements
are recursivly evalutated and a new interactive symbol table is returned."
input Absyn.AlgorithmItem inAlgorithmItem;
output String outString;
algorithm
outString := matchcontinue inAlgorithmItem
local
FCore.Graph env;
DAE.Exp econd,msg_1,sexp,srexp;
DAE.Properties prop,rprop;
Absyn.Exp cond,msg,exp,rexp;
Absyn.Program p;
String str,ident;
DAE.Type t;
Values.Value value;
list<DAE.Type> types;
list<String> idents;
list<Values.Value> values,valList;
list<Absyn.Exp> crefexps;
tuple<Absyn.Exp, list<Absyn.AlgorithmItem>> cond1;
list<tuple<Absyn.Exp, list<Absyn.AlgorithmItem>>> cond2,cond3,elseifexpitemlist;
list<Absyn.AlgorithmItem> algitemlist,elseitemlist;
list<GlobalScript.Variable> vars;
String iter,estr;
list<Absyn.AlgorithmItem> algItemList;
Values.Value startv, stepv, stopv;
Absyn.Exp starte, stepe, stope;
Absyn.ComponentRef cr;
FCore.Cache cache;
SourceInfo info;
Absyn.FunctionArgs fargs;
list<Absyn.Subscript> asubs;
list<DAE.Subscript> dsubs;
list<DAE.ComponentRef> crefs;
case Absyn.ALGORITHMITEM(info=info,
algorithm_ = Absyn.ALG_NORETCALL(functionCall = Absyn.CREF_IDENT(name = "assert"),
functionArgs = Absyn.FUNCTIONARGS(args = {cond,_})))
equation
env = SymbolTable.buildEnv();
(cache,econd,_) = StaticScript.elabExp(FCore.emptyCache(), env, cond, true, true, DAE.NOPRE(), info);
(_,Values.BOOL(true)) = CevalScript.ceval(cache,env, econd, true, Absyn.MSG(info), 0);
then "";
case Absyn.ALGORITHMITEM(info=info,algorithm_ = Absyn.ALG_NORETCALL(functionCall = Absyn.CREF_IDENT(name = "assert"),
functionArgs = Absyn.FUNCTIONARGS(args = {_,msg})))
equation
env = SymbolTable.buildEnv();
(cache,msg_1,_) = StaticScript.elabExp(FCore.emptyCache(), env, msg, true, true, DAE.NOPRE(), info);
(_,Values.STRING(str)) = CevalScript.ceval(cache,env, msg_1, true, Absyn.MSG(info), 0);
then str;
case Absyn.ALGORITHMITEM(info=info,algorithm_ = Absyn.ALG_NORETCALL(functionCall = cr,functionArgs = fargs))
equation
env = SymbolTable.buildEnv();
exp = Absyn.CALL(cr,fargs,{});
(cache,sexp,_) = StaticScript.elabExp(FCore.emptyCache(), env, exp, true, true, DAE.NOPRE(), info);
(_,_) = CevalScript.ceval(cache, env, sexp, true, Absyn.MSG(info), 0);
then "";
// Special case to lookup fields of records.
// SimulationResult, etc are not in the environment,
// but it's nice to be able to script them anyway
case Absyn.ALGORITHMITEM(algorithm_ =
Absyn.ALG_ASSIGN(assignComponent =
Absyn.CREF(Absyn.CREF_IDENT(name = ident,subscripts = {})),value = Absyn.CREF(cr)))
equation
value = getVariableValueLst(AbsynUtil.pathToStringList(AbsynUtil.crefToPath(cr)), SymbolTable.getVars());
str = ValuesUtil.valString(value);
t = Types.typeOfValue(value);
SymbolTable.addVar(DAE.CREF_IDENT(ident, t, {}), value, FGraph.empty());
then str;
case
Absyn.ALGORITHMITEM(info=info,algorithm_ =
Absyn.ALG_ASSIGN(assignComponent =
Absyn.CREF(Absyn.CREF_IDENT(name = ident,subscripts = asubs)),value = exp))
equation
env = SymbolTable.buildEnv();
(cache,sexp,DAE.PROP(_,_)) = StaticScript.elabExp(FCore.emptyCache(),env, exp, true, true, DAE.NOPRE(),info);
(_,value) = CevalScript.ceval(cache,env, sexp, true,Absyn.MSG(info),0);
(_, dsubs, _) = Static.elabSubscripts(cache, env, asubs, true, DAE.NOPRE(), info);
t = Types.typeOfValue(value) "This type can be more specific than the elaborated type; if the dimensions are unknown...";
str = ValuesUtil.valString(value);
SymbolTable.addVar(DAE.CREF_IDENT(ident, t, dsubs), value, env);
then str;
// Since expressions cannot be tuples an empty string is returned
case
Absyn.ALGORITHMITEM(info=info,algorithm_ =
Absyn.ALG_ASSIGN(assignComponent =
Absyn.TUPLE(expressions = crefexps),value = rexp))
equation
env = SymbolTable.buildEnv();
(cache,srexp,rprop) = StaticScript.elabExp(FCore.emptyCache(),env, rexp, true, true, DAE.NOPRE(),info);
DAE.T_TUPLE(types = types) = Types.getPropType(rprop);
crefs = makeTupleCrefs(crefexps, types, env, cache, info);
(_,Values.TUPLE(values)) = CevalScript.ceval(cache, env, srexp, true, Absyn.MSG(info),0);
SymbolTable.addVars(crefs, values, env);
then "";
// if statement
case
Absyn.ALGORITHMITEM(info=info,algorithm_ =
Absyn.ALG_IF(
ifExp = exp,
trueBranch = algitemlist,
elseIfAlgorithmBranch = elseifexpitemlist,
elseBranch = elseitemlist))
equation
cond1 = (exp,algitemlist);
cond2 = (cond1 :: elseifexpitemlist);
cond3 = listAppend(cond2, {(Absyn.BOOL(true), elseitemlist)});
evaluateIfStatementLst(cond3,info);
then "";
// while-statement
case Absyn.ALGORITHMITEM(info=info,algorithm_ = Absyn.ALG_WHILE(boolExpr = exp,whileBody = algitemlist))
equation
value = evaluateExpr(exp, info);
evaluateWhileStmt(value, exp, algitemlist, info);
then "";
// for-statement, optimized case, e.g.: for i in 1:1000 loop
case Absyn.ALGORITHMITEM(info=info,algorithm_ =
Absyn.ALG_FOR(iterators = {Absyn.ITERATOR(iter, NONE(), SOME(Absyn.RANGE(start=starte,step=NONE(), stop=stope)))},
forBody = algItemList))
equation
startv = evaluateExpr(starte, info);
stopv = evaluateExpr(stope, info);
evaluateForStmtRangeOpt(iter, startv, Values.INTEGER(1), stopv, algItemList);
then "";
// for-statement, optimized case, e.g.: for i in 7.3:0.4:1000.3 loop
case Absyn.ALGORITHMITEM(info=info,algorithm_ =
Absyn.ALG_FOR(iterators = {Absyn.ITERATOR(iter, NONE(), SOME(Absyn.RANGE(start=starte, step=SOME(stepe), stop=stope)))},
forBody = algItemList))
equation
startv = evaluateExpr(starte, info);
stepv = evaluateExpr(stepe, info);
stopv = evaluateExpr(stope, info);
evaluateForStmtRangeOpt(iter, startv, stepv, stopv, algItemList);
then "";
// for-statement, general case
case Absyn.ALGORITHMITEM(info=info,algorithm_ =
Absyn.ALG_FOR(iterators = {Absyn.ITERATOR(iter, NONE(), SOME(exp))},forBody = algItemList))
equation
Values.ARRAY(valueLst = valList) = evaluateExpr(exp, info);
evaluateForStmt(iter, valList, algItemList);
then "";
// for-statement - not an array type
case Absyn.ALGORITHMITEM(info=info,algorithm_ = Absyn.ALG_FOR(iterators = {Absyn.ITERATOR(range = SOME(exp))}))
equation
estr = stringRepresOfExpr(exp);
Error.addSourceMessage(Error.NOT_ARRAY_TYPE_IN_FOR_STATEMENT, {estr}, info);
then fail();
end matchcontinue;
end evaluateAlgStmt;
protected function evaluateForStmt
"evaluates a for-statement in an algorithm section"
input String iter "The iterator variable which will be assigned different values";
input list<Values.Value> valList "List of values that the iterator later will be assigned to";
input list<Absyn.AlgorithmItem> algItemList;
algorithm
for val in valList loop
SymbolTable.appendVar(iter, val, Types.typeOfValue(val));
evaluateAlgStmtLst(algItemList);
SymbolTable.deleteVarFirstEntry(iter);
end for;
end evaluateForStmt;
protected function evaluateForStmtRangeOpt
"Optimized version of for statement. In this case, we do not create a large array if
a range expression is given. E.g. for i in 1:10000 loop"
input String iter "The iterator variable which will be assigned different values";
input Values.Value startVal;
input Values.Value stepVal;
input Values.Value stopVal;
input list<Absyn.AlgorithmItem> algItems;
protected
Values.Value val;
algorithm
val := startVal;
try
while ValuesUtil.safeLessEq(val, stopVal) loop
SymbolTable.appendVar(iter, val, Types.typeOfValue(val));
evaluateAlgStmtLst(algItems);
SymbolTable.deleteVarFirstEntry(iter);
val := ValuesUtil.safeIntRealOp(val, stepVal, Values.ADDOP());
end while;
else
// Just... ignore errors and stop the loop. Really bad, I know...
end try;
end evaluateForStmtRangeOpt;
protected function evaluateWhileStmt
"Recursively evaluates the while statement.
Note that it is tail-recursive, so we should result
in a iterative implementation."
input Values.Value inValue;
input Absyn.Exp inExp;
input list<Absyn.AlgorithmItem> inAbsynAlgorithmItemLst;
input SourceInfo info;
algorithm
_ :=
matchcontinue (inValue,inExp,inAbsynAlgorithmItemLst,info)
local
Values.Value value;
Absyn.Exp exp;
list<Absyn.AlgorithmItem> algitemlst;
String estr,tstr;
DAE.Type vtype;
case (Values.BOOL(boolean = false),_,_,_) then ();
case (Values.BOOL(boolean = true),exp,algitemlst,_)
equation
evaluateAlgStmtLst(algitemlst);
value = evaluateExpr(exp, info);
evaluateWhileStmt(value, exp, algitemlst, info); /* Tail recursive */
then ();
// An error occured when evaluating the algorithm items
case (Values.BOOL(_), _,_,_)
then ();
// The condition value was not a boolean
case (value,exp,_,_)
equation
estr = stringRepresOfExpr(exp);
vtype = Types.typeOfValue(value);
tstr = Types.unparseTypeNoAttr(vtype);
Error.addSourceMessage(Error.WHILE_CONDITION_TYPE_ERROR, {estr,tstr}, info);
then fail();
end matchcontinue;
end evaluateWhileStmt;
protected function evaluatePartOfIfStatement
"Evaluates one part of a if statement, i.e. one \"case\". If the condition is true, the algorithm items
associated with this condition are evaluated. The first argument returned is set to true if the
condition was evaluated to true. Fails if the value is not a boolean.
Note that we are sending the expression as an value, so that it does not need to be evaluated twice."
input Values.Value inValue;
input Absyn.Exp inExp;
input list<Absyn.AlgorithmItem> inAbsynAlgorithmItemLst;
input list<tuple<Absyn.Exp, list<Absyn.AlgorithmItem>>> inTplAbsynExpAbsynAlgorithmItemLstLst;
input SourceInfo info;
algorithm
_ :=
matchcontinue (inValue,inExp,inAbsynAlgorithmItemLst,inTplAbsynExpAbsynAlgorithmItemLstLst,info)
local
list<Absyn.AlgorithmItem> algitemlst;
list<tuple<Absyn.Exp, list<Absyn.AlgorithmItem>>> algrest;
String estr,tstr;
DAE.Type vtype;
Values.Value value;
Absyn.Exp exp;
case (Values.BOOL(boolean = true),_,algitemlst,_,_)
equation
evaluateAlgStmtLst(algitemlst);
then ();
case (Values.BOOL(boolean = false),_,_,algrest,_)
equation
evaluateIfStatementLst(algrest, info);
then ();
// Report type error
case (value,exp,_,_,_)
equation
estr = stringRepresOfExpr(exp);
vtype = Types.typeOfValue(value);
tstr = Types.unparseTypeNoAttr(vtype);
Error.addSourceMessage(Error.IF_CONDITION_TYPE_ERROR, {estr,tstr}, info);
then fail();
end matchcontinue;
end evaluatePartOfIfStatement;
protected function evaluateIfStatementLst
"Evaluates all parts of a if statement
(i.e. a list of exp statements)"
input list<tuple<Absyn.Exp, list<Absyn.AlgorithmItem>>> inTplAbsynExpAbsynAlgorithmItemLstLst;
input SourceInfo info;
algorithm
_ :=
match (inTplAbsynExpAbsynAlgorithmItemLstLst,info)
local
Values.Value value;
Absyn.Exp exp;
list<Absyn.AlgorithmItem> algitemlst;
list<tuple<Absyn.Exp, list<Absyn.AlgorithmItem>>> algrest;
case ({},_) then ();
case (((exp,algitemlst) :: algrest),_)
equation
value = evaluateExpr(exp, info);
evaluatePartOfIfStatement(value, exp, algitemlst, algrest, info);
then ();
end match;
end evaluateIfStatementLst;
protected function evaluateAlgStmtLst
" Evaluates a list of algorithm statements"
input list<Absyn.AlgorithmItem> inAbsynAlgorithmItemLst;
algorithm
for algitem in inAbsynAlgorithmItemLst loop
evaluateAlgStmt(algitem);
end for;
end evaluateAlgStmtLst;
protected function evaluateExpr
" Evaluates an expression and returns its value.
We need to return the symbol table, since the command loadFile()
reads in data to the interactive environment.
Note that this function may fail.
Input: Absyn.Exp - Expression to be evaluated
Output: Values.Value - Resulting value of the expression"
input Absyn.Exp inExp;
input SourceInfo info;
output Values.Value outValue;
algorithm
outValue:=
matchcontinue (inExp,info)
local
FCore.Graph env;
DAE.Exp sexp;
DAE.Properties prop;
Values.Value value;
Absyn.Exp exp;
Absyn.Program p;
FCore.Cache cache;
list<GlobalScript.Variable> vars;
Absyn.ComponentRef cr;
// Special case to lookup fields of records.
// SimulationResult, etc are not in the environment, but it's nice to be able to script them anyway */
case (Absyn.CREF(cr),_)
then getVariableValueLst(AbsynUtil.pathToStringList(AbsynUtil.crefToPath(cr)), SymbolTable.getVars());
case (exp,_)
equation
env = SymbolTable.buildEnv();
(cache,sexp,_) = StaticScript.elabExp(FCore.emptyCache(), env, exp, true, true, DAE.NOPRE(), info);
(_,value) = CevalScript.ceval(cache, env, sexp, true, Absyn.MSG(info),0);
then value;
end matchcontinue;
end evaluateExpr;
protected function stringRepresOfExpr
" This function returns a string representation of an expression. For example expression
33+22 will result in \"55\" and expression: \"my\" + \"string\" will result in \"\"my\"+\"string\"\". "
input Absyn.Exp exp;
output String estr;
protected
FCore.Graph env;
DAE.Exp sexp;
DAE.Properties prop;
algorithm
env := SymbolTable.buildEnv();
(_, sexp, prop) := StaticScript.elabExp(FCore.emptyCache(), env, exp, true, true, DAE.NOPRE(), AbsynUtil.dummyInfo);
(_, sexp, prop) := Ceval.cevalIfConstant(FCore.emptyCache(), env, sexp, prop, true, AbsynUtil.dummyInfo);
estr := ExpressionDump.printExpStr(sexp);
end stringRepresOfExpr;
protected function evaluateExprToStr
" This function is similar to evaluateExpr, with the difference that it returns a string
and that it never fails. If the expression contain errors, an empty string will be returned
and the errors will be stated using Error.mo
Input: Absyn.Exp - Expression to be evaluated
Output: string - The resulting value represented as a string"
input Absyn.Exp inExp;
input SourceInfo info;
output String outString;
algorithm
outString:=
matchcontinue (inExp,info)
local
Values.Value value;
String str;
Absyn.Exp exp;
case (exp,_)
equation
value = evaluateExpr(exp, info);
str = ValuesUtil.valString(value);
then str;
else "";
end matchcontinue;
end evaluateExprToStr;
protected function makeTupleCrefs
input list<Absyn.Exp> inCrefs;
input list<DAE.Type> inTypes;
input FCore.Graph inEnv;
input FCore.Cache inCache;
input SourceInfo inInfo;
output list<DAE.ComponentRef> outCrefs;
algorithm
outCrefs := List.threadMap3(inCrefs, inTypes, makeTupleCref, inEnv, inCache, inInfo);
end makeTupleCrefs;
protected function makeTupleCref
"Translates an Absyn.CREF to a DAE.CREF_IDENT."
input Absyn.Exp inCref;
input DAE.Type inType;
input FCore.Graph inEnv;
input FCore.Cache inCache;
input SourceInfo inInfo;
output DAE.ComponentRef outCref;
algorithm
outCref := match(inCref, inType, inEnv, inCache, inInfo)
local
Absyn.Ident id;
list<Absyn.Subscript> asubs;
list<DAE.Subscript> dsubs;
String str;
case (Absyn.CREF(componentRef = Absyn.CREF_IDENT(id, asubs)), _, _, _, _)
equation
(_, dsubs, _) = Static.elabSubscripts(inCache, inEnv, asubs, true, DAE.NOPRE(), inInfo);
then
DAE.CREF_IDENT(id, inType, dsubs);
else
equation
str = Dump.printExpStr(inCref);
Error.addMessage(Error.INVALID_TUPLE_CONTENT, {str});
then
fail();
end match;
end makeTupleCref;
public function getTypeOfVariable
"Return the type of an interactive variable,
given a list of variables and a variable identifier."
input Absyn.Ident inIdent;
input list<GlobalScript.Variable> inVariableLst;
output DAE.Type outType;
protected
String id;
DAE.Type tp;
algorithm
for var in inVariableLst loop
GlobalScript.IVAR(varIdent = id,type_ = tp) := var;
if stringEq(inIdent, id) then
outType := tp;
return;
end if;
end for;
// did not find a type
fail();
end getTypeOfVariable;
protected function getApiFunctionNameInfo
"Returns the name of the called API function."
input GlobalScript.Statement inStmt;
output String outName;
output SourceInfo outInfo;
algorithm
GlobalScript.IEXP(
exp = Absyn.CALL(function_ = Absyn.CREF_IDENT(name = outName)),
info = outInfo
) := inStmt;
end getApiFunctionNameInfo;
protected function getApiFunctionArgs
"Returns a list of arguments to the function in the interactive statement list."
input GlobalScript.Statement inStmt;
output list<Absyn.Exp> outArgs;
algorithm
outArgs := match(inStmt)
local
list<Absyn.Exp> args;
case GlobalScript.IEXP(exp = Absyn.CALL(functionArgs =
Absyn.FUNCTIONARGS(args = args))) then args;
else {};
end match;
end getApiFunctionArgs;
protected function getApiFunctionNamedArgs
"Returns a list of named arguments to the function in the interactive statement list."
input GlobalScript.Statement inStmt;
output list<Absyn.NamedArg> outArgs;
algorithm
GlobalScript.IEXP(exp = Absyn.CALL(functionArgs = Absyn.FUNCTIONARGS(argNames = outArgs))) := inStmt;
end getApiFunctionNamedArgs;
protected function evaluateGraphicalApi
"Evaluating graphical api.
NOTE: the graphical API is always evaluated with checkModel ON and -d=nogen,noevalfunc ON"
input GlobalScript.Statement inStatement;
input Boolean isPartialInst;
input Boolean flagGen;
input Boolean flagEvalFunc;
input Boolean flagKeepArrays;
output String outResult;
protected
String fn_name;
SourceInfo info;
Boolean failed = false;
algorithm
try
outResult := evaluateGraphicalApi_dispatch(inStatement);
else
failed := true;
end try;
// Reset the flags!
System.setPartialInstantiation(isPartialInst);
FlagsUtil.set(Flags.GEN, flagGen);
FlagsUtil.set(Flags.EVAL_FUNC, flagEvalFunc);
FlagsUtil.setConfigBool(Flags.KEEP_ARRAYS, flagKeepArrays);
if failed then fail(); end if;
end evaluateGraphicalApi;
protected function evaluateGraphicalApi_dispatch
"This function evaluates all primitives in the graphical api."
input GlobalScript.Statement inStatement;
output String outResult;
protected
String fn_name, name;
Absyn.Program old_p, p, p_1;
SCode.Program s;
list<Absyn.Exp> args, expl;
Absyn.ComponentRef cr, cr1, cr2, tp, model_, class_, old_cname, new_cname;
Absyn.ComponentRef crident, subident;
Absyn.Path path;
list<Absyn.NamedArg> nargs;
Integer n, access;
String cmt, variability, causality/*, isField*/;
Absyn.Class cls;
Absyn.Modification mod;
Boolean finalPrefix, flowPrefix, streamPrefix, protected_, repl, dref1, dref2, evalParamAnn;
Boolean addFunctions, graphicsExpMode, warningsAsErrors;
FCore.Graph env;
GraphicEnvCache genv;
Absyn.Exp exp;
list<Absyn.Exp> dimensions;
Absyn.CodeNode cn;
Absyn.Element el;
algorithm
fn_name := getApiFunctionNameInfo(inStatement);
p := SymbolTable.getAbsyn();
args := getApiFunctionArgs(inStatement);
outResult := match(fn_name)
case "setComponentModifierValue"
algorithm
{Absyn.CREF(componentRef = class_),
Absyn.CREF(componentRef = cr),
Absyn.CODE(code = Absyn.C_MODIFICATION(modification = mod))} := args;
(p, outResult) := setComponentModifier(class_, cr, mod, p);
then
outResult;
case "setElementModifierValue"
algorithm
{Absyn.CREF(componentRef = class_),
Absyn.CREF(componentRef = cr),
Absyn.CODE(code = cn)} := args;
mod := match cn
case Absyn.C_MODIFICATION(modification = mod) then mod;
case Absyn.C_ELEMENT(element = el) then fail();
end match;
(p, outResult) := InteractiveUtil.setElementModifier(class_, cr, mod, p);
then
outResult;
case "setParameterValue"
algorithm
{Absyn.CREF(componentRef = class_), Absyn.CREF(componentRef = crident), exp} := args;
(p, outResult) := setParameterValue(class_, crident, exp, p);
then
outResult;
case "setComponentDimensions"
algorithm
{Absyn.CREF(componentRef = class_),
Absyn.CREF(componentRef = cr),
Absyn.ARRAY(dimensions)} := args;
(p, outResult) := setComponentDimensions(class_, cr, dimensions, p);
then
outResult;
case "createModel"
algorithm
{Absyn.CREF(componentRef = cr)} := args;
p := createModel(cr, p);
then
"true";
case "newModel"
algorithm
{Absyn.CREF(componentRef = Absyn.CREF_IDENT(name = name)),
Absyn.CREF(componentRef = cr)} := args;
path := AbsynUtil.crefToPath(cr);
p := InteractiveUtil.updateProgram(
Absyn.PROGRAM({
Absyn.CLASS(name,false,false,false,Absyn.R_MODEL(),AbsynUtil.dummyParts,AbsynUtil.dummyInfo)
}, Absyn.WITHIN(path)), p);
then
"true";
// Not moving this yet as it could break things...
case "deleteClass"
algorithm