pascalabcnet/VisualPascalABCNETLinux/DS/RunManager/RunManager.cs
AlexanderZemlyak 0c29ac92b2
Refactoring of Compiler.cs (#2984)
* Add first comments

* Finish commenting for Compile and CompileUnit

* Write TODO sections

* Add a few clarifications

* splitted some functions from compile

* Written some methods from Compile to functions

* Update variable names

* Refactor - stage 1

Refactor GetUsesSection and IsPossibleNameSpace

* Refactor - stage 2

Rename a few functions and variables

* Correct an inaccuracy

* Added comments, look through CompileUnit

* Rename a few functions and add new comments

* Split CompileUnit to Subfunctions

Add IsUnitCompiled, IsUnitInPCU, InitializeNewUnit, GetSourceCode, GenSyntaxTree, GenUnitDocumentation, CheckDLLDirectiveOnlyForLibraries, MatchErrorsToBadNodes, CheckIfUnitModule, SetUseDLLForSystemUnits,
CompileInterfaceDependencies, CompileCurrentUnitInterface, GetImplementationUsesSection, CompileImplementationDependencies, CompileCurrentUnitImplementation

* Added some TODOs

* Return uses_unit_in original name

Renaming of syntax tree nodes leads to internal compiler errors

* Extract GenerateILCode method

* Add checking if recompilation needed method

Needs to be discussed and revised

* Add functions for catch blocks in Compile

* Extract building semantic tree method

Creating main function to be moved to another class

* Rename UnitsSortedList

* Edit CompileUnitsFromDelayedList method

* Change a few variable names, make CreateRCFile function and add comments

* Make code more "user-friendly"

* Add TODOs 31.11.23

* Create PrebuildSemanticTreeActionsMethod

* Refactor semantic checks section in initialize new unit method

* Refactor Adding standard units to uses method

* Return file_name and compiler_directives original names to avoid internal compilation errors

* Refactor GetReferences Method

* Initial refactoring of IncludeNamespaces function

* Create three more methods and wrap important code in regions

* Add TODO's

* Resolve merge conflicts

* Add returned value to ConstructSyntaxTree method

* Fix UnitsSortedList NotFoundError in PCUWriter

* Workaround commit

* Update PABCSystem after tests' changes

* Rename syntax trees in some methods

* Delete CurrentSyntaxUnit variable

* Revert unnecessary project files changes

* Squashed commit of the following:

commit f4d7599f1a39252feac97bd5391f46dfdc25f6f4
Author: Владислав Крылов <krylov@sfedu.ru>
Date:   Wed Nov 22 11:43:29 2023 +0300

    added links to identarranger

commit 3bd5d33e2b2969884e61a3279ff9c353013b57fe
Author: Владислав Крылов <krylov@sfedu.ru>
Date:   Wed Nov 22 11:43:03 2023 +0300

    Change extension for verybasic to yavb

commit 61294c6e7d405e1c68516cc81d3a109e8a1ee295
Author: MovchanGitHub <92666028+MovchanGitHub@users.noreply.github.com>
Date:   Tue Nov 21 09:33:57 2023 +0300

    Change Program Example

commit 86971488341ed6bf13c39e13a513d7ac0c51c285
Author: MovchanGitHub <92666028+MovchanGitHub@users.noreply.github.com>
Date:   Tue Nov 21 09:28:59 2023 +0300

    Add IndentArranger to Compile

commit 2ce50bbbf9db22c4243b247b870f6935ce206d26
Author: MovchanGitHub <92666028+MovchanGitHub@users.noreply.github.com>
Date:   Fri Nov 17 10:00:31 2023 +0300

    Add Semicolon After Each Statement

commit 796309d340e8d8ba730ff9418fa376f34fb7fd36
Author: MovchanGitHub <92666028+MovchanGitHub@users.noreply.github.com>
Date:   Wed Nov 15 18:49:11 2023 +0300

    Add Alpha Version of Python-style If-statement

commit 5eb88f946fe8254b4f5c5a56ed0a567b3be51227
Merge: ab4ce5b0 0162b637
Author: Владислав Крылов <krylov@sfedu.ru>
Date:   Wed Nov 15 16:54:26 2023 +0300

    Merge branch 'IndentArranger' into VeryBasicLanguage

commit ab4ce5b0e32d42004726e3dc45cc0d8a65e53f56
Author: Владислав Крылов <krylov@sfedu.ru>
Date:   Wed Nov 15 16:53:51 2023 +0300

    Fixes from seminar

commit af74012289d0d08517c13499a2a66cb543fc06d2
Author: Владислав Крылов <krylov@sfedu.ru>
Date:   Sun Nov 12 18:57:29 2023 +0300

    finally working!

    fully implemented compatibility

commit 58a39c313324b468d1eec207ba3f5f6eddf74ef2
Author: Владислав Крылов <krylov@sfedu.ru>
Date:   Sun Nov 12 11:58:16 2023 +0300

    more compatibility with pabc

    Now verybasic statements translate to pascal compiler
    added .bat script for autobuilding verybasic

commit 0162b6376b8fe970704f26213bf9f0f670dfb12e
Author: MovchanGitHub <92666028+MovchanGitHub@users.noreply.github.com>
Date:   Sun Nov 12 10:06:14 2023 +0300

    Update test.txt

commit 1b759ab1cd7ee2ffeb14afff0418ddf0f30b0399
Author: MovchanGitHub <92666028+MovchanGitHub@users.noreply.github.com>
Date:   Sun Nov 12 10:05:36 2023 +0300

    Add Indent and Unindent Keywords to Generated File

commit cabda7f3985651cff2a8740f1a5bdea8fe7ac892
Author: MovchanGitHub <92666028+MovchanGitHub@users.noreply.github.com>
Date:   Fri Nov 10 21:25:52 2023 +0300

    Add Generation of Output File

commit 306f033d0176ab559e3622b8505427dbe2e0e203
Author: MovchanGitHub <92666028+MovchanGitHub@users.noreply.github.com>
Date:   Thu Nov 9 20:42:18 2023 +0300

    Update IndentArranger.sln

commit 60c0ceced1aa3a7d2e33de0facb1126e295f43b5
Author: MovchanGitHub <92666028+MovchanGitHub@users.noreply.github.com>
Date:   Thu Nov 9 20:41:22 2023 +0300

    Add IndentArranger

commit 1f4556c4573dae154fcc167b41ff6ab9e8122136
Author: Владислав Крылов <krylov@sfedu.ru>
Date:   Mon Nov 6 22:48:36 2023 +0300

    Made my own VeryBasicParser project

    Copied some code from SaushkinParser
    Tried to compile it and implement into Pascal
    Doesn't work due to grammatik issue

* Squashed commit of the following:

commit 4e73d9ac3ffef68312f06a74dc83afffcf3ccbee
Author: Владислав Крылов <krylov@sfedu.ru>
Date:   Wed Nov 22 15:08:10 2023 +0300

    Fixed GPPG (i think so at least)

commit e5cfc220828b37fb2f35e565683019716ec3f0ce
Author: Владислав Крылов <krylov@sfedu.ru>
Date:   Wed Nov 22 11:44:27 2023 +0300

    Update Compiler.cs

commit 4698e2e75a5f3b4f523a8bc7733a50e8abb4fca1
Merge: 22aaf2b2 f4d7599f
Author: Владислав Крылов <krylov@sfedu.ru>
Date:   Wed Nov 22 11:43:54 2023 +0300

    Merge branch 'IndentArrangerTemp' into VeryBasicLanguage

commit f4d7599f1a39252feac97bd5391f46dfdc25f6f4
Author: Владислав Крылов <krylov@sfedu.ru>
Date:   Wed Nov 22 11:43:29 2023 +0300

    added links to identarranger

commit 3bd5d33e2b2969884e61a3279ff9c353013b57fe
Author: Владислав Крылов <krylov@sfedu.ru>
Date:   Wed Nov 22 11:43:03 2023 +0300

    Change extension for verybasic to yavb

commit 22aaf2b2508278a9ffce525ffed52419bf72c23f
Merge: c326174f 61294c6e
Author: Владислав Крылов <krylov@sfedu.ru>
Date:   Wed Nov 22 11:26:36 2023 +0300

    Merge branch 'IndentArrangerTemp' into VeryBasicLanguage

commit 61294c6e7d405e1c68516cc81d3a109e8a1ee295
Author: MovchanGitHub <92666028+MovchanGitHub@users.noreply.github.com>
Date:   Tue Nov 21 09:33:57 2023 +0300

    Change Program Example

commit 86971488341ed6bf13c39e13a513d7ac0c51c285
Author: MovchanGitHub <92666028+MovchanGitHub@users.noreply.github.com>
Date:   Tue Nov 21 09:28:59 2023 +0300

    Add IndentArranger to Compile

commit c326174ff5ecccf9c4f76d58aea4653f047af049
Author: Владислав Крылов <krylov@sfedu.ru>
Date:   Sun Nov 19 15:03:19 2023 +0300

    Added UniversalParserHelper and GPPG

    ShiftReduceParser moved to another project
    UniversalParserHelper project added, most of it copied from SaushkinParser

commit 2ce50bbbf9db22c4243b247b870f6935ce206d26
Author: MovchanGitHub <92666028+MovchanGitHub@users.noreply.github.com>
Date:   Fri Nov 17 10:00:31 2023 +0300

    Add Semicolon After Each Statement

commit 796309d340e8d8ba730ff9418fa376f34fb7fd36
Author: MovchanGitHub <92666028+MovchanGitHub@users.noreply.github.com>
Date:   Wed Nov 15 18:49:11 2023 +0300

    Add Alpha Version of Python-style If-statement

commit 5eb88f946fe8254b4f5c5a56ed0a567b3be51227
Merge: ab4ce5b0 0162b637
Author: Владислав Крылов <krylov@sfedu.ru>
Date:   Wed Nov 15 16:54:26 2023 +0300

    Merge branch 'IndentArranger' into VeryBasicLanguage

commit ab4ce5b0e32d42004726e3dc45cc0d8a65e53f56
Author: Владислав Крылов <krylov@sfedu.ru>
Date:   Wed Nov 15 16:53:51 2023 +0300

    Fixes from seminar

commit af74012289d0d08517c13499a2a66cb543fc06d2
Author: Владислав Крылов <krylov@sfedu.ru>
Date:   Sun Nov 12 18:57:29 2023 +0300

    finally working!

    fully implemented compatibility

commit 58a39c313324b468d1eec207ba3f5f6eddf74ef2
Author: Владислав Крылов <krylov@sfedu.ru>
Date:   Sun Nov 12 11:58:16 2023 +0300

    more compatibility with pabc

    Now verybasic statements translate to pascal compiler
    added .bat script for autobuilding verybasic

commit 0162b6376b8fe970704f26213bf9f0f670dfb12e
Author: MovchanGitHub <92666028+MovchanGitHub@users.noreply.github.com>
Date:   Sun Nov 12 10:06:14 2023 +0300

    Update test.txt

commit 1b759ab1cd7ee2ffeb14afff0418ddf0f30b0399
Author: MovchanGitHub <92666028+MovchanGitHub@users.noreply.github.com>
Date:   Sun Nov 12 10:05:36 2023 +0300

    Add Indent and Unindent Keywords to Generated File

commit cabda7f3985651cff2a8740f1a5bdea8fe7ac892
Author: MovchanGitHub <92666028+MovchanGitHub@users.noreply.github.com>
Date:   Fri Nov 10 21:25:52 2023 +0300

    Add Generation of Output File

commit 306f033d0176ab559e3622b8505427dbe2e0e203
Author: MovchanGitHub <92666028+MovchanGitHub@users.noreply.github.com>
Date:   Thu Nov 9 20:42:18 2023 +0300

    Update IndentArranger.sln

commit 60c0ceced1aa3a7d2e33de0facb1126e295f43b5
Author: MovchanGitHub <92666028+MovchanGitHub@users.noreply.github.com>
Date:   Thu Nov 9 20:41:22 2023 +0300

    Add IndentArranger

commit 1f4556c4573dae154fcc167b41ff6ab9e8122136
Author: Владислав Крылов <krylov@sfedu.ru>
Date:   Mon Nov 6 22:48:36 2023 +0300

    Made my own VeryBasicParser project

    Copied some code from SaushkinParser
    Tried to compile it and implement into Pascal
    Doesn't work due to grammatik issue

* Changed GPPG project NET Framework version, added .dll to gitignore

* Adding UniversalParserHelper to project, trying to include VeryBasic

* Managed dependencies and got VeryBasicLanguage to work

* Change extension of a test program

* Rebuild changes

What should be added to .gitignore?

* Fix bug related to err0524_res_unit.pas

* Rebuild Parser

* Change Indent and Unindent tokens

* Add Symbol Table to ParserABC.y

* Change Indent Space Number to 2

* Add While Loop

* Add Some Operations to Parser

* Make Initialization Node at the Beginning of a program

* Create Grammar.txt

* Test program added

* Add ELIF and SyntaxHighlight

* Fix TableSymbol

* Add Division

* Add Method Call

* Add For Loop

* Rename SPython Parser Folder

* Add documented comments for CompileUnit method

* Added Errors to SPython

Added Errors.cs
Removed link to PABCSaushkinParser
Minor fixes

* Create default constructor for SourceContext

* Move null check of currentUnit to upper level in CompileUnit

* Move CreateMainFunction method from Compiler to TreeConverter class

* Add gppg and parserhelper to visualpascalabcnet dependencies

* Updated installer files to include GPPG and UniversalParserHelper

* Rename GPPG to ShiftReduceParser

* Fix ShiftReduceParser project dependencies

* Fix ShiftReduceParserDependencies second iteration

* Workaround commit

* Update PABCSystem after tests' changes

* Refactor ConvertDirectives method

* Get rid of legacy standard modules code

* Return varBeginOffset and beginOffset calculation to Compiler class

Размещение метода в SyntaxTreeToSemanticTreeConverter не целесообразно. В комментарии видимо имелось в виду что-то другое.

* Workaround commit

* Update PABCSystem after tests' changes

* Revert SPython changes

Оставляем только изменения связанные с рефакторингом.

* Update .gitignore

Co-authored-by: Sun Serega <sunserega2@gmail.com>

* Resolve a few Sun Serega treds

* Delete comments in ParsersController.cs

* Replace specific path with path variable in Studio.bat

* Add comment in Studio.bat file and return FileName in CompilerError.cs

* Fix TreeSubsidiary.cs encoding and sectCore.nsh indents

* Return old version of TestRunner.exe

* Rename some variables and polish a few methods

* Uncomment accidentally commented code

* Replace spaces with tabs

* Changed dll name from GPPG

* Revert "Changed dll name from GPPG"

This reverts commit c485cc8cb787809b7e9dfa8a361e75f17ed39893.

* Update .gitignore

* Delete Libraries/ShiftReduceParser.dll

* Delete bin\ShiftReduceParser.dll

* Replace tabs with spaces

* Update encoding in Studio.bat

* Fix bug with PABCrtl excluded files

* Refactor StandardModule class

* Add null checks to make debuging easier

* Delete unnecessary null checks in SymTable.cs

---------

Co-authored-by: Владислав Крылов <krylov@sfedu.ru>
Co-authored-by: MovchanGitHub <92666028+MovchanGitHub@users.noreply.github.com>
Co-authored-by: Sun Serega <sunserega2@gmail.com>
2023-12-18 22:33:27 +03:00

419 lines
19 KiB
C#

// Copyright (c) Ivan Bondarev, Stanislav Mikhalkovich (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using PascalABCCompiler.Errors;
using System.IO;
using System.Diagnostics;
using VisualPascalABCPlugins;
namespace VisualPascalABC
{
public class RunManager
{
Hashtable StartedProcesses = new Hashtable(StringComparer.CurrentCultureIgnoreCase);
Hashtable StartedFiles = new Hashtable();
PascalABCCompiler.EventedStreamReaderList EventedStreamReaderList;
//EventedEventWaitHandleList ReadSignalList;
//Encoding InputEncoding = Encoding.GetEncoding(866);
Encoding InputEncoding = Encoding.UTF8;
string OutputStreamId = "OUT";
string ErrorStreamId = "ERR";
const int idStreamLength = 3;
public enum StreamType { Output, Error };
string RuntimeExceptionDelimer1 = "[EXCEPTION]";
string RuntimeExceptionDelimer2 = "[MESSAGE]";
string RuntimeExceptionDelimer3 = "[STACK]";
string RuntimeExceptionDelimer4 = "[END]";
string RuntimeExceptionAtIdent = " at ";
string RuntimeExceptionLineIdent = ":line ";
string RuntimeExceptionInIdent = " in ";
string RuntimeCommandReadlnSignal = "[READLNSIGNAL]";
string RuntimeCommandCodePage = "[CODEPAGE";
public int Count
{
get { return StartedProcesses.Count; }
}
public delegate void TextRecivedDelegate(string fileName, StreamType streamType, string text);
public event TextRecivedDelegate OutputStringReceived;
public delegate void ReadStringRequestDelegate(string ForId);
ReadStringRequestDelegate ReadStringRequest;
void StringRecived(string id, string Data)
{
System.Threading.Thread.Sleep(50);
string streamId = id.Substring(0, idStreamLength);
id = id.Substring(idStreamLength);
StreamType streamType = StreamType.Output;
if (streamId == ErrorStreamId)
streamType = StreamType.Error;
if (streamType == StreamType.Error && IsSpecialMessage(id, Data))
return;
if (OutputStringReceived != null)
OutputStringReceived(id, streamType, Data);
}
string waitSpecialMessageText = "";
bool IsSpecialMessage(string id, string data)
{
bool res = false;
try
{
if (data == RuntimeCommandReadlnSignal)
{
ReadStringRequest(id);
return true;
}
if (data.IndexOf(RuntimeCommandCodePage)==0)
{
int t = data.IndexOf(']');
int encodingNum = Convert.ToInt32(data.Substring(RuntimeCommandCodePage.Length, t - RuntimeCommandCodePage.Length));
Encoding NewEncoding = Encoding.GetEncoding(encodingNum);
Encoding OldEncoding = EventedStreamReaderList.GetEncoding(OutputStreamId + id);
EventedStreamReaderList.SetEncoding(OutputStreamId + id, NewEncoding);
EventedStreamReaderList.SetEncoding(ErrorStreamId + id, NewEncoding);
if (data.Length > t + 1)
{
data = data.Substring(t + 1);
data = NewEncoding.GetString(OldEncoding.GetBytes(data));
if (data == RuntimeCommandReadlnSignal)
{
ReadStringRequest(id);
return true;
}
res = true;
}
else
return true;
}
if (data == '\n'.ToString())
{
return true;
}
if (data.IndexOf(StackOverflowExceptionText) >= 0)
{
RunnerManagerUnhanledRuntimeException(id, StackOverflowExceptionType, StackOverflowExceptionText, null, new List<StackTraceItem>());
return true;
}
if ((waitSpecialMessageText != "" || (data.Length >= RuntimeExceptionDelimer1.Length && data.Substring(0, RuntimeExceptionDelimer1.Length) == RuntimeExceptionDelimer1)) && RunnerManagerUnhanledRuntimeException != null)
{
if (data.IndexOf(RuntimeExceptionDelimer4) < 0)
{
waitSpecialMessageText += data;
return true;
}
if (waitSpecialMessageText != "")
data = waitSpecialMessageText + data;
int Section1Begin = RuntimeExceptionDelimer1.Length;
int Section1Length = data.IndexOf(RuntimeExceptionDelimer2) - Section1Begin;
int Section2Begin = Section1Begin + Section1Length + RuntimeExceptionDelimer2.Length;
int Section2Length = data.IndexOf(RuntimeExceptionDelimer3) - Section2Begin;
int Section3Begin = Section2Begin + Section2Length + RuntimeExceptionDelimer3.Length;
int Section3Length = data.IndexOf(RuntimeExceptionDelimer4) - Section3Begin;
string ExceptionType = data.Substring(Section1Begin, Section1Length);
string ExceptionMessage = data.Substring(Section2Begin, Section2Length);
string StackTraceData = data.Substring(Section3Begin, Section3Length);
List<StackTraceItem> StackTrace = new List<StackTraceItem>();
string[] delimer = new string[1];
delimer[0] = Environment.NewLine;
string[] StackItemsData = StackTraceData.Split(delimer, StringSplitOptions.RemoveEmptyEntries);
try
{
foreach (string StackItemData in StackItemsData)
{
StackTraceItem StackTraceItem = new StackTraceItem();
string str = StackItemData.TrimStart(' ');
int beg = str.IndexOf(' ');
int end = str.IndexOf(") ");
if (end == -1)
end = str.IndexOf(")");
if (end == -1)
end = str.Length - 1;
StackTraceItem.FunctionName = str.Substring(beg + 1, end - beg);
if (end + 1 < str.Length)
{
str = str.Substring(end + 1);
str = str.TrimStart(' ');
beg = str.IndexOf("in ");
end = str.IndexOf(':');
//end = str.IndexOf(':', end + 1);
if (end == -1)
continue;
StackTraceItem.SourceFileName = str.Substring(beg + 3, end - beg - 3);
//Console.WriteLine(StackTraceItem.SourceFileName);
beg = end;
if (beg > 0)
{
string slnum = str.Substring(beg + 1).Replace(".", "");
StackTraceItem.LineNumber = Convert.ToInt32(slnum);
if (StackTraceItem.LineNumber >= 16777214)
{
StackTraceItem.LineNumber = 0;
StackTraceItem.SourceFileName = null;
}
}
}
StackTrace.Add(StackTraceItem);
}
}
catch (Exception e)
{
StackTraceItem StackTraceItem = new StackTraceItem();
StackTraceItem.FunctionName = "Исключение при формировании стека исключений. Проверьте код RunManager.cs";
StackTrace.Add(StackTraceItem);
//e = e;
}
RunnerManagerUnhanledRuntimeException(id, ExceptionType, ExceptionMessage, StackTraceData, StackTrace);
waitSpecialMessageText = "";
return true;
}
}
catch (Exception e)
{
//OutputStringReceived(id, StreamType.Output,e.ToString());
}
return res;
}
string StackOverflowExceptionText;
string StackOverflowExceptionType;
public RunManager(ReadStringRequestDelegate ReadStringRequest)
{
this.ReadStringRequest = ReadStringRequest;
EventedStreamReaderList = new PascalABCCompiler.EventedStreamReaderList(StringRecived);
StackOverflowExceptionText = PascalABCCompiler.StringResources.Get("!STACK_OVERFLOW_EXCEPTION_TEXT");
StackOverflowExceptionType = "StackOverflowException";
//ReadSignalList = new EventedEventWaitHandleList(ReadSignal);
/*
string name_format = ".\\" + Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName) + "{0}";
string name;
while (MessageQueue == null)
{
name = string.Format(name_format, i);
if (!System.Messaging.MessageQueue.Exists(name))
MessageQueue = new System.Messaging.MessageQueue(name);
i++;
}
*/
}
public event RunnerManagerActionDelegate Exited;
public event RunnerManagerActionDelegate Starting;
public class StackTraceItem
{
public string SourceFileName;
public int LineNumber;
public string FunctionName;
}
public delegate void RunnerManagerUnhanledRuntimeExceptionDelegate(string id, string ExceptionType, string ExceptionMessage, string StackTraceData, List<StackTraceItem> StackTrace);
public event RunnerManagerUnhanledRuntimeExceptionDelegate RunnerManagerUnhanledRuntimeException;
public bool IsRun(string fileName)
{
return StartedProcesses[fileName] != null;
}
public bool IsRun()
{
return StartedProcesses.Count != 0;
}
public void KillAll()
{
Utils.ProcessRunner[] process = new Utils.ProcessRunner[StartedProcesses.Values.Count];
StartedProcesses.Values.CopyTo(process, 0);
foreach (Utils.ProcessRunner pr in process)
{
pr.Kill();
PRunner_ProcessExited(pr,null);
}
}
public void SendText(string FileName, string Text)
{
//messageServer.SendText(file_name, Text);
}
/*private void MessageQueueReceive_Callback(IAsyncResult ar)
{
if (ar.IsCompleted)
{
System.Messaging.Message msg = MessageQueue.EndReceive(ar);
string s = msg.Body as string;
int delimerPos = s.IndexOf(':');
string id = s.Substring(0, delimerPos - 1);
string cmd = s.Substring(delimerPos);
if (OutputLineReceived != null)
OutputLineReceived(id, cmd);
}
if (StartedFiles.Count > 0)
MessageQueue.BeginReceive(TimeSpan.FromSeconds(10), null, MessageQueueReceive_Callback);
else
MessageQueueBeginReceive = false;
}*/
//bool MessageQueueBeginReceive = false;
//Dictionary<string, string> ReadSignalNames = new Dictionary<string, string>();
public Dictionary<string, string> TempBatFiles = new Dictionary<string, string>();
public void Run(string fileName,string args,bool redirectIO,bool redirectErrors, bool RunWithPause, string WorkingDirectory, bool attachDebugger, bool fictive_attach)
{
Utils.ProcessRunner PRunner = new Utils.ProcessRunner();
PRunner.ProcessExited += new EventHandler(PRunner_ProcessExited);
//PRunner.OutputLineReceived += new Utils.LineReceivedEventHandler(PRunner_OutputLineReceived);
PRunner.WorkingDirectory = WorkingDirectory;
StartedProcesses.Add(fileName, PRunner);
StartedFiles.Add(PRunner, fileName);
string ReadSignalName=null;
try
{
PRunner.Start(fileName, args, redirectIO, redirectErrors, RunWithPause, attachDebugger, fictive_attach);
if (Starting != null)
Starting(fileName);
if ((PRunner.TempBatFile != null) && !TempBatFiles.ContainsKey(fileName))
TempBatFiles.Add(fileName, PRunner.TempBatFile);
if (redirectIO)
{
EventedStreamReaderList.Add(PRunner.process.StandardOutput, OutputStreamId + fileName, InputEncoding);
PRunner.process.StandardInput.AutoFlush = true;
}
if (redirectErrors)
{
EventedStreamReaderList.Add(PRunner.process.StandardError, ErrorStreamId + fileName, InputEncoding);
}
}
catch(Exception e)
{
#if DEBUG
File.AppendAllText("logRun.txt", e.Message + Environment.NewLine + e.StackTrace + Environment.NewLine);
#endif
if (!WorkbenchServiceFactory.Workbench.UserOptions.AlwaysAttachDebuggerAtStart)
WorkbenchServiceFactory.Workbench.DebuggerManager.NullProcessHandleIfNeed(fileName);
RemoveFromTables(fileName);
if (Exited != null)
Exited(fileName);
throw; // Это не перехватывается и приводит к вылету оболочки - SSM 22/04/19
}
}
private void Write_Callback(IAsyncResult ar)
{
StreamObject so = (StreamObject)ar.AsyncState;
so.stream.EndWrite(ar);
so.stream.Flush();
}
class StreamObject
{
public Stream stream;
public string text;
public string id;
}
public void WritelnStringToProcess(string id, string data)
{
Utils.ProcessRunner pr = StartedProcesses[id] as Utils.ProcessRunner;
if (pr == null)
{
string files = "";
foreach (string key in StartedProcesses.Keys)
{
files += key + " ";
}
throw new Exception("pr = null: " + id + " Count = " + StartedProcesses.Count + " Files " + files);
}
if (pr.process == null)
throw new Exception("pr.process = null");
if (pr.process.StandardInput == null)
throw new Exception("pr.process.StandardInput = null");
if (pr.process.StandardInput.BaseStream == null)
throw new Exception("pr.process.StandardInput.BaseStream = null");
byte[] buffer = InputEncoding.GetBytes(data + pr.process.StandardInput.NewLine);
StreamObject so=new StreamObject();
so.stream = pr.process.StandardInput.BaseStream;
so.text = data + Environment.NewLine;
so.id = id;
pr.process.StandardInput.BaseStream.BeginWrite(buffer, 0, buffer.Length, Write_Callback, so);
}
public void Run(string fileName, bool redirectIO, string ModeName, bool RunWithPause, string WorkingDirectory, bool attachDebugger, bool fictive_attach)
{
if (ModeName == null)
ModeName = string.Empty;
Run(fileName, ModeName, redirectIO, redirectIO, RunWithPause, WorkingDirectory, attachDebugger, fictive_attach);
}
public void Run(string fileName, bool redirectIO, string ModeName, bool RunWithPause, string WorkingDirectory, string CommandLineArguments, bool attachDebugger, bool fictive_attach)
{
if (ModeName == null)
ModeName = string.Empty;
Run(fileName, ModeName+(string.IsNullOrEmpty(CommandLineArguments)?"":" "+CommandLineArguments), redirectIO, redirectIO, RunWithPause, WorkingDirectory, attachDebugger, fictive_attach);
}
void PRunner_ProcessExited(object sender, EventArgs e)
{
string fileName = (string)StartedFiles[sender];
if (fileName == null) return;//TODO: это ошибочная ситуация
if (!WorkbenchServiceFactory.Workbench.UserOptions.AlwaysAttachDebuggerAtStart)
WorkbenchServiceFactory.Workbench.DebuggerManager.NullProcessHandleIfNeed(fileName);
EventedStreamReaderList.Remove(fileName);
RemoveFromTables(fileName);
if (Exited != null)
Exited(fileName);
}
void RemoveFromTables(string FileName)
{
if (StartedProcesses[FileName] != null)//TODO: это ошибочная ситуация
{
EventedStreamReaderList.Remove(FileName);
StartedFiles.Remove(StartedProcesses[FileName]);
StartedProcesses.Remove(FileName);
}
}
public void Stop(string fileName)
{
EventedStreamReaderList.Remove(fileName);
if (Path.GetExtension((StartedProcesses[fileName] as Utils.ProcessRunner).process.StartInfo.FileName) == ".bat")
{
Process[] ps = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(fileName));
foreach (Process p in ps)
if (Tools.FileNameToLower(p.Modules[0].FileName) == Tools.FileNameToLower(fileName))
{
p.Kill();
p.Close();
p.Dispose();
break;
}
}
(StartedProcesses[fileName] as Utils.ProcessRunner).Kill();
if (!WorkbenchServiceFactory.Workbench.UserOptions.AlwaysAttachDebuggerAtStart)
WorkbenchServiceFactory.Workbench.DebuggerManager.NullProcessHandleIfNeed(fileName);
WorkbenchServiceFactory.DebuggerManager.EndDebuggerSession();
RemoveFromTables(fileName);
if (Exited != null)
Exited(fileName);
}
}
}