/
Main.mo
946 lines (860 loc) · 31.5 KB
/
Main.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
/*
* 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 Main
" file: Main.mo
package: Main
description: Modelica main program
This is the main program in the Modelica specification.
It either translates a file given as a command line argument
or starts a server loop communicating through CORBA or sockets
(The Win32 implementation only implements CORBA)"
protected
import Absyn;
import BackendDAE;
import BackendDAECreate;
import BackendDAEUtil;
import CevalScript;
import CevalScriptBackend;
import ClockIndexes;
import Config;
import Corba;
import DAE;
import DAEDump;
import DAEUtil;
import Debug;
import Dump;
import DumpGraphviz;
import FCore;
import FGraph;
import FGraphStream;
import Error;
import ErrorExt;
import Flags;
import GC;
import Global;
import GlobalScript;
import GlobalScriptUtil;
import Interactive;
import List;
import Parser;
import Print;
import Settings;
import SimCode;
import SimCodeMain;
import ExecStat.{execStat,execStatReset};
import Socket;
import StackOverflow;
import System;
import TplMain;
import Util;
import ZeroMQ;
protected function serverLoop
"This function is the main loop of the server listening
to a port which recieves modelica expressions."
input Boolean cont;
input Integer inInteger;
input GlobalScript.SymbolTable inInteractiveSymbolTable;
output GlobalScript.SymbolTable outInteractiveSymbolTable;
algorithm
outInteractiveSymbolTable := match (cont,inInteger,inInteractiveSymbolTable)
local
Boolean b;
String str,replystr;
GlobalScript.SymbolTable newsymb,ressymb,isymb;
Integer shandle;
case (false,_,isymb) then isymb;
case (_,-1,_) then fail();
case (_,shandle,isymb)
equation
str = Socket.handlerequest(shandle);
if Flags.isSet(Flags.INTERACTIVE_DUMP) then
Debug.trace("------- Recieved Data from client -----\n");
Debug.trace(str);
Debug.trace("------- End recieved Data-----\n");
end if;
(b,replystr,newsymb) = handleCommand(str, isymb) "Print.clearErrorBuf &" ;
replystr = if b then replystr else "quit requested, shutting server down\n";
Socket.sendreply(shandle, replystr);
if not b then
Socket.close(shandle);
Socket.cleanup();
end if;
then serverLoop(b, shandle, newsymb);
end match;
end serverLoop;
protected function serverLoopZMQ
"This function is the main loop of the ZeroMQ server listening
to a port which recieves modelica expressions."
input Boolean cont;
input Option<Integer> inZMQSocket;
input GlobalScript.SymbolTable inInteractiveSymbolTable;
output GlobalScript.SymbolTable outInteractiveSymbolTable;
algorithm
outInteractiveSymbolTable := match (cont,inZMQSocket,inInteractiveSymbolTable)
local
Boolean b;
String str,replystr;
GlobalScript.SymbolTable newsymb,ressymb,isymb;
Option<Integer> zmqSocket;
case (false,_,isymb) then isymb;
case (_,SOME(0),_) then fail();
case (_,zmqSocket,isymb)
equation
str = ZeroMQ.handleRequest(zmqSocket);
if Flags.isSet(Flags.INTERACTIVE_DUMP) then
Debug.trace("------- Recieved Data from client -----\n");
Debug.trace(str);
Debug.trace("------- End recieved Data-----\n");
end if;
(b,replystr,newsymb) = handleCommand(str, isymb) "Print.clearErrorBuf &" ;
replystr = if b then replystr else "quit requested, shutting server down\n";
ZeroMQ.sendReply(zmqSocket, replystr);
if not b then
ZeroMQ.close(zmqSocket);
end if;
then serverLoopZMQ(b, zmqSocket, newsymb);
end match;
end serverLoopZMQ;
protected function makeDebugResult
input Flags.DebugFlag inFlag;
input String res;
output String res_1;
algorithm
res_1 := matchcontinue (inFlag,res)
local
String debugstr,res_with_debug,flagstr;
case (Flags.DEBUG_FLAG(name = flagstr),_)
equation
true = Flags.isSet(inFlag);
debugstr = Print.getString();
res_with_debug = stringAppendList({res,"\n---DEBUG(",flagstr,")---\n",debugstr,"\n---/DEBUG(",flagstr,")---\n"});
then res_with_debug;
else res;
end matchcontinue;
end makeDebugResult;
protected function parseCommand
"Helper function to handleCommand. First tries to parse the given command as a
list of statements, and if that fails tries to parse it as a collection of
classes. Returns either GlobalScript.Statements or Absyn.Program based on
which parser succeeds, or neither if a parser error occured."
input String inCommand;
output Option<GlobalScript.Statements> outStatements;
output Option<Absyn.Program> outProgram;
algorithm
(outStatements, outProgram) := matchcontinue(inCommand)
local
GlobalScript.Statements stmts;
Absyn.Program prog;
String str;
case (_)
equation
ErrorExt.setCheckpoint("parsestring");
stmts = Parser.parsestringexp(inCommand, "<interactive>");
ErrorExt.delCheckpoint("parsestring");
then
(SOME(stmts), NONE());
case (_)
equation
ErrorExt.rollBack("parsestring");
prog = Parser.parsestring(inCommand, "<interactive>");
then
(NONE(), SOME(prog));
else (NONE(), NONE());
end matchcontinue;
end parseCommand;
public function handleCommand
"This function handles the commands in form of strings send to the server.
If the command is quit, the function returns false, otherwise it sends the
string to the parse function and returns true."
input String inCommand;
input GlobalScript.SymbolTable inSymbolTable;
output Boolean outContinue;
output String outResult;
output GlobalScript.SymbolTable outSymbolTable = inSymbolTable;
protected
Option<GlobalScript.Statements> stmts;
Option<Absyn.Program> prog;
GlobalScript.SymbolTable st;
algorithm
Print.clearBuf();
if Util.strncmp("quit()", inCommand, 6) then
outContinue := false;
outResult := "Ok\n";
else
outContinue := true;
(stmts, prog) := parseCommand(inCommand);
(outResult, outSymbolTable) := handleCommand2(stmts, prog, inCommand, outSymbolTable);
outResult := makeDebugResult(Flags.DUMP, outResult);
outResult := makeDebugResult(Flags.DUMP_GRAPHVIZ, outResult);
end if;
end handleCommand;
protected function handleCommand2
input Option<GlobalScript.Statements> inStatements;
input Option<Absyn.Program> inProgram;
input String inCommand;
input GlobalScript.SymbolTable inSymbolTable;
output String outResult;
output GlobalScript.SymbolTable outSymbolTable;
algorithm
(outResult, outSymbolTable) :=
matchcontinue(inStatements, inProgram, inSymbolTable)
local
GlobalScript.Statements stmts;
Absyn.Program prog, prog2, ast;
String result;
GlobalScript.SymbolTable st;
list<GlobalScript.Variable> vars;
// Interactively evaluate an algorithm statement or expression.
case (SOME(stmts), NONE(), _)
equation
(result, st) = Interactive.evaluate(stmts, inSymbolTable, false);
then (result, st);
// Add a class or function to the interactive symbol table.
case (NONE(), SOME(prog), GlobalScript.SYMBOLTABLE(ast = ast, lstVarVal = vars))
equation
prog2 = Interactive.addScope(prog, vars);
prog2 = Interactive.updateProgram(prog2, ast);
if Flags.isSet(Flags.DUMP) then
Debug.trace("\n--------------- Parsed program ---------------\n");
Dump.dump(prog2);
end if;
if Flags.isSet(Flags.DUMP_GRAPHVIZ) then
DumpGraphviz.dump(prog2);
end if;
result = makeClassDefResult(prog) "Return vector of toplevel classnames.";
st = GlobalScriptUtil.setSymbolTableAST(inSymbolTable, prog2);
then (result, st);
// A parser error occured in parseCommand, display the error message. This
// is handled here instead of in parseCommand, since parseCommand does not
// return a result string.
case (NONE(), NONE(), _)
equation
Print.printBuf("Error occurred building AST\n");
result = Print.getString();
result = stringAppend(result, "Syntax Error\n");
result = stringAppend(result, Error.printMessagesStr(false));
then (result, inSymbolTable);
// A non-parser error occured, display the error message.
case (_, _, _)
equation
true = Util.isSome(inStatements) or Util.isSome(inProgram);
result = Error.printMessagesStr(false);
then (result, inSymbolTable);
else
equation
true = Util.isSome(inStatements) or Util.isSome(inProgram);
Error.addMessage(Error.STACK_OVERFLOW, {inCommand});
then ("", inSymbolTable);
end matchcontinue;
end handleCommand2;
protected function makeClassDefResult
"creates a list of classes of the program to be returned from evaluate"
input Absyn.Program p;
output String res;
algorithm
res := match(p)
local
list<Absyn.Path> names;
Absyn.Path scope;
list<Absyn.Class> cls;
case(Absyn.PROGRAM(classes=cls,within_=Absyn.WITHIN(scope)))
equation
names = List.map(cls,Absyn.className);
names = List.map1(names,Absyn.joinPaths,scope);
res = "{" + stringDelimitList(list(Absyn.pathString(n) for n in names),",") + "}\n";
then res;
case(Absyn.PROGRAM(classes=cls,within_=Absyn.TOP()))
equation
names = List.map(cls,Absyn.className);
res = "{" + stringDelimitList(list(Absyn.pathString(n) for n in names),",") + "}\n";
then res;
end match;
end makeClassDefResult;
protected function isModelicaFile
"Succeeds if filename ends with .mo or .mof"
input String inFilename;
output Boolean outIsModelicaFile;
protected
list<String> lst;
String file_ext;
algorithm
lst := System.strtok(inFilename, ".");
if listEmpty(lst) then
outIsModelicaFile := false;
else
file_ext := List.last(lst);
outIsModelicaFile := file_ext == "mo" or file_ext == "mof";
end if;
end isModelicaFile;
protected function isEmptyOrFirstIsModelicaFile
input list<String> libs;
algorithm
_ := match libs
local
String f;
case {} then ();
case f::_ equation true = isModelicaFile(f); then ();
end match;
end isEmptyOrFirstIsModelicaFile;
protected function isFlatModelicaFile
"Succeeds if filename ends with .mof"
input String filename;
protected
list<String> lst;
String last;
algorithm
lst := System.strtok(filename, ".");
last :: _ := listReverse(lst);
true := stringEq(last, "mof");
end isFlatModelicaFile;
protected function isModelicaScriptFile
"Succeeds if filname end with .mos"
input String filename;
protected
list<String> lst;
String last;
algorithm
true := System.regularFileExists(filename);
lst := System.strtok(filename, ".");
last :: _ := listReverse(lst);
true := stringEq(last, "mos");
end isModelicaScriptFile;
protected function isCodegenTemplateFile
"Succeeds if filname end with .tpl"
input String filename;
protected
list<String> lst;
String last;
algorithm
lst := System.strtok(filename, ".");
last :: _ := listReverse(lst);
true := stringEq(last, "tpl");
end isCodegenTemplateFile;
protected function showErrors
input String errorString;
input String errorMessages;
algorithm
if errorString <> "" then
print(errorString); print("\n");
end if;
if errorMessages <> "" then
print(errorMessages); print("\n");
end if;
end showErrors;
protected function loadLib
input String inLib;
input GlobalScript.SymbolTable inSymTab;
output GlobalScript.SymbolTable outSymTab;
protected
Boolean is_modelica_file;
algorithm
is_modelica_file := isModelicaFile(inLib);
outSymTab := matchcontinue(is_modelica_file)
local
String lib, mp;
list<String> rest;
Absyn.Program pnew, p;
list<GlobalScript.InstantiatedClass> ic;
list<GlobalScript.Variable> iv;
list<GlobalScript.CompiledCFunction> cf;
list<GlobalScript.LoadedFile> lf;
GlobalScript.SymbolTable st, newst;
Absyn.Path path;
// A .mo-file.
case true
equation
pnew = Parser.parse(inLib, "UTF-8");
p = GlobalScriptUtil.getSymbolTableAST(inSymTab);
pnew = Interactive.mergeProgram(pnew, p);
newst = GlobalScriptUtil.setSymbolTableAST(inSymTab, pnew);
then
newst;
// some libs present
case false
equation
path = Absyn.stringPath(inLib);
mp = Settings.getModelicaPath(Config.getRunningTestsuite());
p = GlobalScriptUtil.getSymbolTableAST(inSymTab);
(pnew, true) = CevalScript.loadModel({(path, {"default"})}, mp, p, true, true, true, false);
newst = GlobalScriptUtil.setSymbolTableAST(inSymTab, pnew);
then
newst;
// problem with the libs, ignore!
case false
equation
Print.printErrorBuf("Failed to load library: " + inLib + "!\n");
then
fail();
case true
equation
Print.printErrorBuf("Failed to parse file: " + inLib + "!\n");
then
fail();
end matchcontinue;
end loadLib;
protected function translateFile
"This function invokes the translator on a source file. The argument should be
a list with a single file name, with the rest of the list being an optional
list of libraries and .mo-files if the file is a .mo-file"
input list<String> inStringLst;
algorithm
_ := matchcontinue (inStringLst)
local
Absyn.Program p, pLibs;
DAE.DAElist d;
String s,str,f;
list<String> libs;
Absyn.Path cname;
Boolean silent,notsilent;
GlobalScript.Statements stmts;
GlobalScript.SymbolTable newst, st;
FCore.Cache cache;
FCore.Graph env;
DAE.FunctionTree funcs;
list<Absyn.Class> cls;
// A .mo-file, followed by an optional list of extra .mo-files and libraries.
// The last class in the first file will be instantiated.
case (libs)
equation
//print("Class to instantiate: " + Config.classToInstantiate() + "\n");
isEmptyOrFirstIsModelicaFile(libs);
execStatReset();
// Parse libraries and extra mo-files that might have been given at the command line.
GlobalScript.SYMBOLTABLE(ast = p) = List.fold(libs, loadLib, GlobalScript.emptySymboltable);
// Show any errors that occured during parsing.
showErrors(Print.getErrorString(), ErrorExt.printMessagesStr(false));
if Flags.isSet(Flags.DUMP) then
Debug.trace("\n--------------- Parsed program ---------------\n");
Dump.dump(p);
print(Print.getString());
end if;
if Flags.isSet(Flags.DUMP_GRAPHVIZ) then
DumpGraphviz.dump(p);
end if;
execStat("Parsed file");
// Instantiate the program.
(cache, env, d, cname) = instantiate(p);
d = if Flags.isSet(Flags.TRANSFORMS_BEFORE_DUMP) then DAEUtil.transformationsBeforeBackend(cache,env,d) else d;
funcs = FCore.getFunctionTree(cache);
Print.clearBuf();
execStat("Transformations before Dump");
s = if Config.silent() then "" else DAEDump.dumpStr(d, funcs);
execStat("DAEDump done");
Print.printBuf(s);
if Flags.isSet(Flags.DAE_DUMP_GRAPHV) then
DAEDump.dumpGraphviz(d);
end if;
execStat("Misc Dump");
// Do any transformations required before going into code generation, e.g. if-equations to expressions.
d = if boolNot(Flags.isSet(Flags.TRANSFORMS_BEFORE_DUMP)) then DAEUtil.transformationsBeforeBackend(cache,env,d) else d;
if not Config.silent() then
print(Print.getString());
end if;
execStat("Transformations before backend");
// Run the backend.
optimizeDae(cache, env, d, p, cname);
// Show any errors or warnings if there are any!
showErrors(Print.getErrorString(), ErrorExt.printMessagesStr(false));
then ();
/* Modelica script file .mos */
case (f::libs)
equation
isModelicaScriptFile(f);
// loading possible libraries given at the command line
st = List.fold(libs, loadLib, GlobalScript.emptySymboltable);
//System.startTimer();
//print("\nParseExp");
// parse our algorithm given in the script
stmts = Parser.parseexp(f);
//System.stopTimer();
//print("\nParseExp: " + realString(System.getTimerIntervalTime()));
// are there any errors?
// show errors if there are any
showErrors(Print.getErrorString(), ErrorExt.printMessagesStr(false));
// evaluate statements and print the result to stdout directly
_ = Interactive.evaluateToStdOut(stmts, st, true);
then
();
case {f} /* A template file .tpl (in the Susan language)*/
equation
isCodegenTemplateFile(f);
TplMain.main(f);
then
();
// deal with problems
case (f::_)
algorithm
if System.regularFileExists(f) then
print("Error processing file: ");
else
print(System.gettext("File does not exist: "));
end if;
print(f); print("\n");
// show errors if there are any
showErrors(Print.getErrorString(), ErrorExt.printMessagesStr(false));
then
fail();
end matchcontinue;
end translateFile;
protected function instantiate
"Translates the Absyn.Program to SCode and instantiates either a given class
specified by the +i flag on the command line, or the last class in the
program if no class was specified."
input Absyn.Program program;
output FCore.Cache cache;
output FCore.Graph env;
output DAE.DAElist dae;
output Absyn.Path cname;
protected
String cls;
GlobalScript.SymbolTable st;
algorithm
cls := Config.classToInstantiate();
// If no class was explicitly specified, instantiate the last class in the
// program. Otherwise, instantiate the given class name.
cname := if stringEmpty(cls) then Absyn.lastClassname(program) else Absyn.stringPath(cls);
st := GlobalScriptUtil.setSymbolTableAST(GlobalScript.emptySymboltable, program);
(cache, env, dae) := CevalScriptBackend.runFrontEnd(FCore.emptyCache(), FGraph.empty(), cname, st, true);
end instantiate;
protected function optimizeDae
"Run the backend. Used for both parallization and for normal execution."
input FCore.Cache inCache;
input FCore.Graph inEnv;
input DAE.DAElist dae;
input Absyn.Program ap;
input Absyn.Path inClassName;
protected
BackendDAE.ExtraInfo info;
BackendDAE.BackendDAE dlow;
BackendDAE.BackendDAE initDAE;
Option<BackendDAE.BackendDAE> initDAE_lambda0;
Option<BackendDAE.InlineData> inlineData;
list<BackendDAE.Equation> removedInitialEquationLst;
algorithm
if Config.simulationCg() then
info := BackendDAE.EXTRA_INFO(DAEUtil.daeDescription(dae), Absyn.pathString(inClassName));
dlow := BackendDAECreate.lower(dae, inCache, inEnv, info);
(dlow, initDAE, initDAE_lambda0, inlineData, removedInitialEquationLst) := BackendDAEUtil.getSolvedSystem(dlow, "");
simcodegen(dlow, initDAE, initDAE_lambda0, inlineData, removedInitialEquationLst, inClassName, ap);
end if;
end optimizeDae;
protected function simcodegen "
Genereates simulation code using the SimCode module"
input BackendDAE.BackendDAE inBackendDAE;
input BackendDAE.BackendDAE inInitDAE;
input Option<BackendDAE.BackendDAE> inInitDAE_lambda0;
input Option<BackendDAE.InlineData> inInlineData;
input list<BackendDAE.Equation> inRemovedInitialEquationLst;
input Absyn.Path inClassName;
input Absyn.Program inProgram;
protected
String cname;
SimCode.SimulationSettings sim_settings;
Integer intervals;
algorithm
if Config.simulationCg() then
Print.clearErrorBuf();
Print.clearBuf();
cname := Absyn.pathString(inClassName);
// If accepting parModelica create a slightly different default settings.
// Temporary solution for now since Intel OpenCL dll calls hang.
sim_settings := if Config.acceptParModelicaGrammar() then
SimCodeMain.createSimulationSettings(0.0, 1.0, 1, 1e-6, "dassl", "", "plt", ".*", "") else
SimCodeMain.createSimulationSettings(0.0, 1.0, 500, 1e-6, "dassl", "", "mat", ".*", "");
System.realtimeTock(ClockIndexes.RT_CLOCK_BACKEND); // Is this necessary?
SimCodeMain.generateModelCode(inBackendDAE, inInitDAE, inInitDAE_lambda0, inInlineData, inRemovedInitialEquationLst, inProgram, inClassName, cname, SOME(sim_settings), Absyn.FUNCTIONARGS({}, {}));
execStat("Codegen Done");
end if;
end simcodegen;
protected function interactivemode
"Initiate the interactive mode using socket communication."
input GlobalScript.SymbolTable symbolTable;
algorithm
serverLoop(true, Socket.waitforconnect(29500), symbolTable);
end interactivemode;
protected function interactivemodeCorba
"Initiate the interactive mode using corba communication."
input GlobalScript.SymbolTable inArguments;
algorithm
try
Corba.initialize();
serverLoopCorba(inArguments);
else
Print.printBuf("Failed to initialize Corba! Is another OMC already running?\n");
Print.printBuf("Exiting!\n");
end try;
end interactivemodeCorba;
protected function interactivemodeZMQ
"Initiate the interactive mode using ZMQ communication."
input GlobalScript.SymbolTable symbolTable;
algorithm
serverLoopZMQ(true, ZeroMQ.initialize(), symbolTable);
end interactivemodeZMQ;
protected function serverLoopCorba
"This function is the main loop of the server for a CORBA impl."
input GlobalScript.SymbolTable inSettings;
output GlobalScript.SymbolTable outSettings;
protected
String str, reply_str;
GlobalScript.SymbolTable settings;
Boolean cont;
algorithm
str := Corba.waitForCommand();
Print.clearBuf();
(cont, reply_str, settings) := handleCommand(str, inSettings);
if cont then
Corba.sendreply(reply_str);
outSettings := serverLoopCorba(settings);
else
Corba.sendreply("quit requested, shutting server down\n");
Corba.close();
outSettings := inSettings;
end if;
end serverLoopCorba;
public function readSettings
" author: x02lucpo
Checks if 'settings.mos' exist and uses handleCommand with runScript(...) to execute it.
Checks if '-s <file>.mos' has been
returns GlobalScript.SymbolTable which is used in the rest of the loop"
input list<String> inArguments;
output GlobalScript.SymbolTable outSettings;
protected
String settings_file;
algorithm
settings_file := Util.flagValue("-s", inArguments);
if settings_file == "" then
outSettings := GlobalScript.emptySymboltable;
else
settings_file := System.trim(settings_file, " \"");
outSettings := readSettingsFile(settings_file, GlobalScript.emptySymboltable);
end if;
end readSettings;
protected function readSettingsFile
input String filePath;
input GlobalScript.SymbolTable inSettings;
output GlobalScript.SymbolTable outSettings;
protected
String command;
algorithm
if System.regularFileExists(filePath) then
command := "runScript(\"" + filePath + "\")";
(_, _, outSettings) := handleCommand(command, inSettings);
else
outSettings := inSettings;
end if;
end readSettingsFile;
public function setWindowsPaths
"@author: adrpo
set the windows paths for MinGW.
do some checks on where needed things are present.
BIG WARNING: if MinGW gcc version from OMDev or OpenModelica/MinGW
changes you will need to change here!"
input String inOMHome;
algorithm
_ := match(inOMHome)
local
String oldPath, newPath, omHome, omdevPath, mingwDir, binDir, libBinDir, msysBinDir;
Boolean hasBinDir, hasLibBinDir;
// check if we have OMDEV set
case (omHome)
equation
System.setEnv("OPENMODELICAHOME",omHome,true);
omdevPath = Util.makeValueOrDefault(System.readEnv,"OMDEV","");
mingwDir = System.openModelicaPlatform();
// if we don't have something in OMDEV use OMHOME
if stringEq(omdevPath, "") then
omdevPath = omHome;
end if;
msysBinDir = omdevPath + "\\tools\\msys\\usr\\bin";
binDir = omdevPath + "\\tools\\msys\\" + mingwDir + "\\bin";
libBinDir = omdevPath + "\\tools\\msys\\" + mingwDir + "\\lib\\gcc\\" + System.gccDumpMachine() + "\\" + System.gccVersion();
// do we have bin and lib bin?
hasBinDir = System.directoryExists(binDir);
hasLibBinDir = System.directoryExists(libBinDir);
if hasBinDir and hasLibBinDir
then
oldPath = System.readEnv("PATH");
newPath = stringAppendList({omHome, "\\bin;", omHome, "\\lib;", binDir + ";", libBinDir + ";", msysBinDir + ";"});
newPath = System.stringReplace(newPath, "/", "\\") + oldPath;
// print("Path set: " + newPath + "\n");
System.setEnv("PATH",newPath,true);
else
// do not display anything if -d=disableWindowsPathCheckWarning
if not Flags.isSet(Flags.DISABLE_WINDOWS_PATH_CHECK_WARNING) then
print("We could not find some needed MINGW paths in $OPENMODELICAHOME or $OMDEV. Searched for paths:\n");
print("\t" + binDir + (if hasBinDir then " [found] " else " [not found] ") + "\n");
print("\t" + libBinDir + (if hasLibBinDir then " [found] " else " [not found] ") + "\n");
end if;
end if;
then ();
end match;
end setWindowsPaths;
protected function setDefaultCC "Reads the environment variable CC to change the default CC"
algorithm
try
System.setCCompiler(System.readEnv("CC"));
else
end try;
end setDefaultCC;
public function init
input list<String> args;
output list<String> args_1;
algorithm
// set glib G_SLICE to always-malloc as is rummored to be better for Boehm GC
System.setEnv("G_SLICE", "always-malloc", true);
// call GC_init() the first thing we do!
System.initGarbageCollector();
// Experimentally found to make the testsuite pass on asap.openmodelica.org.
// 150M for Windows, 300M for others makes the GC try to unmap less and so it crashes less.
// Disabling unmap is another alternative that seems to work well (but could cause the memory consumption to not be released, and requires manually calling collect and unmap
if true then
GC.setForceUnmapOnGcollect(if System.os() == "Windows_NT" then true else false);
else
GC.expandHeap(if System.os() == "Windows_NT"
then 1024*1024*150
else 1024*1024*300);
end if;
Global.initialize();
ErrorExt.registerModelicaFormatError();
System.realtimeTick(ClockIndexes.RT_CLOCK_SIMULATE_TOTAL);
args_1 := Flags.new(args);
System.gettextInit(if Config.getRunningTestsuite() then "C" else Flags.getConfigString(Flags.LOCALE_FLAG));
setDefaultCC();
end init;
public function main
"This is the main function that the MetaModelica Compiler (MMC) runtime system calls to
start the translation."
input list<String> args;
protected
list<String> args_1;
GC.ProfStats stats;
Integer seconds;
algorithm
try
try
args_1 := init(args);
if Flags.isSet(Flags.GC_PROF) then
print(GC.profStatsStr(GC.getProfStats(), head="GC stats after initialization:") + "\n");
end if;
seconds := Flags.getConfigInt(Flags.ALARM);
if seconds > 0 then
System.alarm(seconds);
end if;
main2(args_1);
else
ErrorExt.clearMessages();
failure(_ := Flags.new(args));
print(ErrorExt.printMessagesStr(false)); print("\n");
fail();
end try;
if Flags.isSet(Flags.GC_PROF) then
print(GC.profStatsStr(GC.getProfStats(), head="GC stats at end of program:") + "\n");
end if;
else
print("Stack overflow detected and was not caught.\nSend us a bug report at https://trac.openmodelica.org/OpenModelica/newticket\n Include the following trace:\n");
for s in StackOverflow.readableStacktraceMessages() loop
print(s);
print("\n");
end for;
end try annotation(__OpenModelica_stackOverflowCheckpoint=true);
end main;
protected function main2
"This is the main function that the MetaModelica Compiler (MMC) runtime system calls to
start the translation."
input list<String> args;
protected
String interactiveMode;
algorithm
// Version requested using --version.
if Config.versionRequest() then
print(Settings.getVersionNr() + "\n");
return;
end if;
// Don't allow running omc as root due to security risks.
interactiveMode := Flags.getConfigString(Flags.INTERACTIVE);
if System.userIsRoot() and (Flags.isSet(Flags.INTERACTIVE_TCP) or Flags.isSet(Flags.INTERACTIVE_CORBA)
or interactiveMode == "corba" or interactiveMode == "tcp" or interactiveMode == "zmq") then
Error.addMessage(Error.ROOT_USER_INTERACTIVE, {});
print(ErrorExt.printMessagesStr(false));
fail();
end if;
// Setup mingw path only once
// adrpo: NEVER MOVE THIS CASE FROM HERE OR PUT ANY OTHER CASES BEFORE IT
// without asking Adrian.Pop@liu.se
if System.os() == "Windows_NT" then
setWindowsPaths(Settings.getInstallationDirectoryPath());
end if;
try
Settings.getInstallationDirectoryPath();
if Flags.isSet(Flags.INTERACTIVE_TCP) then
print("The flag -d=interactive is depreciated. Please use --interactive=tcp\n");
interactivemode(readSettings(args));
elseif interactiveMode == "tcp" then
interactivemode(readSettings(args));
elseif Flags.isSet(Flags.INTERACTIVE_CORBA) then
print("The flag -d=interactiveCorba is depreciated. Please use --interactive=corba\n");
interactivemodeCorba(readSettings(args));
elseif interactiveMode == "corba" then
interactivemodeCorba(readSettings(args));
elseif interactiveMode == "zmq" then
interactivemodeZMQ(readSettings(args));
else // No interactive flag given, try to flatten the file.
readSettings(args);
FGraphStream.start();
translateFile(args);
FGraphStream.finish();
end if;
else // Something went wrong, print an appropriate error.
// OMC called with no arguments, print usage information and quit.
if listEmpty(args) and Config.classToInstantiate()=="" then
if not Config.helpRequest() then
print(Flags.printUsage());
end if;
return;
end if;
try
Settings.getInstallationDirectoryPath();
print("# Error encountered! Exiting...\n");
print("# Please check the error message and the flags.\n");
Print.printBuf("\n\n----\n\nError buffer:\n\n");
print(Print.getErrorString());
print(ErrorExt.printMessagesStr(false)); print("\n");
FGraphStream.finish();
else
print("Error: OPENMODELICAHOME was not set.\n");
print(" Read the documentation for instructions on how to set it properly.\n");
print(" Most OpenModelica release distributions have scripts that set OPENMODELICAHOME for you.\n\n");
end try;
fail();
end try;
end main2;
annotation(__OpenModelica_Interface="backend");
end Main;