From e28c03d9905c217eee4da2379fbfec8c190546ea Mon Sep 17 00:00:00 2001 From: Sergey Batanov Date: Tue, 4 Oct 2016 13:44:43 +0300 Subject: [PATCH 001/230] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B0=20bash-=D0=BF=D0=BE=D0=B4=D1=81=D0=BA=D0=B0?= =?UTF-8?q?=D0=B7=D0=BA=D0=B0=20=D0=B4=D0=BB=D1=8F=20opm.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- install/builders/deb/build.sh | 2 ++ install/builders/deb/oscript-opm-completion | 11 +++++++++++ install/builders/deb/settings/dirs | 1 + 3 files changed, 14 insertions(+) create mode 100644 install/builders/deb/oscript-opm-completion diff --git a/install/builders/deb/build.sh b/install/builders/deb/build.sh index 197b5cf3e..2453ec4c6 100755 --- a/install/builders/deb/build.sh +++ b/install/builders/deb/build.sh @@ -15,6 +15,7 @@ mkdir -p $DSTPATH/usr/bin mkdir -p $DSTPATH/usr/share/oscript/lib mkdir -p $DSTPATH/usr/share/oscript/bin mkdir -p $DSTPATH/etc +mkdir -p $DSTPATH/etc/bash_completion.d cp ${BUILDERROOT}settings/dirs $DSTPATH/DEBIAN/ cat ${BUILDERROOT}settings/control | sed -r "s/VERSION/$VERSION/g" > $DSTPATH/DEBIAN/control @@ -23,6 +24,7 @@ cp ${BINPATH}*.dll $DSTPATH/usr/share/oscript/bin cp ${BUILDERROOT}oscript $DSTPATH/usr/bin cp ${BUILDERROOT}oscript-cgi $DSTPATH/usr/bin cp ${BUILDERROOT}oscript-opm $DSTPATH/usr/bin +cp ${BUILDERROOT}oscript-opm-completion $DSTPATH/etc/bash_completion.d cp -r ${SRCPATH}/lib/* $DSTPATH/usr/share/oscript/lib cp ${BINPATH}/oscript.cfg $DSTPATH/etc diff --git a/install/builders/deb/oscript-opm-completion b/install/builders/deb/oscript-opm-completion new file mode 100644 index 000000000..9b1f647b8 --- /dev/null +++ b/install/builders/deb/oscript-opm-completion @@ -0,0 +1,11 @@ +_opm_complete() +{ + local cur opts + COMPREPLY=() + cur="${COMP_WORDS[COMP_CWORD]}" + opts="build prepare install update app help" + COMPREPLY=( $(compgen -W "$opts" -- ${cur}) ) + return 0 +} +complete -F _opm_complete opm + diff --git a/install/builders/deb/settings/dirs b/install/builders/deb/settings/dirs index a7e362059..d48b6e912 100644 --- a/install/builders/deb/settings/dirs +++ b/install/builders/deb/settings/dirs @@ -2,4 +2,5 @@ /etc /usr/share/oscript/bin /usr/share/oscript/lib +/etc/bash_completion.d From b897ae3322350de672e651725d857825435dffda Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sun, 26 Feb 2017 23:04:29 +0300 Subject: [PATCH 002/230] =?UTF-8?q?=D0=97=D0=B0=D0=B4=D0=B5=D0=BB=20=D0=BF?= =?UTF-8?q?=D0=BE=20=D0=BE=D1=82=D0=BB=D0=B0=D0=B4=D1=87=D0=B8=D0=BA=D1=83?= =?UTF-8?q?.=20see=20#411=20#412?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Machine/Contexts/ContextIValueImpl.cs | 10 ++++++ .../Machine/Contexts/GlobalContextBase.cs | 10 ++++++ .../Machine/Contexts/ReflectableSDO.cs | 10 ++++++ .../Machine/IRuntimeContextInstance.cs | 3 ++ src/ScriptEngine/Machine/Variables.cs | 33 ++++++++++++------- 5 files changed, 54 insertions(+), 12 deletions(-) diff --git a/src/ScriptEngine/Machine/Contexts/ContextIValueImpl.cs b/src/ScriptEngine/Machine/Contexts/ContextIValueImpl.cs index 496beefa8..2506813b9 100644 --- a/src/ScriptEngine/Machine/Contexts/ContextIValueImpl.cs +++ b/src/ScriptEngine/Machine/Contexts/ContextIValueImpl.cs @@ -168,6 +168,16 @@ public virtual void SetPropValue(int propNum, IValue newVal) throw new NotImplementedException(); } + public virtual int GetPropCount() + { + throw new NotImplementedException(); + } + + public virtual string GetPropName(int propNum) + { + throw new NotImplementedException(); + } + public virtual IEnumerable GetMethods() { throw new NotImplementedException(); diff --git a/src/ScriptEngine/Machine/Contexts/GlobalContextBase.cs b/src/ScriptEngine/Machine/Contexts/GlobalContextBase.cs index 8b2635017..a9399bec0 100644 --- a/src/ScriptEngine/Machine/Contexts/GlobalContextBase.cs +++ b/src/ScriptEngine/Machine/Contexts/GlobalContextBase.cs @@ -87,6 +87,16 @@ public virtual void SetPropValue(int propNum, IValue newVal) } } + public int GetPropCount() + { + return Properties.Count; + } + + public string GetPropName(int propNum) + { + var prop = Properties.GetProperty(propNum); + return prop.Name; + } public virtual int FindMethod(string name) { diff --git a/src/ScriptEngine/Machine/Contexts/ReflectableSDO.cs b/src/ScriptEngine/Machine/Contexts/ReflectableSDO.cs index 3dfef2bd4..0ad534b2a 100644 --- a/src/ScriptEngine/Machine/Contexts/ReflectableSDO.cs +++ b/src/ScriptEngine/Machine/Contexts/ReflectableSDO.cs @@ -325,6 +325,16 @@ public void SetPropValue(int propNum, IValue newVal) _instance.SetPropValue(propNum, newVal); } + public int GetPropCount() + { + return _instance.GetPropCount(); + } + + public string GetPropName(int propNum) + { + return _instance.GetPropName(propNum); + } + public IEnumerable GetMethods() { return _instance.GetMethods(); diff --git a/src/ScriptEngine/Machine/IRuntimeContextInstance.cs b/src/ScriptEngine/Machine/IRuntimeContextInstance.cs index b52281dfb..7c07484fe 100644 --- a/src/ScriptEngine/Machine/IRuntimeContextInstance.cs +++ b/src/ScriptEngine/Machine/IRuntimeContextInstance.cs @@ -25,6 +25,9 @@ public interface IRuntimeContextInstance IValue GetPropValue(int propNum); void SetPropValue(int propNum, IValue newVal); + int GetPropCount(); + string GetPropName(int propNum); + IEnumerable GetMethods(); int FindMethod(string name); MethodInfo GetMethodInfo(int methodNumber); diff --git a/src/ScriptEngine/Machine/Variables.cs b/src/ScriptEngine/Machine/Variables.cs index 4b24925e0..03a161597 100644 --- a/src/ScriptEngine/Machine/Variables.cs +++ b/src/ScriptEngine/Machine/Variables.cs @@ -14,11 +14,14 @@ namespace ScriptEngine.Machine public interface IVariable : IValue { IValue Value { get; set; } + string Name { get; } } public class Variable : IVariable { - IValue _val; + private IValue _val; + + public string Name { get; private set; } private Variable() { @@ -27,27 +30,28 @@ private Variable() #region Factory - public static IVariable Create(IValue val) + public static IVariable Create(IValue val, string symbol) { return new Variable() { - _val = val + _val = val, + Name = symbol }; } - public static IVariable CreateReference(IVariable variable) + public static IVariable CreateReference(IVariable variable, string refName) { - return VariableReference.CreateSimpleReference(variable); + return VariableReference.CreateSimpleReference(variable, refName); } - public static IVariable CreateContextPropertyReference(IRuntimeContextInstance context, int propertyNumber) + public static IVariable CreateContextPropertyReference(IRuntimeContextInstance context, int propertyNumber, string refName) { - return VariableReference.CreateContextPropertyReference(context, propertyNumber); + return VariableReference.CreateContextPropertyReference(context, propertyNumber, refName); } - public static IVariable CreateIndexedPropertyReference(IRuntimeContextInstance context, IValue index) + public static IVariable CreateIndexedPropertyReference(IRuntimeContextInstance context, IValue index, string refName) { - return VariableReference.CreateIndexedPropertyReference(context, index); + return VariableReference.CreateIndexedPropertyReference(context, index, refName); } #endregion @@ -140,6 +144,8 @@ private class VariableReference : IVariable private int _contextPropertyNumber; private IValue _index; + public string Name { get; private set; } + private VariableReference() { @@ -258,29 +264,32 @@ public bool Equals(IValue other) #endregion - public static IVariable CreateSimpleReference(IVariable var) + public static IVariable CreateSimpleReference(IVariable var, string name) { var newVar = new VariableReference(); newVar._refType = ReferenceType.Simple; newVar._referencedValue = var; + newVar.Name = name; return newVar; } - public static IVariable CreateContextPropertyReference(IRuntimeContextInstance context, int propertyNumber) + public static IVariable CreateContextPropertyReference(IRuntimeContextInstance context, int propertyNumber, string name) { var newVar = new VariableReference(); newVar._refType = ReferenceType.ContextProperty; newVar._context = context; newVar._contextPropertyNumber = propertyNumber; + newVar.Name = name; return newVar; } - public static IVariable CreateIndexedPropertyReference(IRuntimeContextInstance context, IValue index) + public static IVariable CreateIndexedPropertyReference(IRuntimeContextInstance context, IValue index, string name) { var newVar = new VariableReference(); newVar._refType = ReferenceType.IndexedProperty; newVar._context = context; newVar._index = index; + newVar.Name = name; return newVar; } From fd9ce2ade3b3e6b7f93a3b467e5a42388d47ca51 Mon Sep 17 00:00:00 2001 From: Faithfinder Date: Tue, 28 Feb 2017 22:00:45 +0300 Subject: [PATCH 003/230] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=BE=20=D0=BF=D0=BE=D0=BB=D1=83=D1=87=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D0=B5=20=D0=B4=D0=B0=D1=82=D1=8B=20=D1=81=D0=BE=D0=B7?= =?UTF-8?q?=D0=B4=D0=B0=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine.HostedScript/Library/FileContext.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/ScriptEngine.HostedScript/Library/FileContext.cs b/src/ScriptEngine.HostedScript/Library/FileContext.cs index 41d8aa292..01489c27e 100644 --- a/src/ScriptEngine.HostedScript/Library/FileContext.cs +++ b/src/ScriptEngine.HostedScript/Library/FileContext.cs @@ -160,6 +160,12 @@ public DateTime GetModificationTime() return File.GetLastWriteTime(FullName); } + [ContextMethod("ПолучитьВремяСоздания", "GetCreationTime")] + public DateTime GetCreationTime() + { + return File.GetCreationTime(FullName); + } + [ContextMethod("УстановитьНевидимость", "SetHidden")] public void SetHidden(bool value) { From 63c994812a54edf4441ad1ac0ba1b5811e304876 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Fri, 3 Mar 2017 00:54:30 +0300 Subject: [PATCH 004/230] =?UTF-8?q?=D0=9D=D0=B5=20=D0=B8=D0=BD=D0=B8=D1=86?= =?UTF-8?q?=D0=B8=D0=B0=D0=BB=D0=B8=D0=B7=D0=B8=D1=80=D0=BE=D0=B2=D0=B0?= =?UTF-8?q?=D0=BB=D0=B8=D1=81=D1=8C=20=D0=BC=D0=BE=D0=B4=D1=83=D0=BB=D0=B8?= =?UTF-8?q?,=20=D0=BF=D0=BE=D0=B4=D0=BA=D0=BB=D1=8E=D1=87=D0=B5=D0=BD?= =?UTF-8?q?=D0=BD=D1=8B=D0=B5=20=D0=B2=20=D1=86=D0=B5=D0=BF=D0=BE=D1=87?= =?UTF-8?q?=D0=BA=D0=B5=20=D0=97=D0=B0=D0=BF=D1=83=D1=81=D0=BA->=D0=9F?= =?UTF-8?q?=D0=BE=D0=B4=D0=BA=D0=BB=D1=8E=D1=87=D0=B8=D1=82=D1=8C=D0=A1?= =?UTF-8?q?=D1=86=D0=B5=D0=BD=D0=B0=D1=80=D0=B8=D0=B9->=D0=98=D1=81=D0=BF?= =?UTF-8?q?=D0=BE=D0=BB=D1=8C=D0=B7=D0=BE=D0=B2=D0=B0=D1=82=D1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine.HostedScript/HostedScriptEngine.cs | 13 ++++++++++--- src/ScriptEngine/RuntimeEnvironment.cs | 11 +++++++++-- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/src/ScriptEngine.HostedScript/HostedScriptEngine.cs b/src/ScriptEngine.HostedScript/HostedScriptEngine.cs index 7ae8f95c5..89e0fe871 100644 --- a/src/ScriptEngine.HostedScript/HostedScriptEngine.cs +++ b/src/ScriptEngine.HostedScript/HostedScriptEngine.cs @@ -219,6 +219,7 @@ private Process InitProcess(IHostApplication host, ref LoadedModuleHandle module { Initialize(); CompileDelayedModules(); + _env.EnvironmentChanged += LoadUserModuleAsProperty; var process = new Process(host, module, _engine); return process; @@ -229,12 +230,17 @@ private void CompileDelayedModules() var scripts = GetUserAddedScripts().Where(x => x.Type == UserAddedScriptType.Module); foreach (var script in scripts) { - var loaded = _engine.LoadModuleImage(script.Module); - var instance = (IValue)_engine.NewObject(loaded); - _env.SetGlobalProperty(script.Symbol, instance); + LoadUserModuleAsProperty(script); } } + private void LoadUserModuleAsProperty(UserAddedScript script) + { + var loaded = _engine.LoadModuleImage(script.Module); + var instance = (IValue) _engine.NewObject(loaded); + _env.SetGlobalProperty(script.Symbol, instance); + } + public void EnableCodeStatistics(string outputFileName) { _codeStat = new CodeStatProcessor(outputFileName); @@ -244,6 +250,7 @@ public void EnableCodeStatistics(string outputFileName) public void Finalize() { _codeStat?.OutputCodeStat(); + _env.EnvironmentChanged -= LoadUserModuleAsProperty; } } } diff --git a/src/ScriptEngine/RuntimeEnvironment.cs b/src/ScriptEngine/RuntimeEnvironment.cs index d44f5aab9..f8f199846 100644 --- a/src/ScriptEngine/RuntimeEnvironment.cs +++ b/src/ScriptEngine/RuntimeEnvironment.cs @@ -14,6 +14,8 @@ This Source Code Form is subject to the terms of the namespace ScriptEngine { + public delegate void EnvironmentChangedHandler(UserAddedScript script); + public class RuntimeEnvironment { private readonly List _objects = new List(); @@ -88,14 +90,19 @@ public void NotifyClassAdded(ScriptModuleHandle module, string symbol) public void NotifyModuleAdded(ScriptModuleHandle module, string symbol) { - _externalScripts.Add(new UserAddedScript() + var script = new UserAddedScript() { Type = UserAddedScriptType.Module, Symbol = symbol, Module = module - }); + }; + + _externalScripts.Add(script); + EnvironmentChanged?.Invoke(script); } + public event EnvironmentChangedHandler EnvironmentChanged; + public IEnumerable GetUserAddedScripts() { return _externalScripts; From d84bcda0c701299db63b49f1d6d800388bf0169e Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sun, 5 Mar 2017 22:26:17 +0300 Subject: [PATCH 005/230] =?UTF-8?q?=D0=A3=D0=B1=D1=80=D0=B0=D0=BB=20=D0=BF?= =?UTF-8?q?=D1=80=D0=B8=D1=87=D0=B8=D0=BD=D1=83=20warning-=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine.HostedScript/HostedScriptEngine.cs | 2 +- src/oscript/ExecuteScriptBehavior.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ScriptEngine.HostedScript/HostedScriptEngine.cs b/src/ScriptEngine.HostedScript/HostedScriptEngine.cs index 89e0fe871..a02245b1f 100644 --- a/src/ScriptEngine.HostedScript/HostedScriptEngine.cs +++ b/src/ScriptEngine.HostedScript/HostedScriptEngine.cs @@ -247,7 +247,7 @@ public void EnableCodeStatistics(string outputFileName) _engine.SetCodeStatisticsCollector(_codeStat); } - public void Finalize() + public void Dispose() { _codeStat?.OutputCodeStat(); _env.EnvironmentChanged -= LoadUserModuleAsProperty; diff --git a/src/oscript/ExecuteScriptBehavior.cs b/src/oscript/ExecuteScriptBehavior.cs index 8d09fd0d6..c23627e43 100644 --- a/src/oscript/ExecuteScriptBehavior.cs +++ b/src/oscript/ExecuteScriptBehavior.cs @@ -54,7 +54,7 @@ public override int Execute() } var result = process.Start(); - hostedScript.Finalize(); + hostedScript.Dispose(); return result; } From 465f6b95ffd1534053048f0f38bd79777e7fdd9d Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sun, 5 Mar 2017 22:27:16 +0300 Subject: [PATCH 006/230] =?UTF-8?q?=D0=A0=D0=B5=D0=B3=D0=B8=D1=81=D1=82?= =?UTF-8?q?=D1=80=D0=B0=D1=86=D0=B8=D1=8F=20=D0=B8=D0=BC=D0=B5=D0=BD=20?= =?UTF-8?q?=D0=BF=D0=B5=D1=80=D0=B5=D0=BC=D0=B5=D0=BD=D0=BD=D1=8B=D1=85=20?= =?UTF-8?q?=D0=B2=20=D1=80=D0=B0=D0=BD=D1=82=D0=B0=D0=B9=D0=BC=D0=B5.=20se?= =?UTF-8?q?e=20#411?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Library/Reflector.cs | 2 +- .../Library/SystemGlobalContext.cs | 13 ++++++- .../LibraryLoader.cs | 4 +- src/ScriptEngine/Compiler/Compiler.cs | 20 ++++++++-- src/ScriptEngine/Compiler/ModuleWriter.cs | 9 ++++- .../Machine/Contexts/ScriptDrivenObject.cs | 6 +-- src/ScriptEngine/Machine/LoadedModule.cs | 4 +- src/ScriptEngine/Machine/MachineInstance.cs | 39 ++++++++++--------- src/ScriptEngine/Machine/PropertyBag.cs | 14 ++++--- src/ScriptEngine/ModuleImage.cs | 7 ++-- src/ScriptEngine/ScriptEngine.csproj | 5 +-- src/ScriptEngine/Utils.cs | 8 ++++ src/oscript/CgiBehavior.cs | 10 +++++ 13 files changed, 96 insertions(+), 45 deletions(-) diff --git a/src/ScriptEngine.HostedScript/Library/Reflector.cs b/src/ScriptEngine.HostedScript/Library/Reflector.cs index 5dbc2e689..611869355 100644 --- a/src/ScriptEngine.HostedScript/Library/Reflector.cs +++ b/src/ScriptEngine.HostedScript/Library/Reflector.cs @@ -73,7 +73,7 @@ private static IValue[] GetArgsToPass(ArrayImpl arguments, MethodInfo methInfo) for (int i = 0; i < argsToPass.Length; i++) { if (!methInfo.Params[i].IsByValue) - argsToPass[i] = Variable.Create(argsToPass[i]); + argsToPass[i] = Variable.Create(argsToPass[i], $"reflectorArg{i}"); } return argsToPass; diff --git a/src/ScriptEngine.HostedScript/Library/SystemGlobalContext.cs b/src/ScriptEngine.HostedScript/Library/SystemGlobalContext.cs index 226b1431f..e3208b7ef 100644 --- a/src/ScriptEngine.HostedScript/Library/SystemGlobalContext.cs +++ b/src/ScriptEngine.HostedScript/Library/SystemGlobalContext.cs @@ -52,9 +52,10 @@ private void InitContextVariables() { _state = new IVariable[_properties.Count]; + var propNames = _propHolder.GetProperties().OrderBy(x=>x.Value).Select(x=>x.Key).ToArray(); for (int i = 0; i < _properties.Count; i++) { - _state[i] = Variable.CreateContextPropertyReference(this, i); + _state[i] = Variable.CreateContextPropertyReference(this, i, propNames[i]); } } @@ -570,6 +571,16 @@ public void SetPropValue(int propNum, IValue newVal) throw new InvalidOperationException("global props are not writable"); } + public int GetPropCount() + { + return _properties.Count; + } + + public string GetPropName(int index) + { + return _propHolder.GetProperties().First(x => x.Value == index).Key; + } + public int FindMethod(string name) { return _methods.FindMethod(name); diff --git a/src/ScriptEngine.HostedScript/LibraryLoader.cs b/src/ScriptEngine.HostedScript/LibraryLoader.cs index 153344a12..a1e06b298 100644 --- a/src/ScriptEngine.HostedScript/LibraryLoader.cs +++ b/src/ScriptEngine.HostedScript/LibraryLoader.cs @@ -210,8 +210,8 @@ public bool ProcessLibrary(string libraryPath) private bool CustomizedProcessing(string libraryPath) { var libPathValue = ValueFactory.Create(libraryPath); - var defaultLoading = Variable.Create(ValueFactory.Create(true)); - var cancelLoading = Variable.Create(ValueFactory.Create(false)); + var defaultLoading = Variable.Create(ValueFactory.Create(true), "$internalDefaultLoading"); + var cancelLoading = Variable.Create(ValueFactory.Create(false), "$internalCancelLoading"); int eventIdx = GetScriptMethod("ПриЗагрузкеБиблиотеки", "OnLibraryLoad"); if(eventIdx == -1) diff --git a/src/ScriptEngine/Compiler/Compiler.cs b/src/ScriptEngine/Compiler/Compiler.cs index 0d6fc3fd5..95395b598 100644 --- a/src/ScriptEngine/Compiler/Compiler.cs +++ b/src/ScriptEngine/Compiler/Compiler.cs @@ -223,7 +223,7 @@ private void BuildVariableDefinitions() } _module.VariableRefs.Add(definition); - _module.VariableFrameSize++; + _module.Variables.Add(symbolicName); } NextToken(); if (_lastExtractedLexem.Token == Token.Export) @@ -286,8 +286,8 @@ private void BuildModuleBody() var descriptor = new MethodDescriptor(); descriptor.EntryPoint = entry; descriptor.Signature = bodyMethod; - descriptor.VariableFrameSize = localCtx.VariableCount; - + FillVariablesFrame(descriptor, localCtx); + var entryRefNumber = _module.MethodRefs.Count; var bodyBinding = new SymbolBinding() { @@ -300,6 +300,17 @@ private void BuildModuleBody() } } + private static void FillVariablesFrame(MethodDescriptor descriptor, SymbolScope localCtx) + { + descriptor.Variables = new VariablesFrame(); + + for (int i = 0; i < localCtx.VariableCount; i++) + { + descriptor.Variables.Add(localCtx.GetVariable(i).Identifier); + } + + } + private void HandleDirective(bool codeEntered) { var directive = _lastExtractedLexem.Content; @@ -448,7 +459,8 @@ private void BuildSingleMethod() var descriptor = new MethodDescriptor(); descriptor.EntryPoint = entryPoint; descriptor.Signature = method; - descriptor.VariableFrameSize = methodCtx.VariableCount; + FillVariablesFrame(descriptor, methodCtx); + SymbolBinding binding; try { diff --git a/src/ScriptEngine/Compiler/ModuleWriter.cs b/src/ScriptEngine/Compiler/ModuleWriter.cs index e855f0ef6..0b02c7bdb 100644 --- a/src/ScriptEngine/Compiler/ModuleWriter.cs +++ b/src/ScriptEngine/Compiler/ModuleWriter.cs @@ -36,7 +36,9 @@ public void Write(TextWriter output, ScriptModuleHandle module) private void WriteImage(TextWriter output, ModuleImage module) { - output.WriteLine(".variableFrame:" + module.VariableFrameSize.ToString()); + output.WriteLine(".variableFrame:"); + module.Variables.ForEach(x=>output.WriteLine(" " + x)); + output.WriteLine(".constants"); for (int i = 0; i < module.Constants.Count; i++) { @@ -88,7 +90,7 @@ private void WriteMethodDefinition(TextWriter output, MethodDescriptor item) output.Write(string.Format("{0} entryPoint: {1}, frameSize:{2}\n", item.Signature.Name, item.EntryPoint, - item.VariableFrameSize)); + item.Variables.Count)); output.Write(string.Format(".args {0}\n", item.Signature.ArgCount)); if (item.Signature.Params != null) { @@ -105,6 +107,9 @@ private void WriteMethodDefinition(TextWriter output, MethodDescriptor item) } } } + output.WriteLine(".variables ["); + item.Variables.ForEach(x=>output.WriteLine(" " + x)); + output.Write("]"); } private void WriteExports(TextWriter output, IList exports) diff --git a/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs b/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs index 63e8eb724..3bae8b0a2 100644 --- a/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs +++ b/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs @@ -55,14 +55,14 @@ public void InitOwnData() VARIABLE_COUNT = GetOwnVariableCount(); METHOD_COUNT = GetOwnMethodCount(); - int stateSize = VARIABLE_COUNT + _module.VariableFrameSize; + int stateSize = VARIABLE_COUNT + _module.Variables.Count; _state = new IVariable[stateSize]; for (int i = 0; i < stateSize; i++) { if (i < VARIABLE_COUNT) - _state[i] = Variable.CreateContextPropertyReference(this, i); + _state[i] = Variable.CreateContextPropertyReference(this, i, GetPropName(i)); else - _state[i] = Variable.Create(ValueFactory.Create()); + _state[i] = Variable.Create(ValueFactory.Create(), _module.Variables[i]); } ReadExportedSymbols(_module.ExportedMethods, _methodSearchCache); diff --git a/src/ScriptEngine/Machine/LoadedModule.cs b/src/ScriptEngine/Machine/LoadedModule.cs index ba7c1aedb..d39078386 100644 --- a/src/ScriptEngine/Machine/LoadedModule.cs +++ b/src/ScriptEngine/Machine/LoadedModule.cs @@ -23,7 +23,7 @@ internal LoadedModule(ModuleImage image) this.VariableRefs = image.VariableRefs.ToArray(); this.Methods = image.Methods.ToArray(); this.Constants = new IValue[image.Constants.Count]; - this.VariableFrameSize = image.VariableFrameSize; + this.Variables = new VariablesFrame(image.Variables); this.ExportedProperies = image.ExportedProperties.ToArray(); this.ExportedMethods = image.ExportedMethods.ToArray(); this.ModuleInfo = image.ModuleInfo; @@ -34,7 +34,7 @@ internal LoadedModule(ModuleImage image) } } - public int VariableFrameSize { get; private set; } + public VariablesFrame Variables { get; private set; } public int EntryMethodIndex { get; private set; } public Command[] Code { get; private set;} public SymbolBinding[] VariableRefs { get; private set; } diff --git a/src/ScriptEngine/Machine/MachineInstance.cs b/src/ScriptEngine/Machine/MachineInstance.cs index 23a9e8af7..eb2a4bb51 100644 --- a/src/ScriptEngine/Machine/MachineInstance.cs +++ b/src/ScriptEngine/Machine/MachineInstance.cs @@ -90,14 +90,15 @@ internal void ExecuteModuleBody() internal IValue ExecuteMethod(int methodIndex, IValue[] arguments) { PrepareMethodExecutionDirect(methodIndex); + var method = _module.Methods[methodIndex]; for (int i = 0; i < arguments.Length; i++) { if (arguments[i] is IVariable) - _currentFrame.Locals[i] = (IVariable)arguments[i]; + _currentFrame.Locals[i] = Variable.CreateReference((IVariable)arguments[i], method.Variables[i]); else if(arguments[i] == null) - _currentFrame.Locals[i] = Variable.Create(GetDefaultArgValue(methodIndex, i)); + _currentFrame.Locals[i] = Variable.Create(GetDefaultArgValue(methodIndex, i), method.Variables[i]); else - _currentFrame.Locals[i] = Variable.Create(arguments[i]); + _currentFrame.Locals[i] = Variable.Create(arguments[i], method.Variables[i]); } ExecuteCode(); @@ -105,8 +106,8 @@ internal IValue ExecuteMethod(int methodIndex, IValue[] arguments) { return _operationStack.Pop(); } - else - return null; + + return null; } internal ScriptInformationContext CurrentScript @@ -290,10 +291,10 @@ private void PrepareMethodExecutionDirect(int methodIndex) var methDescr = _module.Methods[methodIndex]; var frame = new ExecutionFrame(); frame.MethodName = methDescr.Signature.Name; - frame.Locals = new IVariable[methDescr.VariableFrameSize]; - for (int i = 0; i < methDescr.VariableFrameSize; i++) + frame.Locals = new IVariable[methDescr.Variables.Count]; + for (int i = 0; i < frame.Locals.Length; i++) { - frame.Locals[i] = Variable.Create(ValueFactory.Create()); + frame.Locals[i] = Variable.Create(ValueFactory.Create(), methDescr.Variables[i]); } frame.InstructionPointer = methDescr.EntryPoint; @@ -592,7 +593,7 @@ private void PushRef(int arg) { var vm = _module.VariableRefs[arg]; var scope = _scopes[vm.ContextIndex]; - var reference = Variable.CreateContextPropertyReference(scope.Instance, vm.CodeIndex); + var reference = Variable.CreateContextPropertyReference(scope.Instance, vm.CodeIndex, "$stackvar"); _operationStack.Push(reference); NextInstruction(); } @@ -817,8 +818,8 @@ private bool MethodCallImpl(int arg, bool asFunc) var methDescr = _module.Methods[sdo.GetMethodDescriptorIndex(methodRef.CodeIndex)]; var frame = new ExecutionFrame(); frame.MethodName = methInfo.Name; - frame.Locals = new IVariable[methDescr.VariableFrameSize]; - for (int i = 0; i < methDescr.VariableFrameSize; i++) + frame.Locals = new IVariable[methDescr.Variables.Count]; + for (int i = 0; i < frame.Locals.Length; i++) { if (i < argValues.Length) { @@ -828,16 +829,16 @@ private bool MethodCallImpl(int arg, bool asFunc) if (paramDef.IsByValue) { var value = ((IVariable)argValues[i]).Value; - frame.Locals[i] = Variable.Create(value); + frame.Locals[i] = Variable.Create(value, methDescr.Variables[i]); } else { - frame.Locals[i] = (IVariable)argValues[i]; + frame.Locals[i] = Variable.CreateReference((IVariable)argValues[i], methDescr.Variables[i]); } } else { - frame.Locals[i] = Variable.Create(argValues[i]); + frame.Locals[i] = Variable.Create(argValues[i], methDescr.Variables[i]); } } @@ -845,15 +846,15 @@ private bool MethodCallImpl(int arg, bool asFunc) { if (methInfo.Params[i].DefaultValueIndex == ParameterDefinition.UNDEFINED_VALUE_INDEX) { - frame.Locals[i] = Variable.Create(ValueFactory.Create()); + frame.Locals[i] = Variable.Create(ValueFactory.Create(), methDescr.Variables[i]); } else { - frame.Locals[i] = Variable.Create(_module.Constants[methInfo.Params[i].DefaultValueIndex]); + frame.Locals[i] = Variable.Create(_module.Constants[methInfo.Params[i].DefaultValueIndex], methDescr.Variables[i]); } } else - frame.Locals[i] = Variable.Create(ValueFactory.Create()); + frame.Locals[i] = Variable.Create(ValueFactory.Create(), methDescr.Variables[i]); } @@ -942,7 +943,7 @@ private void ResolveProp(int arg) var propName = _module.Constants[arg].AsString(); var propNum = context.FindProperty(propName); - var propReference = Variable.CreateContextPropertyReference(context, propNum); + var propReference = Variable.CreateContextPropertyReference(context, propNum, "stackvar"); _operationStack.Push(propReference); NextInstruction(); @@ -1099,7 +1100,7 @@ private void PushIndexed(int arg) throw RuntimeException.IndexedAccessIsNotSupportedException(); } - _operationStack.Push(Variable.CreateIndexedPropertyReference(context, index)); + _operationStack.Push(Variable.CreateIndexedPropertyReference(context, index, "$stackvar")); NextInstruction(); } diff --git a/src/ScriptEngine/Machine/PropertyBag.cs b/src/ScriptEngine/Machine/PropertyBag.cs index 047949bb7..ec729d6c0 100644 --- a/src/ScriptEngine/Machine/PropertyBag.cs +++ b/src/ScriptEngine/Machine/PropertyBag.cs @@ -4,8 +4,9 @@ This Source Code Form is subject to the terms of the was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. ----------------------------------------------------------*/ -using System; -using System.Collections.Generic; +using System; +using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Text; using ScriptEngine.Machine.Contexts; @@ -79,10 +80,13 @@ public int Count public void OnAttach(MachineInstance machine, out IVariable[] variables, out MethodInfo[] methods, out IRuntimeContextInstance instance) { - variables = new IVariable[this.Count]; - for (int i = 0; i < variables.Length; i++) + variables = new IVariable[this.Count]; + var props = GetProperties().OrderBy(x => x.Value).Select(x=>x.Key).ToArray(); + Debug.Assert(props.Length == variables.Length); + + for (var i = 0; i < variables.Length; i++) { - variables[i] = Variable.CreateContextPropertyReference(this, i); + variables[i] = Variable.CreateContextPropertyReference(this, i, props[i]); } methods = new MethodInfo[0]; diff --git a/src/ScriptEngine/ModuleImage.cs b/src/ScriptEngine/ModuleImage.cs index 3c44d3a6d..50822cbdd 100644 --- a/src/ScriptEngine/ModuleImage.cs +++ b/src/ScriptEngine/ModuleImage.cs @@ -26,9 +26,10 @@ public ModuleImage() Constants = new List(); ExportedProperties = new List(); ExportedMethods = new List(); + Variables = new VariablesFrame(); } - - public int VariableFrameSize { get; set; } + + public VariablesFrame Variables { get; } public int EntryMethodIndex { get; set; } public IList Code { get; set; } public IList VariableRefs { get; set; } @@ -59,7 +60,7 @@ internal ModuleInformation ModuleInfo struct MethodDescriptor { public MethodInfo Signature; - public int VariableFrameSize; + public VariablesFrame Variables; public int EntryPoint; } diff --git a/src/ScriptEngine/ScriptEngine.csproj b/src/ScriptEngine/ScriptEngine.csproj index db5d4deef..d94b77801 100644 --- a/src/ScriptEngine/ScriptEngine.csproj +++ b/src/ScriptEngine/ScriptEngine.csproj @@ -195,10 +195,9 @@ + - - - + diff --git a/src/ScriptEngine/Utils.cs b/src/ScriptEngine/Utils.cs index 79828526f..2b324f07d 100644 --- a/src/ScriptEngine/Utils.cs +++ b/src/ScriptEngine/Utils.cs @@ -29,5 +29,13 @@ public static bool IsValidIdentifier(string name) return true; } + + public static void ForEach(this IEnumerable input, Action action) + { + foreach (var data in input) + { + action(data); + } + } } } diff --git a/src/oscript/CgiBehavior.cs b/src/oscript/CgiBehavior.cs index 232df4ffd..bff8a0370 100644 --- a/src/oscript/CgiBehavior.cs +++ b/src/oscript/CgiBehavior.cs @@ -229,6 +229,16 @@ public void SetPropValue(int propNum, IValue newVal) throw new InvalidOperationException("global props are not writable"); } + public int GetPropCount() + { + return 0; + } + + public string GetPropName(int index) + { + throw new ArgumentOutOfRangeException(); + } + public int FindMethod(string name) { return _methods.FindMethod(name); From f4d35f9c93ab50888abdab327219ba9627330987 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sun, 5 Mar 2017 22:45:24 +0300 Subject: [PATCH 007/230] =?UTF-8?q?=D0=A0=D0=B5=D0=B3=D0=B8=D1=81=D1=82?= =?UTF-8?q?=D1=80=D0=B0=D1=86=D0=B8=D1=8F=20=D0=B8=D0=BC=D0=B5=D0=BD=20?= =?UTF-8?q?=D0=BF=D0=B5=D1=80=D0=B5=D0=BC=D0=B5=D0=BD=D0=BD=D1=8B=D1=85=20?= =?UTF-8?q?=D0=B2=20=D1=80=D0=B0=D0=BD=D1=82=D0=B0=D0=B9=D0=BC=D0=B5.=20se?= =?UTF-8?q?e=20#411?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine/VariablesFrame.cs | 89 ++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 src/ScriptEngine/VariablesFrame.cs diff --git a/src/ScriptEngine/VariablesFrame.cs b/src/ScriptEngine/VariablesFrame.cs new file mode 100644 index 000000000..b7850d321 --- /dev/null +++ b/src/ScriptEngine/VariablesFrame.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace ScriptEngine +{ + internal class VariablesFrame : IList + { + private readonly List _data; + + public VariablesFrame() + { + _data = new List(); + } + + public VariablesFrame(IEnumerable src) + { + _data = new List(src); + } + + public IEnumerator GetEnumerator() + { + return _data.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return ((IEnumerable) _data).GetEnumerator(); + } + + public void Add(string item) + { + _data.Add(item); + } + + public void Clear() + { + _data.Clear(); + } + + public bool Contains(string item) + { + return _data.Contains(item); + } + + public void CopyTo(string[] array, int arrayIndex) + { + _data.CopyTo(array, arrayIndex); + } + + public bool Remove(string item) + { + return _data.Remove(item); + } + + public int Count + { + get { return _data.Count; } + } + + public bool IsReadOnly + { + get { return false; } + } + + public int IndexOf(string item) + { + return _data.IndexOf(item); + } + + public void Insert(int index, string item) + { + _data.Insert(index, item); + } + + public void RemoveAt(int index) + { + _data.RemoveAt(index); + } + + public string this[int index] + { + get { return _data[index]; } + set { _data[index] = value; } + } + } +} From ee0444240f931ad0c0c84ddd8795fd7f87039aac Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sun, 5 Mar 2017 23:42:07 +0300 Subject: [PATCH 008/230] =?UTF-8?q?=D0=BF=D1=80=D0=BE=D0=B4=D0=BE=D0=BB?= =?UTF-8?q?=D0=B6=D0=B5=D0=BD=D0=B8=D0=B5=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=20=D0=BF=D0=BE=20#412?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Library/StructureImpl.cs | 12 ++++++++- .../Machine/Contexts/AutoContext.cs | 10 ++++++++ .../Contexts/DynamicPropertiesAccessor.cs | 5 ++++ .../Contexts/DynamicPropertiesHolder.cs | 25 +++++++++++-------- .../Machine/Contexts/ScriptDrivenObject.cs | 7 +++++- .../Contexts/UserScriptContextInstance.cs | 6 +++++ 6 files changed, 53 insertions(+), 12 deletions(-) diff --git a/src/ScriptEngine.HostedScript/Library/StructureImpl.cs b/src/ScriptEngine.HostedScript/Library/StructureImpl.cs index aa676dbf7..99b33835c 100644 --- a/src/ScriptEngine.HostedScript/Library/StructureImpl.cs +++ b/src/ScriptEngine.HostedScript/Library/StructureImpl.cs @@ -24,7 +24,7 @@ public StructureImpl(string strProperties, params IValue[] values) { var props = strProperties.Split(','); if (props.Length < values.Length) - throw new RuntimeException("Неверное значение аргумента"); + throw RuntimeException.InvalidArgumentValue(); for (int i = 0; i < props.Length; i++) { @@ -97,6 +97,16 @@ public override void SetPropValue(int propNum, IValue newVal) _values[propNum] = newVal; } + public override int GetPropCount() + { + return _values.Count; + } + + public override string GetPropName(int propNum) + { + return GetPropertyName(propNum); + } + public override MethodInfo GetMethodInfo(int methodNumber) { return _methods.GetMethodInfo(methodNumber); diff --git a/src/ScriptEngine/Machine/Contexts/AutoContext.cs b/src/ScriptEngine/Machine/Contexts/AutoContext.cs index af8720c67..f166fd498 100644 --- a/src/ScriptEngine/Machine/Contexts/AutoContext.cs +++ b/src/ScriptEngine/Machine/Contexts/AutoContext.cs @@ -52,6 +52,16 @@ public override void SetPropValue(int propNum, IValue newVal) } } + public override int GetPropCount() + { + return _properties.Count; + } + + public override string GetPropName(int propNum) + { + return _properties.GetProperty(propNum).Name; + } + public override int FindMethod(string name) { return _methods.FindMethod(name); diff --git a/src/ScriptEngine/Machine/Contexts/DynamicPropertiesAccessor.cs b/src/ScriptEngine/Machine/Contexts/DynamicPropertiesAccessor.cs index 39160a231..40dbda390 100644 --- a/src/ScriptEngine/Machine/Contexts/DynamicPropertiesAccessor.cs +++ b/src/ScriptEngine/Machine/Contexts/DynamicPropertiesAccessor.cs @@ -40,6 +40,11 @@ protected void ClearProperties() _propHolder.ClearProperties(); } + protected string GetPropertyName(int idx) + { + return _propHolder.GetPropertyName(idx); + } + protected virtual IEnumerable> GetProperties() { return _propHolder.GetProperties(); diff --git a/src/ScriptEngine/Machine/Contexts/DynamicPropertiesHolder.cs b/src/ScriptEngine/Machine/Contexts/DynamicPropertiesHolder.cs index f6e07eb07..a7c545527 100644 --- a/src/ScriptEngine/Machine/Contexts/DynamicPropertiesHolder.cs +++ b/src/ScriptEngine/Machine/Contexts/DynamicPropertiesHolder.cs @@ -14,33 +14,33 @@ namespace ScriptEngine.Machine.Contexts public class DynamicPropertiesHolder { private readonly Dictionary _propNumbers = new Dictionary(StringComparer.InvariantCultureIgnoreCase); - + public int RegisterProperty(string name) { if (_propNumbers.ContainsKey(name)) { return _propNumbers[name]; } - else - { - if (!IsValidIdentifier(name)) - { - throw new RuntimeException("Неверное значение аргумента"); - } - var idx = _propNumbers.Count; - _propNumbers.Add(name, idx); - return idx; + if (!IsValidIdentifier(name)) + { + throw RuntimeException.InvalidArgumentValue(); } + + var idx = _propNumbers.Count; + _propNumbers.Add(name, idx); + return idx; } public void RemoveProperty(string name) { + var idx = _propNumbers[name]; _propNumbers.Remove(name); } public void ReorderPropertyNumbers() { + _propNumbers.Clear(); var sorted = _propNumbers.OrderBy(x => x.Value).Select(x => x.Key).ToArray(); _propNumbers.Clear(); for (int i = 0; i < sorted.Length; i++) @@ -66,6 +66,11 @@ public int GetPropertyNumber(string name) } } + public string GetPropertyName(int idx) + { + return _propNumbers.First(x => x.Value == idx).Key; + } + public IEnumerable> GetProperties() { return _propNumbers.AsEnumerable(); diff --git a/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs b/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs index 3bae8b0a2..d4844a088 100644 --- a/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs +++ b/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs @@ -60,7 +60,7 @@ public void InitOwnData() for (int i = 0; i < stateSize; i++) { if (i < VARIABLE_COUNT) - _state[i] = Variable.CreateContextPropertyReference(this, i, GetPropName(i)); + _state[i] = Variable.CreateContextPropertyReference(this, i, GetOwnPropName(i)); else _state[i] = Variable.Create(ValueFactory.Create(), _module.Variables[i]); } @@ -167,6 +167,11 @@ protected virtual IValue GetOwnPropValue(int index) throw new NotImplementedException(); } + protected virtual string GetOwnPropName(int index) + { + throw new NotImplementedException(); + } + protected virtual void SetOwnPropValue(int index, IValue val) { throw new NotImplementedException(); diff --git a/src/ScriptEngine/Machine/Contexts/UserScriptContextInstance.cs b/src/ScriptEngine/Machine/Contexts/UserScriptContextInstance.cs index 36fe63a6e..cadda9c8a 100644 --- a/src/ScriptEngine/Machine/Contexts/UserScriptContextInstance.cs +++ b/src/ScriptEngine/Machine/Contexts/UserScriptContextInstance.cs @@ -77,6 +77,12 @@ protected override IValue GetOwnPropValue(int index) return _ownProperties[index]; } + protected override string GetOwnPropName(int index) + { + var prop = _module.ExportedProperies[index]; + return prop.SymbolicName; + } + #region IReflectableContext Members public override IEnumerable GetProperties() From 701ee4688a8cb836d81f8bf363b9ff4a650fd6ee Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Mon, 6 Mar 2017 18:01:01 +0300 Subject: [PATCH 009/230] =?UTF-8?q?=D0=9A=D1=80=D0=B0=D1=81=D0=B8=D0=B2?= =?UTF-8?q?=D0=BE=D1=81=D1=82=D0=B8=20=D0=B2=20=D0=B2=D1=8B=D0=B2=D0=BE?= =?UTF-8?q?=D0=B4=D0=B5=20=D0=BC=D0=BE=D0=B4=D1=83=D0=BB=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine/Compiler/ModuleWriter.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ScriptEngine/Compiler/ModuleWriter.cs b/src/ScriptEngine/Compiler/ModuleWriter.cs index 0b02c7bdb..5c9656e9d 100644 --- a/src/ScriptEngine/Compiler/ModuleWriter.cs +++ b/src/ScriptEngine/Compiler/ModuleWriter.cs @@ -109,7 +109,7 @@ private void WriteMethodDefinition(TextWriter output, MethodDescriptor item) } output.WriteLine(".variables ["); item.Variables.ForEach(x=>output.WriteLine(" " + x)); - output.Write("]"); + output.WriteLine("]"); } private void WriteExports(TextWriter output, IList exports) From 6be1bb3cfd41a3e39a0e2818908efce214c362df Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Mon, 6 Mar 2017 18:01:23 +0300 Subject: [PATCH 010/230] =?UTF-8?q?=D0=9E=D1=88=D0=B8=D0=B1=D0=BA=D0=B0=20?= =?UTF-8?q?=D1=81=20=D0=B7=D0=B0=D0=BF=D0=BE=D0=BB=D0=BD=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5=D0=BC=20=D1=81=D0=BF=D0=B8=D1=81=D0=BA=D0=B0=20=D0=BF?= =?UTF-8?q?=D0=B5=D1=80=D0=B5=D0=BC=D0=B5=D0=BD=D0=BD=D1=8B=D1=85=20=D0=BC?= =?UTF-8?q?=D0=B5=D1=82=D0=BE=D0=B4=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine/Compiler/Compiler.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/ScriptEngine/Compiler/Compiler.cs b/src/ScriptEngine/Compiler/Compiler.cs index 95395b598..568671dbf 100644 --- a/src/ScriptEngine/Compiler/Compiler.cs +++ b/src/ScriptEngine/Compiler/Compiler.cs @@ -286,7 +286,7 @@ private void BuildModuleBody() var descriptor = new MethodDescriptor(); descriptor.EntryPoint = entry; descriptor.Signature = bodyMethod; - FillVariablesFrame(descriptor, localCtx); + FillVariablesFrame(ref descriptor, localCtx); var entryRefNumber = _module.MethodRefs.Count; var bodyBinding = new SymbolBinding() @@ -300,7 +300,7 @@ private void BuildModuleBody() } } - private static void FillVariablesFrame(MethodDescriptor descriptor, SymbolScope localCtx) + private static void FillVariablesFrame(ref MethodDescriptor descriptor, SymbolScope localCtx) { descriptor.Variables = new VariablesFrame(); @@ -459,7 +459,7 @@ private void BuildSingleMethod() var descriptor = new MethodDescriptor(); descriptor.EntryPoint = entryPoint; descriptor.Signature = method; - FillVariablesFrame(descriptor, methodCtx); + FillVariablesFrame(ref descriptor, methodCtx); SymbolBinding binding; try From 2fe52fbf2ee3f2a02d3de48334299398d120ae99 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Mon, 6 Mar 2017 18:34:49 +0300 Subject: [PATCH 011/230] =?UTF-8?q?=D0=98=D0=B7=D0=B1=D1=8B=D1=82=D0=BE?= =?UTF-8?q?=D1=87=D0=BD=D0=BE=20=D0=B4=D0=B5=D1=80=D0=B6=D0=B0=D1=82=D1=8C?= =?UTF-8?q?=20WeakReference?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Library/ValueTable/ValueTableRow.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableRow.cs b/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableRow.cs index 352952087..564d896ef 100644 --- a/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableRow.cs +++ b/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableRow.cs @@ -17,23 +17,23 @@ namespace ScriptEngine.HostedScript.Library.ValueTable public class ValueTableRow : DynamicPropertiesAccessor, ICollectionContext, IEnumerable { private readonly Dictionary _data = new Dictionary(); - private readonly WeakReference _owner; + private readonly ValueTable _owner; - public ValueTableRow(ValueTable Owner) + public ValueTableRow(ValueTable owner) { - _owner = new WeakReference(Owner); + _owner = owner; } public int Count() { - var Owner = _owner.Target as ValueTable; + var Owner = _owner; return Owner.Columns.Count(); } [ContextMethod("Владелец", "Owner")] public ValueTable Owner() { - return _owner.Target as ValueTable; + return _owner; } private IValue TryValue(ValueTableColumn Column) From 44fca3c561268d23b92c78d8cf9e4c6ebeffc0dc Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Mon, 6 Mar 2017 18:36:13 +0300 Subject: [PATCH 012/230] =?UTF-8?q?=D0=92=20=D1=81=D1=82=D1=80=D0=BE=D0=BA?= =?UTF-8?q?=D0=B5=20=D1=82=D0=B0=D0=B1=D0=BB=D0=B8=D1=86=D1=8B=20=D0=B7?= =?UTF-8?q?=D0=BD=D0=B0=D1=87=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=B4=D0=BE=D0=BB?= =?UTF-8?q?=D0=B6=D0=BD=D0=B0=20=D0=B1=D1=8B=D1=82=D1=8C=20=D0=B4=D1=80?= =?UTF-8?q?=D1=83=D0=B3=D0=B0=D1=8F=20=D0=B8=D0=B5=D1=80=D0=B0=D1=80=D1=85?= =?UTF-8?q?=D0=B8=D1=8F.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Library/ValueTable/ValueTableRow.cs | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableRow.cs b/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableRow.cs index 564d896ef..d6fd96b86 100644 --- a/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableRow.cs +++ b/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableRow.cs @@ -14,7 +14,7 @@ This Source Code Form is subject to the terms of the namespace ScriptEngine.HostedScript.Library.ValueTable { [ContextClass("СтрокаТаблицыЗначений", "ValueTableRow")] - public class ValueTableRow : DynamicPropertiesAccessor, ICollectionContext, IEnumerable + public class ValueTableRow : PropertyNameIndexAccessor, ICollectionContext, IEnumerable { private readonly Dictionary _data = new Dictionary(); private readonly ValueTable _owner; @@ -175,14 +175,15 @@ public override int FindMethod(string name) return _methods.FindMethod(name); } - protected override IEnumerable> GetProperties() - { - return Owner().Columns - .Select(x=> - { - var column = x as ValueTableColumn; - return new KeyValuePair(column.Name, column.ID); - }); - } + // FIXME: это был костыль для ЗаполнитьЗначенияСвойств + //protected override IEnumerable> GetProperties() + //{ + // return Owner().Columns + // .Select(x=> + // { + // var column = x as ValueTableColumn; + // return new KeyValuePair(column.Name, column.ID); + // }); + //} } } From a466d97cb8ee30089c3daa2ad5a8190086e5a0a6 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Mon, 6 Mar 2017 18:36:28 +0300 Subject: [PATCH 013/230] =?UTF-8?q?=D0=92=D1=81=D0=BF=D0=BE=D0=BC=D0=BE?= =?UTF-8?q?=D0=B3=D0=B0=D1=82=D0=B5=D0=BB=D1=8C=D0=BD=D1=8B=D0=B9=20=D0=BC?= =?UTF-8?q?=D0=B5=D1=82=D0=BE=D0=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ValueTable/ValueTableColumnCollection.cs | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableColumnCollection.cs b/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableColumnCollection.cs index 1fa2645ca..f32599f74 100644 --- a/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableColumnCollection.cs +++ b/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableColumnCollection.cs @@ -159,6 +159,34 @@ public ValueTableColumn GetColumnByIIndex(IValue index) throw RuntimeException.InvalidArgumentType(); } + public int GetColumnNumericIndex(IValue index) + { + if (index.DataType == DataType.String) + { + ValueTableColumn Column = FindColumnByName(index.AsString()); + if (Column == null) + throw RuntimeException.PropNotFoundException(index.AsString()); + return Column.ID; + } + + if (index.DataType == DataType.Number) + { + int iIndex = Decimal.ToInt32(index.AsNumber()); + if (iIndex < 0 || iIndex >= Count()) + throw RuntimeException.InvalidArgumentValue(); + + return iIndex; + } + + var column = index.GetRawValue() as ValueTableColumn; + if (column != null) + { + return column.ID; + } + + throw RuntimeException.InvalidArgumentType(); + } + public override IValue GetIndexedValue(IValue index) { return GetColumnByIIndex(index); From ff07a36cdce70e52c5d87d9a2a8f50a336556879 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Tue, 7 Mar 2017 13:51:01 +0300 Subject: [PATCH 014/230] =?UTF-8?q?=D0=A0=D0=B5=D1=84=D0=B0=D0=BA=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=B8=D0=BD=D0=B3=20=D0=B8=D0=BD=D1=84=D1=80=D0=B0?= =?UTF-8?q?=D1=81=D1=82=D1=80=D1=83=D0=BA=D1=82=D1=83=D1=80=D1=8B=20=D1=81?= =?UTF-8?q?=D0=B2=D0=BE=D0=B9=D1=81=D1=82=D0=B2.=20=D0=A3=D0=B4=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D1=8B=20=D1=81=D1=82=D0=B0=D1=80=D1=8B=D0=B5?= =?UTF-8?q?=20=D0=BA=D0=BE=D1=81=D1=82=D1=8B=D0=BB=D0=B8.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Library/SystemGlobalContext.cs | 23 +++++++------- .../Library/ValueTable/ValueTable.cs | 11 ++++--- .../ValueTable/ValueTableColumnCollection.cs | 9 ++++-- .../Library/ValueTable/ValueTableRow.cs | 20 +++++------- .../Machine/Contexts/AutoContext.cs | 24 +++----------- .../Machine/Contexts/ContextPropertyMapper.cs | 6 ---- .../Contexts/DynamicPropertiesAccessor.cs | 26 +--------------- .../Machine/Contexts/ExceptionTemplate.cs | 2 +- .../Machine/Contexts/GlobalContextBase.cs | 15 +-------- .../Machine/Contexts/LibraryContextBase.cs | 31 ------------------- .../Machine/Contexts/ScriptDrivenObject.cs | 9 ------ .../Contexts/UserScriptContextInstance.cs | 15 +-------- .../Machine/IAttachableContext.cs | 2 +- .../Machine/IReflectableContext.cs | 19 ------------ src/ScriptEngine/Machine/PropertyBag.cs | 14 --------- src/ScriptEngine/RuntimeEnvironment.cs | 21 ++++++------- src/ScriptEngine/ScriptEngine.csproj | 2 -- src/oscript/CgiBehavior.cs | 5 --- 18 files changed, 52 insertions(+), 202 deletions(-) delete mode 100644 src/ScriptEngine/Machine/Contexts/LibraryContextBase.cs delete mode 100644 src/ScriptEngine/Machine/IReflectableContext.cs diff --git a/src/ScriptEngine.HostedScript/Library/SystemGlobalContext.cs b/src/ScriptEngine.HostedScript/Library/SystemGlobalContext.cs index e3208b7ef..92bbe81f7 100644 --- a/src/ScriptEngine.HostedScript/Library/SystemGlobalContext.cs +++ b/src/ScriptEngine.HostedScript/Library/SystemGlobalContext.cs @@ -422,19 +422,18 @@ public bool IsValueFilled(IValue value) [ContextMethod("ЗаполнитьЗначенияСвойств","FillPropertyValues")] public void FillPropertyValues(IRuntimeContextInstance acceptor, IRuntimeContextInstance source, string filledProperties = null, string ignoredProperties = null) { - var accReflector = acceptor as IReflectableContext; - if (accReflector == null) - throw RuntimeException.InvalidArgumentValue(); - - var srcReflector = source as IReflectableContext; - if (srcReflector == null) - throw RuntimeException.InvalidArgumentValue(); - IEnumerable sourceProperties; - IEnumerable ignoredPropCollection; - if(filledProperties == null) - { - sourceProperties = srcReflector.GetProperties().Select(x => x.Identifier); + IEnumerable ignoredPropCollection; + + if (filledProperties == null) + { + string[] names = new string[source.GetPropCount()]; + for (int i = 0; i < names.Length; i++) + { + names[i] = source.GetPropName(i); + } + + sourceProperties = names; } else { diff --git a/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTable.cs b/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTable.cs index 1af69a63d..a3ac4c5c1 100644 --- a/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTable.cs +++ b/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTable.cs @@ -16,13 +16,16 @@ namespace ScriptEngine.HostedScript.Library.ValueTable [ContextClass("ТаблицаЗначений", "ValueTable")] public class ValueTable : AutoContext, ICollectionContext, IEnumerable { - private readonly ValueTableColumnCollection _columns = new ValueTableColumnCollection(); - private readonly List _rows = new List(); - private readonly CollectionIndexes _indexes = new CollectionIndexes(); + private readonly ValueTableColumnCollection _columns; + private readonly List _rows; + private readonly CollectionIndexes _indexes; public ValueTable() { - } + _columns = new ValueTableColumnCollection(this); + _rows = new List(); + _indexes = new CollectionIndexes(); + } [ContextProperty("Колонки", "Columns")] public ValueTableColumnCollection Columns diff --git a/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableColumnCollection.cs b/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableColumnCollection.cs index f32599f74..f7b2ac14a 100644 --- a/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableColumnCollection.cs +++ b/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableColumnCollection.cs @@ -19,8 +19,11 @@ public class ValueTableColumnCollection : DynamicPropertiesAccessor, ICollection private readonly List _columns = new List(); private int _internal_counter = 0; // Нарастающий счётчик определителей колонок - public ValueTableColumnCollection() + private readonly ValueTable _owner; + + public ValueTableColumnCollection(ValueTable owner) { + _owner = owner; } [ContextMethod("Добавить", "Add")] @@ -78,7 +81,9 @@ public IValue Find(string Name) public void Delete(IValue Column) { Column = Column.GetRawValue(); - _columns.Remove(GetColumnByIIndex(Column)); + var vtColumn = GetColumnByIIndex(Column); + _owner.ForEach(x=>x.OnOwnerColumnRemoval(vtColumn)); + _columns.Remove(vtColumn); } public ValueTableColumn FindColumnByName(string Name) diff --git a/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableRow.cs b/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableRow.cs index d6fd96b86..bfc4982a9 100644 --- a/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableRow.cs +++ b/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableRow.cs @@ -26,8 +26,7 @@ public ValueTableRow(ValueTable owner) public int Count() { - var Owner = _owner; - return Owner.Columns.Count(); + return Owner().Columns.Count(); } [ContextMethod("Владелец", "Owner")] @@ -61,7 +60,7 @@ public IValue Get(ValueTableColumn C) { return TryValue(C); } - + [ContextMethod("Установить", "Set")] public void Set(int index, IValue Value) { @@ -80,6 +79,11 @@ public void Set(ValueTableColumn Column, IValue Value) _data[Column] = Value; } + public void OnOwnerColumnRemoval(ValueTableColumn column) + { + _data.Remove(column); + } + public IEnumerator GetEnumerator() { foreach (ValueTableColumn item in Owner().Columns) @@ -175,15 +179,5 @@ public override int FindMethod(string name) return _methods.FindMethod(name); } - // FIXME: это был костыль для ЗаполнитьЗначенияСвойств - //protected override IEnumerable> GetProperties() - //{ - // return Owner().Columns - // .Select(x=> - // { - // var column = x as ValueTableColumn; - // return new KeyValuePair(column.Name, column.ID); - // }); - //} } } diff --git a/src/ScriptEngine/Machine/Contexts/AutoContext.cs b/src/ScriptEngine/Machine/Contexts/AutoContext.cs index f166fd498..9f12272f4 100644 --- a/src/ScriptEngine/Machine/Contexts/AutoContext.cs +++ b/src/ScriptEngine/Machine/Contexts/AutoContext.cs @@ -6,12 +6,13 @@ This Source Code Form is subject to the terms of the ----------------------------------------------------------*/ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Text; namespace ScriptEngine.Machine.Contexts { - public abstract class AutoContext : LibraryContextBase where TInstance : AutoContext + public abstract class AutoContext : PropertyNameIndexAccessor where TInstance : AutoContext { public override bool IsPropReadable(int propNum) { @@ -36,6 +37,7 @@ public override IValue GetPropValue(int propNum) } catch (System.Reflection.TargetInvocationException e) { + Debug.Assert(e.InnerException != null); throw e.InnerException; } } @@ -88,6 +90,7 @@ public override void CallAsProcedure(int methodNumber, IValue[] arguments) } catch (System.Reflection.TargetInvocationException e) { + Debug.Assert(e.InnerException != null); throw e.InnerException; } } @@ -100,28 +103,11 @@ public override void CallAsFunction(int methodNumber, IValue[] arguments, out IV } catch (System.Reflection.TargetInvocationException e) { + Debug.Assert(e.InnerException != null); throw e.InnerException; } } - public override IEnumerable GetProperties() - { - var allProps = _properties.GetProperties(); - var result = new VariableInfo[allProps.Length]; - for (int i = 0; i < allProps.Length; i++) - { - result[i] = new VariableInfo() - { - Identifier = allProps[i], - Index = i, - Type = SymbolType.ContextProperty - }; - } - - return result; - - } - private static readonly ContextPropertyMapper _properties = new ContextPropertyMapper(); private static readonly ContextMethodsMapper _methods = new ContextMethodsMapper(); } diff --git a/src/ScriptEngine/Machine/Contexts/ContextPropertyMapper.cs b/src/ScriptEngine/Machine/Contexts/ContextPropertyMapper.cs index e07236c06..63c037d2e 100644 --- a/src/ScriptEngine/Machine/Contexts/ContextPropertyMapper.cs +++ b/src/ScriptEngine/Machine/Contexts/ContextPropertyMapper.cs @@ -201,11 +201,5 @@ public int Count return _properties.Count; } } - - public string[] GetProperties() - { - return _properties.Select(x => x.Name).ToArray(); - } - } } diff --git a/src/ScriptEngine/Machine/Contexts/DynamicPropertiesAccessor.cs b/src/ScriptEngine/Machine/Contexts/DynamicPropertiesAccessor.cs index 40dbda390..0ca8ead35 100644 --- a/src/ScriptEngine/Machine/Contexts/DynamicPropertiesAccessor.cs +++ b/src/ScriptEngine/Machine/Contexts/DynamicPropertiesAccessor.cs @@ -11,7 +11,7 @@ This Source Code Form is subject to the terms of the namespace ScriptEngine.Machine.Contexts { - public abstract class DynamicPropertiesAccessor : PropertyNameIndexAccessor, IReflectableContext + public abstract class DynamicPropertiesAccessor : PropertyNameIndexAccessor { private readonly DynamicPropertiesHolder _propHolder; @@ -81,29 +81,5 @@ public override bool IsPropWritable(int propNum) #endregion - - IEnumerable IReflectableContext.GetProperties() - { - var props = this.GetProperties(); - - var result = new List(); - - foreach (var prop in props) - { - result.Add(new VariableInfo() - { - Identifier = prop.Key, - Index = prop.Value, - Type = SymbolType.ContextProperty - }); - } - - return result; - } - - IEnumerable IReflectableContext.GetMethods() - { - throw new NotImplementedException(); - } } } diff --git a/src/ScriptEngine/Machine/Contexts/ExceptionTemplate.cs b/src/ScriptEngine/Machine/Contexts/ExceptionTemplate.cs index 3b6477c39..fb65a00f9 100644 --- a/src/ScriptEngine/Machine/Contexts/ExceptionTemplate.cs +++ b/src/ScriptEngine/Machine/Contexts/ExceptionTemplate.cs @@ -20,7 +20,7 @@ namespace ScriptEngine.Machine.Contexts /// /// ВызватьИсключение Новый ИнформацияОбОшибке("Текст ошибки", ДополнительныеДанные); [ContextClass("ИнформацияОбОшибкеШаблон", "ExceptionInfoTemplate")] - public class ExceptionTemplate : LibraryContextBase + public class ExceptionTemplate : ContextIValueImpl { public string Message { get; private set; } public IValue Parameter { get; private set; } diff --git a/src/ScriptEngine/Machine/Contexts/GlobalContextBase.cs b/src/ScriptEngine/Machine/Contexts/GlobalContextBase.cs index a9399bec0..15965cc8d 100644 --- a/src/ScriptEngine/Machine/Contexts/GlobalContextBase.cs +++ b/src/ScriptEngine/Machine/Contexts/GlobalContextBase.cs @@ -128,20 +128,7 @@ public virtual void OnAttach(MachineInstance machine, out IVariable[] variables, methods = GetMethods().ToArray(); instance = this; } - - public virtual IEnumerable GetProperties() - { - int i = 0; - - return _properties.GetProperties() - .Select(x => new VariableInfo() - { - Identifier = x, - Index = i++, - Type = SymbolType.ContextProperty - }); - } - + public virtual IEnumerable GetMethods() { var array = new MethodInfo[_methods.Count]; diff --git a/src/ScriptEngine/Machine/Contexts/LibraryContextBase.cs b/src/ScriptEngine/Machine/Contexts/LibraryContextBase.cs deleted file mode 100644 index 10117b246..000000000 --- a/src/ScriptEngine/Machine/Contexts/LibraryContextBase.cs +++ /dev/null @@ -1,31 +0,0 @@ -/*---------------------------------------------------------- -This Source Code Form is subject to the terms of the -Mozilla Public License, v.2.0. If a copy of the MPL -was not distributed with this file, You can obtain one -at http://mozilla.org/MPL/2.0/. -----------------------------------------------------------*/ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace ScriptEngine.Machine.Contexts -{ - // костыльный класс для реализации ЗаполнитьЗначенияСвойств. - // в версии 2.0 используется другой подход к иерархии контекстов. - - public class LibraryContextBase : PropertyNameIndexAccessor, IReflectableContext - { - - public virtual IEnumerable GetProperties() - { - throw new NotImplementedException(); - } - - public override IEnumerable GetMethods() - { - throw new NotImplementedException(); - } - - } -} diff --git a/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs b/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs index d4844a088..54bbc5706 100644 --- a/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs +++ b/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs @@ -235,15 +235,6 @@ private MethodInfo[] AttachMethods() #endregion - #region IReflectableContext Members - - public virtual IEnumerable GetProperties() - { - throw new NotImplementedException(); - } - - #endregion - #region IRuntimeContextInstance Members public override int FindProperty(string name) diff --git a/src/ScriptEngine/Machine/Contexts/UserScriptContextInstance.cs b/src/ScriptEngine/Machine/Contexts/UserScriptContextInstance.cs index cadda9c8a..6fa32ed82 100644 --- a/src/ScriptEngine/Machine/Contexts/UserScriptContextInstance.cs +++ b/src/ScriptEngine/Machine/Contexts/UserScriptContextInstance.cs @@ -84,20 +84,7 @@ protected override string GetOwnPropName(int index) } #region IReflectableContext Members - - public override IEnumerable GetProperties() - { - foreach (var item in _module.ExportedProperies) - { - var vi = new VariableInfo(); - vi.Identifier = item.SymbolicName; - vi.Index = item.Index; - vi.Type = SymbolType.ContextProperty; - - yield return vi; - } - } - + public override IEnumerable GetMethods() { foreach (var item in _module.ExportedMethods) diff --git a/src/ScriptEngine/Machine/IAttachableContext.cs b/src/ScriptEngine/Machine/IAttachableContext.cs index 6effc625a..baaaadaa7 100644 --- a/src/ScriptEngine/Machine/IAttachableContext.cs +++ b/src/ScriptEngine/Machine/IAttachableContext.cs @@ -11,7 +11,7 @@ This Source Code Form is subject to the terms of the namespace ScriptEngine.Machine { - public interface IAttachableContext : IReflectableContext + public interface IAttachableContext { void OnAttach(MachineInstance machine, out IVariable[] variables, diff --git a/src/ScriptEngine/Machine/IReflectableContext.cs b/src/ScriptEngine/Machine/IReflectableContext.cs deleted file mode 100644 index 59c939a36..000000000 --- a/src/ScriptEngine/Machine/IReflectableContext.cs +++ /dev/null @@ -1,19 +0,0 @@ -/*---------------------------------------------------------- -This Source Code Form is subject to the terms of the -Mozilla Public License, v.2.0. If a copy of the MPL -was not distributed with this file, You can obtain one -at http://mozilla.org/MPL/2.0/. -----------------------------------------------------------*/ -using System.Collections.Generic; -using ScriptEngine.Compiler; -using ScriptEngine.Machine; - -namespace ScriptEngine.Machine -{ - public interface IReflectableContext - { - IEnumerable GetProperties(); - IEnumerable GetMethods(); - } - -} diff --git a/src/ScriptEngine/Machine/PropertyBag.cs b/src/ScriptEngine/Machine/PropertyBag.cs index ec729d6c0..45dab6c9c 100644 --- a/src/ScriptEngine/Machine/PropertyBag.cs +++ b/src/ScriptEngine/Machine/PropertyBag.cs @@ -94,19 +94,5 @@ public void OnAttach(MachineInstance machine, out IVariable[] variables, out Met } #endregion - - #region IReflectableContext Members - - IEnumerable IReflectableContext.GetProperties() - { - throw new NotImplementedException(); - } - - IEnumerable IReflectableContext.GetMethods() - { - throw new NotImplementedException(); - } - - #endregion } } diff --git a/src/ScriptEngine/RuntimeEnvironment.cs b/src/ScriptEngine/RuntimeEnvironment.cs index f8f199846..b191f74a3 100644 --- a/src/ScriptEngine/RuntimeEnvironment.cs +++ b/src/ScriptEngine/RuntimeEnvironment.cs @@ -108,25 +108,24 @@ public IEnumerable GetUserAddedScripts() return _externalScripts; } - private void RegisterSymbolScope(IReflectableContext provider, bool asDynamicScope) + private void RegisterSymbolScope(IAttachableContext provider, bool asDynamicScope) { var scope = new SymbolScope(); scope.IsDynamicScope = asDynamicScope; + IVariable[] vars; + MethodInfo[] methods; + IRuntimeContextInstance inst; + + provider.OnAttach(null, out vars, out methods, out inst); + _symbolScopes.PushScope(scope); - foreach (var item in provider.GetProperties()) + foreach (var item in vars) { - if (item.Type == SymbolType.Variable) - { - _symbolScopes.DefineVariable(item.Identifier); - } - else - { - _symbolScopes.DefineProperty(item.Identifier); - } + _symbolScopes.DefineVariable(item.Name); } - foreach (var item in provider.GetMethods()) + foreach (var item in methods) { _symbolScopes.DefineMethod(item); } diff --git a/src/ScriptEngine/ScriptEngine.csproj b/src/ScriptEngine/ScriptEngine.csproj index d94b77801..ae4b6524a 100644 --- a/src/ScriptEngine/ScriptEngine.csproj +++ b/src/ScriptEngine/ScriptEngine.csproj @@ -124,7 +124,6 @@ - @@ -159,7 +158,6 @@ - diff --git a/src/oscript/CgiBehavior.cs b/src/oscript/CgiBehavior.cs index bff8a0370..8e7dcb53e 100644 --- a/src/oscript/CgiBehavior.cs +++ b/src/oscript/CgiBehavior.cs @@ -160,11 +160,6 @@ public void OnAttach(MachineInstance machine, out IVariable[] variables, out Met instance = this; } - public IEnumerable GetProperties() - { - return new VariableInfo[0]; - } - public IEnumerable GetMethods() { var array = new MethodInfo[_methods.Count]; From 78b9d476e6d4af09acb14252a853fd6c6de8074b Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Tue, 7 Mar 2017 13:52:45 +0300 Subject: [PATCH 015/230] =?UTF-8?q?=D1=80=D0=B5=D1=84=D0=B0=D0=BA=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=B8=D0=BD=D0=B3=20=D1=81=D0=B2=D0=BE=D0=B9=D1=81?= =?UTF-8?q?=D1=82=D0=B2=20=D0=B2=20ValueTreeRow?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Library/ValueTree/ValueTreeRow.cs | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/src/ScriptEngine.HostedScript/Library/ValueTree/ValueTreeRow.cs b/src/ScriptEngine.HostedScript/Library/ValueTree/ValueTreeRow.cs index f0d3c09a7..6a67d3686 100644 --- a/src/ScriptEngine.HostedScript/Library/ValueTree/ValueTreeRow.cs +++ b/src/ScriptEngine.HostedScript/Library/ValueTree/ValueTreeRow.cs @@ -17,7 +17,7 @@ namespace ScriptEngine.HostedScript.Library.ValueTree /// Строка дерева значений. /// [ContextClass("СтрокаДереваЗначений", "ValueTreeRow")] - public class ValueTreeRow : DynamicPropertiesAccessor, ICollectionContext, IEnumerable + public class ValueTreeRow : PropertyNameIndexAccessor, ICollectionContext, IEnumerable { private readonly Dictionary _data = new Dictionary(); private readonly ValueTreeRow _parent; @@ -241,15 +241,6 @@ public override int FindMethod(string name) { return _methods.FindMethod(name); } - - protected override IEnumerable> GetProperties() - { - return Owner().Columns - .Select(x => - { - var column = x as ValueTreeColumn; - return new KeyValuePair(column.Name, column.ID); - }); - } + } } From 51b6e025a0a56cd6f6ead121e9137aacabfd45ae Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Tue, 7 Mar 2017 17:33:28 +0300 Subject: [PATCH 016/230] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=20=D1=88=D0=B0=D0=B1=D0=BB=D0=BE=D0=BD=20=D1=81?= =?UTF-8?q?=D0=B5=D1=80=D0=B2=D0=B5=D1=80=D0=B0=20=D0=BE=D1=82=D0=BB=D0=B0?= =?UTF-8?q?=D0=B4=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/1Script.sln | 34 ++ src/DebugServer/App.config | 6 + src/DebugServer/DebugServer.csproj | 69 +++ src/DebugServer/DebugSession.cs | 527 +++++++++++++++++++++ src/DebugServer/OscriptDebugSession.cs | 92 ++++ src/DebugServer/Program.cs | 38 ++ src/DebugServer/Properties/AssemblyInfo.cs | 36 ++ src/DebugServer/Protocol.cs | 274 +++++++++++ src/DebugServer/Utilities.cs | 39 ++ src/DebugServer/packages.config | 4 + 10 files changed, 1119 insertions(+) create mode 100644 src/DebugServer/App.config create mode 100644 src/DebugServer/DebugServer.csproj create mode 100644 src/DebugServer/DebugSession.cs create mode 100644 src/DebugServer/OscriptDebugSession.cs create mode 100644 src/DebugServer/Program.cs create mode 100644 src/DebugServer/Properties/AssemblyInfo.cs create mode 100644 src/DebugServer/Protocol.cs create mode 100644 src/DebugServer/Utilities.cs create mode 100644 src/DebugServer/packages.config diff --git a/src/1Script.sln b/src/1Script.sln index 38a9dbac9..4f3ad7cd0 100644 --- a/src/1Script.sln +++ b/src/1Script.sln @@ -26,34 +26,68 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{930C7802-8A8C-48F9-8165-68863BCCD9DD}") = "Installer", "Installer\Installer.wixproj", "{BBE794A6-B159-422F-B655-B7F03F25F223}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DebugServer", "DebugServer\DebugServer.csproj", "{C979F151-AA29-47E4-B020-3039BA0986D9}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution + {4585BA5D-9EC4-4C89-8250-2033D2AC2999}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4585BA5D-9EC4-4C89-8250-2033D2AC2999}.Debug|Any CPU.Build.0 = Debug|Any CPU {4585BA5D-9EC4-4C89-8250-2033D2AC2999}.Debug|x86.ActiveCfg = Debug|x86 {4585BA5D-9EC4-4C89-8250-2033D2AC2999}.Debug|x86.Build.0 = Debug|x86 + {4585BA5D-9EC4-4C89-8250-2033D2AC2999}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4585BA5D-9EC4-4C89-8250-2033D2AC2999}.Release|Any CPU.Build.0 = Release|Any CPU {4585BA5D-9EC4-4C89-8250-2033D2AC2999}.Release|x86.ActiveCfg = Release|x86 {4585BA5D-9EC4-4C89-8250-2033D2AC2999}.Release|x86.Build.0 = Release|x86 + {F062D1D9-D307-492A-A56B-FF3C55F8F6C0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F062D1D9-D307-492A-A56B-FF3C55F8F6C0}.Debug|Any CPU.Build.0 = Debug|Any CPU {F062D1D9-D307-492A-A56B-FF3C55F8F6C0}.Debug|x86.ActiveCfg = Debug|Any CPU {F062D1D9-D307-492A-A56B-FF3C55F8F6C0}.Debug|x86.Build.0 = Debug|Any CPU + {F062D1D9-D307-492A-A56B-FF3C55F8F6C0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F062D1D9-D307-492A-A56B-FF3C55F8F6C0}.Release|Any CPU.Build.0 = Release|Any CPU {F062D1D9-D307-492A-A56B-FF3C55F8F6C0}.Release|x86.ActiveCfg = Release|Any CPU {F062D1D9-D307-492A-A56B-FF3C55F8F6C0}.Release|x86.Build.0 = Release|Any CPU + {F09A46BD-5737-45E7-BA60-A47C9F7821A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F09A46BD-5737-45E7-BA60-A47C9F7821A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {F09A46BD-5737-45E7-BA60-A47C9F7821A9}.Debug|x86.ActiveCfg = Debug|Any CPU {F09A46BD-5737-45E7-BA60-A47C9F7821A9}.Debug|x86.Build.0 = Debug|Any CPU + {F09A46BD-5737-45E7-BA60-A47C9F7821A9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F09A46BD-5737-45E7-BA60-A47C9F7821A9}.Release|Any CPU.Build.0 = Release|Any CPU {F09A46BD-5737-45E7-BA60-A47C9F7821A9}.Release|x86.ActiveCfg = Release|Any CPU {F09A46BD-5737-45E7-BA60-A47C9F7821A9}.Release|x86.Build.0 = Release|Any CPU + {2590E2BB-CC1F-4775-80ED-451F45C9A4F1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2590E2BB-CC1F-4775-80ED-451F45C9A4F1}.Debug|Any CPU.Build.0 = Debug|Any CPU {2590E2BB-CC1F-4775-80ED-451F45C9A4F1}.Debug|x86.ActiveCfg = Debug|x86 {2590E2BB-CC1F-4775-80ED-451F45C9A4F1}.Debug|x86.Build.0 = Debug|x86 + {2590E2BB-CC1F-4775-80ED-451F45C9A4F1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2590E2BB-CC1F-4775-80ED-451F45C9A4F1}.Release|Any CPU.Build.0 = Release|Any CPU {2590E2BB-CC1F-4775-80ED-451F45C9A4F1}.Release|x86.ActiveCfg = Release|x86 {2590E2BB-CC1F-4775-80ED-451F45C9A4F1}.Release|x86.Build.0 = Release|x86 + {795AA2F5-3074-4BC5-A30F-1B6354044D9B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {795AA2F5-3074-4BC5-A30F-1B6354044D9B}.Debug|Any CPU.Build.0 = Debug|Any CPU {795AA2F5-3074-4BC5-A30F-1B6354044D9B}.Debug|x86.ActiveCfg = Debug|x86 {795AA2F5-3074-4BC5-A30F-1B6354044D9B}.Debug|x86.Build.0 = Debug|x86 + {795AA2F5-3074-4BC5-A30F-1B6354044D9B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {795AA2F5-3074-4BC5-A30F-1B6354044D9B}.Release|Any CPU.Build.0 = Release|Any CPU {795AA2F5-3074-4BC5-A30F-1B6354044D9B}.Release|x86.ActiveCfg = Release|x86 {795AA2F5-3074-4BC5-A30F-1B6354044D9B}.Release|x86.Build.0 = Release|x86 + {BBE794A6-B159-422F-B655-B7F03F25F223}.Debug|Any CPU.ActiveCfg = Debug|x86 {BBE794A6-B159-422F-B655-B7F03F25F223}.Debug|x86.ActiveCfg = Debug|x86 + {BBE794A6-B159-422F-B655-B7F03F25F223}.Release|Any CPU.ActiveCfg = Release|x86 {BBE794A6-B159-422F-B655-B7F03F25F223}.Release|x86.ActiveCfg = Release|x86 + {C979F151-AA29-47E4-B020-3039BA0986D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C979F151-AA29-47E4-B020-3039BA0986D9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C979F151-AA29-47E4-B020-3039BA0986D9}.Debug|x86.ActiveCfg = Debug|Any CPU + {C979F151-AA29-47E4-B020-3039BA0986D9}.Debug|x86.Build.0 = Debug|Any CPU + {C979F151-AA29-47E4-B020-3039BA0986D9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C979F151-AA29-47E4-B020-3039BA0986D9}.Release|Any CPU.Build.0 = Release|Any CPU + {C979F151-AA29-47E4-B020-3039BA0986D9}.Release|x86.ActiveCfg = Release|Any CPU + {C979F151-AA29-47E4-B020-3039BA0986D9}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/src/DebugServer/App.config b/src/DebugServer/App.config new file mode 100644 index 000000000..88fa4027b --- /dev/null +++ b/src/DebugServer/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/src/DebugServer/DebugServer.csproj b/src/DebugServer/DebugServer.csproj new file mode 100644 index 000000000..4e44ef9a0 --- /dev/null +++ b/src/DebugServer/DebugServer.csproj @@ -0,0 +1,69 @@ + + + + + Debug + AnyCPU + {C979F151-AA29-47E4-B020-3039BA0986D9} + Exe + Properties + DebugServer + DebugServer + v4.5.2 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll + True + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/DebugServer/DebugSession.cs b/src/DebugServer/DebugSession.cs new file mode 100644 index 000000000..3a25a6323 --- /dev/null +++ b/src/DebugServer/DebugSession.cs @@ -0,0 +1,527 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Linq; +using System.IO; +using DebugServer; + +namespace VSCodeDebug +{ + // ---- Types ------------------------------------------------------------------------- + + public class Message { + public int id { get; } + public string format { get; } + public dynamic variables { get; } + public dynamic showUser { get; } + public dynamic sendTelemetry { get; } + + public Message(int id, string format, dynamic variables = null, bool user = true, bool telemetry = false) { + this.id = id; + this.format = format; + this.variables = variables; + this.showUser = user; + this.sendTelemetry = telemetry; + } + } + + public class StackFrame + { + public int id { get; } + public Source source { get; } + public int line { get; } + public int column { get; } + public string name { get; } + + public StackFrame(int id, string name, Source source, int line, int column) { + this.id = id; + this.name = name; + this.source = source; + this.line = line; + this.column = column; + } + } + + public class Scope + { + public string name { get; } + public int variablesReference { get; } + public bool expensive { get; } + + public Scope(string name, int variablesReference, bool expensive = false) { + this.name = name; + this.variablesReference = variablesReference; + this.expensive = expensive; + } + } + + public class Variable + { + public string name { get; } + public string value { get; } + public string type { get; } + public int variablesReference { get; } + + public Variable(string name, string value, string type, int variablesReference = 0) { + this.name = name; + this.value = value; + this.type = type; + this.variablesReference = variablesReference; + } + } + + public class Thread + { + public int id { get; } + public string name { get; } + + public Thread(int id, string name) { + this.id = id; + if (name == null || name.Length == 0) { + this.name = string.Format("Thread #{0}", id); + } + else { + this.name = name; + } + } + } + + public class Source + { + public string name { get; } + public string path { get; } + public int sourceReference { get; } + + public Source(string name, string path, int sourceReference = 0) { + this.name = name; + this.path = path; + this.sourceReference = sourceReference; + } + + public Source(string path, int sourceReference = 0) { + this.name = Path.GetFileName(path); + this.path = path; + this.sourceReference = sourceReference; + } + } + + public class Breakpoint + { + public bool verified { get; } + public int line { get; } + + public Breakpoint(bool verified, int line) { + this.verified = verified; + this.line = line; + } + } + + // ---- Events ------------------------------------------------------------------------- + + public class InitializedEvent : Event + { + public InitializedEvent() + : base("initialized") { } + } + + public class StoppedEvent : Event + { + public StoppedEvent(int tid, string reasn, string txt = null) + : base("stopped", new { + threadId = tid, + reason = reasn, + text = txt + }) { } + } + + public class ExitedEvent : Event + { + public ExitedEvent(int exCode) + : base("exited", new { exitCode = exCode } ) { } + } + + public class TerminatedEvent : Event + { + public TerminatedEvent() + : base("terminated") { } + } + + public class ThreadEvent : Event + { + public ThreadEvent(string reasn, int tid) + : base("thread", new { + reason = reasn, + threadId = tid + }) { } + } + + public class OutputEvent : Event + { + public OutputEvent(string cat, string outpt) + : base("output", new { + category = cat, + output = outpt + }) { } + } + + // ---- Response ------------------------------------------------------------------------- + + public class Capabilities : ResponseBody { + + public bool supportsConfigurationDoneRequest; + public bool supportsFunctionBreakpoints; + public bool supportsConditionalBreakpoints; + public bool supportsEvaluateForHovers; + public dynamic[] exceptionBreakpointFilters; + } + + public class ErrorResponseBody : ResponseBody { + + public Message error { get; } + + public ErrorResponseBody(Message error) { + this.error = error; + } + } + + public class StackTraceResponseBody : ResponseBody + { + public StackFrame[] stackFrames { get; } + + public StackTraceResponseBody(List frames = null) { + if (frames == null) + stackFrames = new StackFrame[0]; + else + stackFrames = frames.ToArray(); + } + } + + public class ScopesResponseBody : ResponseBody + { + public Scope[] scopes { get; } + + public ScopesResponseBody(List scps = null) { + if (scps == null) + scopes = new Scope[0]; + else + scopes = scps.ToArray(); + } + } + + public class VariablesResponseBody : ResponseBody + { + public Variable[] variables { get; } + + public VariablesResponseBody(List vars = null) { + if (vars == null) + variables = new Variable[0]; + else + variables = vars.ToArray(); + } + } + + public class ThreadsResponseBody : ResponseBody + { + public Thread[] threads { get; } + + public ThreadsResponseBody(List vars = null) { + if (vars == null) + threads = new Thread[0]; + else + threads = vars.ToArray(); + } + } + + public class EvaluateResponseBody : ResponseBody + { + public string result { get; } + public int variablesReference { get; } + + public EvaluateResponseBody(string value, int reff = 0) { + result = value; + variablesReference = reff; + } + } + + public class SetBreakpointsResponseBody : ResponseBody + { + public Breakpoint[] breakpoints { get; } + + public SetBreakpointsResponseBody(List bpts = null) { + if (bpts == null) + breakpoints = new Breakpoint[0]; + else + breakpoints = bpts.ToArray(); + } + } + + // ---- The Session -------------------------------------------------------- + + public abstract class DebugSession : ProtocolServer + { + private bool _debuggerLinesStartAt1; + private bool _debuggerPathsAreURI; + private bool _clientLinesStartAt1 = true; + private bool _clientPathsAreURI = true; + + + public DebugSession(bool debuggerLinesStartAt1, bool debuggerPathsAreURI = false) + { + _debuggerLinesStartAt1 = debuggerLinesStartAt1; + _debuggerPathsAreURI = debuggerPathsAreURI; + } + + public void SendResponse(Response response, dynamic body = null) + { + if (body != null) { + response.SetBody(body); + } + SendMessage(response); + } + + public void SendErrorResponse(Response response, int id, string format, dynamic arguments = null, bool user = true, bool telemetry = false) + { + var msg = new Message(id, format, arguments, user, telemetry); + var message = Utilities.ExpandVariables(msg.format, msg.variables); + response.SetErrorBody(message, new ErrorResponseBody(msg)); + SendMessage(response); + } + + protected override void DispatchRequest(string command, dynamic args, Response response) + { + if (args == null) { + args = new { }; + } + + try { + switch (command) { + + case "initialize": + if (args.linesStartAt1 != null) { + _clientLinesStartAt1 = (bool)args.linesStartAt1; + } + var pathFormat = (string)args.pathFormat; + if (pathFormat != null) { + switch (pathFormat) { + case "uri": + _clientPathsAreURI = true; + break; + case "path": + _clientPathsAreURI = false; + break; + default: + SendErrorResponse(response, 1015, "initialize: bad value '{_format}' for pathFormat", new { _format = pathFormat }); + return; + } + } + Initialize(response, args); + break; + + case "launch": + Launch(response, args); + break; + + case "attach": + Attach(response, args); + break; + + case "disconnect": + Disconnect(response, args); + break; + + case "next": + Next(response, args); + break; + + case "continue": + Continue(response, args); + break; + + case "stepIn": + StepIn(response, args); + break; + + case "stepOut": + StepOut(response, args); + break; + + case "pause": + Pause(response, args); + break; + + case "stackTrace": + StackTrace(response, args); + break; + + case "scopes": + Scopes(response, args); + break; + + case "variables": + Variables(response, args); + break; + + case "source": + Source(response, args); + break; + + case "threads": + Threads(response, args); + break; + + case "setBreakpoints": + SetBreakpoints(response, args); + break; + + case "setFunctionBreakpoints": + SetFunctionBreakpoints(response, args); + break; + + case "setExceptionBreakpoints": + SetExceptionBreakpoints(response, args); + break; + + case "evaluate": + Evaluate(response, args); + break; + + default: + SendErrorResponse(response, 1014, "unrecognized request: {_request}", new { _request = command }); + break; + } + } + catch (Exception e) { + SendErrorResponse(response, 1104, "error while processing request '{_request}' (exception: {_exception})", new { _request = command, _exception = e.Message }); + } + + if (command == "disconnect") { + Stop(); + } + } + + public abstract void Initialize(Response response, dynamic args); + + public abstract void Launch(Response response, dynamic arguments); + + public abstract void Attach(Response response, dynamic arguments); + + public abstract void Disconnect(Response response, dynamic arguments); + + public virtual void SetFunctionBreakpoints(Response response, dynamic arguments) + { + } + + public virtual void SetExceptionBreakpoints(Response response, dynamic arguments) + { + } + + public abstract void SetBreakpoints(Response response, dynamic arguments); + + public abstract void Continue(Response response, dynamic arguments); + + public abstract void Next(Response response, dynamic arguments); + + public abstract void StepIn(Response response, dynamic arguments); + + public abstract void StepOut(Response response, dynamic arguments); + + public abstract void Pause(Response response, dynamic arguments); + + public abstract void StackTrace(Response response, dynamic arguments); + + public abstract void Scopes(Response response, dynamic arguments); + + public abstract void Variables(Response response, dynamic arguments); + + public virtual void Source(Response response, dynamic arguments) + { + SendErrorResponse(response, 1020, "Source not supported"); + } + + public abstract void Threads(Response response, dynamic arguments); + + public abstract void Evaluate(Response response, dynamic arguments); + + // protected + + protected int ConvertDebuggerLineToClient(int line) + { + if (_debuggerLinesStartAt1) { + return _clientLinesStartAt1 ? line : line - 1; + } + else { + return _clientLinesStartAt1 ? line + 1 : line; + } + } + + protected int ConvertClientLineToDebugger(int line) + { + if (_debuggerLinesStartAt1) { + return _clientLinesStartAt1 ? line : line + 1; + } + else { + return _clientLinesStartAt1 ? line - 1 : line; + } + } + + protected string ConvertDebuggerPathToClient(string path) + { + if (_debuggerPathsAreURI) { + if (_clientPathsAreURI) { + return path; + } + else { + Uri uri = new Uri(path); + return uri.LocalPath; + } + } + else { + if (_clientPathsAreURI) { + try { + var uri = new System.Uri(path); + return uri.AbsoluteUri; + } + catch { + return null; + } + } + else { + return path; + } + } + } + + protected string ConvertClientPathToDebugger(string clientPath) + { + if (clientPath == null) { + return null; + } + + if (_debuggerPathsAreURI) { + if (_clientPathsAreURI) { + return clientPath; + } + else { + var uri = new System.Uri(clientPath); + return uri.AbsoluteUri; + } + } + else { + if (_clientPathsAreURI) { + if (Uri.IsWellFormedUriString(clientPath, UriKind.Absolute)) { + Uri uri = new Uri(clientPath); + return uri.LocalPath; + } + Console.Error.WriteLine("path not well formed: '{0}'", clientPath); + return null; + } + else { + return clientPath; + } + } + } + } +} diff --git a/src/DebugServer/OscriptDebugSession.cs b/src/DebugServer/OscriptDebugSession.cs new file mode 100644 index 000000000..0493b1a39 --- /dev/null +++ b/src/DebugServer/OscriptDebugSession.cs @@ -0,0 +1,92 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using VSCodeDebug; + +namespace DebugServer +{ + class OscriptDebugSession : DebugSession + { + public OscriptDebugSession() : base(true, false) + { + } + + public override void Initialize(Response response, dynamic args) + { + throw new NotImplementedException(); + } + + public override void Launch(Response response, dynamic arguments) + { + throw new NotImplementedException(); + } + + public override void Attach(Response response, dynamic arguments) + { + throw new NotImplementedException(); + } + + public override void Disconnect(Response response, dynamic arguments) + { + throw new NotImplementedException(); + } + + public override void SetBreakpoints(Response response, dynamic arguments) + { + throw new NotImplementedException(); + } + + public override void Continue(Response response, dynamic arguments) + { + throw new NotImplementedException(); + } + + public override void Next(Response response, dynamic arguments) + { + throw new NotImplementedException(); + } + + public override void StepIn(Response response, dynamic arguments) + { + throw new NotImplementedException(); + } + + public override void StepOut(Response response, dynamic arguments) + { + throw new NotImplementedException(); + } + + public override void Pause(Response response, dynamic arguments) + { + throw new NotImplementedException(); + } + + public override void StackTrace(Response response, dynamic arguments) + { + throw new NotImplementedException(); + } + + public override void Scopes(Response response, dynamic arguments) + { + throw new NotImplementedException(); + } + + public override void Variables(Response response, dynamic arguments) + { + throw new NotImplementedException(); + } + + public override void Threads(Response response, dynamic arguments) + { + throw new NotImplementedException(); + } + + public override void Evaluate(Response response, dynamic arguments) + { + throw new NotImplementedException(); + } + } +} diff --git a/src/DebugServer/Program.cs b/src/DebugServer/Program.cs new file mode 100644 index 000000000..c82fd9782 --- /dev/null +++ b/src/DebugServer/Program.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DebugServer +{ + class Program + { + static void Main(string[] args) + { + bool showTrace = false; + + foreach (var argument in args) + { + switch (argument) + { + case "-trace": + showTrace = true; + break; + } + } + + StartSession(showTrace, Console.OpenStandardInput(), Console.OpenStandardOutput()); + + } + + private static void StartSession(bool showTrace, Stream input, Stream output) + { + var session = new OscriptDebugSession(); + session.TRACE = showTrace; + session.TRACE_RESPONSE = showTrace; + session.Start(input, output).Wait(); + } + } +} diff --git a/src/DebugServer/Properties/AssemblyInfo.cs b/src/DebugServer/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..6541516ca --- /dev/null +++ b/src/DebugServer/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("DebugServer")] +[assembly: AssemblyDescription("1Script Debug Server for VS Code")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("1Script Debug Server")] +[assembly: AssemblyCopyright("Copyright EvilBeaver© 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("c979f151-aa29-47e4-b020-3039ba0986d9")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/DebugServer/Protocol.cs b/src/DebugServer/Protocol.cs new file mode 100644 index 000000000..0127557dd --- /dev/null +++ b/src/DebugServer/Protocol.cs @@ -0,0 +1,274 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Text; +using System.IO; +using System.Threading.Tasks; +using System.Text.RegularExpressions; +using Newtonsoft.Json; + +namespace VSCodeDebug +{ + public class ProtocolMessage + { + public int seq; + public string type { get; } + + public ProtocolMessage(string typ) { + type = typ; + } + + public ProtocolMessage(string typ, int sq) { + type = typ; + seq = sq; + } + } + + public class Request : ProtocolMessage + { + public string command; + public dynamic arguments; + + public Request(int id, string cmd, dynamic arg) : base("request", id) { + command = cmd; + arguments = arg; + } + } + + /* + * subclasses of ResponseBody are serialized as the body of a response. + * Don't change their instance variables since that will break the debug protocol. + */ + public class ResponseBody { + // empty + } + + public class Response : ProtocolMessage + { + public bool success { get; private set; } + public string message { get; private set; } + public int request_seq { get; } + public string command { get; } + public ResponseBody body { get; private set; } + + public Response(Request req) : base("response") { + success = true; + request_seq = req.seq; + command = req.command; + } + + public void SetBody(ResponseBody bdy) { + success = true; + body = bdy; + } + + public void SetErrorBody(string msg, ResponseBody bdy = null) { + success = false; + message = msg; + body = bdy; + } + } + + public class Event : ProtocolMessage + { + [JsonProperty(PropertyName = "event")] + public string eventType { get; } + public dynamic body { get; } + + public Event(string type, dynamic bdy = null) : base("event") { + eventType = type; + body = bdy; + } + } + + /* + * The ProtocolServer can be used to implement a server that uses the VSCode debug protocol. + */ + public abstract class ProtocolServer + { + public bool TRACE; + public bool TRACE_RESPONSE; + + protected const int BUFFER_SIZE = 4096; + protected const string TWO_CRLF = "\r\n\r\n"; + protected static readonly Regex CONTENT_LENGTH_MATCHER = new Regex(@"Content-Length: (\d+)"); + + protected static readonly Encoding Encoding = System.Text.Encoding.UTF8; + + private int _sequenceNumber; + + private Stream _outputStream; + + private ByteBuffer _rawData; + private int _bodyLength; + + private bool _stopRequested; + + + public ProtocolServer() { + _sequenceNumber = 1; + _bodyLength = -1; + _rawData = new ByteBuffer(); + } + + public async Task Start(Stream inputStream, Stream outputStream) + { + _outputStream = outputStream; + + byte[] buffer = new byte[BUFFER_SIZE]; + + _stopRequested = false; + while (!_stopRequested) { + var read = await inputStream.ReadAsync(buffer, 0, buffer.Length); + + if (read == 0) { + // end of stream + break; + } + + if (read > 0) { + _rawData.Append(buffer, read); + ProcessData(); + } + } + } + + public void Stop() + { + _stopRequested = true; + } + + public void SendEvent(Event e) + { + SendMessage(e); + } + + protected abstract void DispatchRequest(string command, dynamic args, Response response); + + // ---- private ------------------------------------------------------------------------ + + private void ProcessData() + { + while (true) { + if (_bodyLength >= 0) { + if (_rawData.Length >= _bodyLength) { + var buf = _rawData.RemoveFirst(_bodyLength); + + _bodyLength = -1; + + Dispatch(Encoding.GetString(buf)); + + continue; // there may be more complete messages to process + } + } + else { + string s = _rawData.GetString(Encoding); + var idx = s.IndexOf(TWO_CRLF); + if (idx != -1) { + Match m = CONTENT_LENGTH_MATCHER.Match(s); + if (m.Success && m.Groups.Count == 2) { + _bodyLength = Convert.ToInt32(m.Groups[1].ToString()); + + _rawData.RemoveFirst(idx + TWO_CRLF.Length); + + continue; // try to handle a complete message + } + } + } + break; + } + } + + private void Dispatch(string req) + { + var request = JsonConvert.DeserializeObject(req); + if (request != null && request.type == "request") { + if (TRACE) + Console.Error.WriteLine(string.Format("C {0}: {1}", request.command, JsonConvert.SerializeObject(request.arguments))); + + var response = new Response(request); + + DispatchRequest(request.command, request.arguments, response); + + SendMessage(response); + } + } + + protected void SendMessage(ProtocolMessage message) + { + message.seq = _sequenceNumber++; + + if (TRACE_RESPONSE && message.type == "response") { + Console.Error.WriteLine(string.Format(" R: {0}", JsonConvert.SerializeObject(message))); + } + if (TRACE && message.type == "event") { + Event e = (Event)message; + Console.Error.WriteLine(string.Format("E {0}: {1}", e.eventType, JsonConvert.SerializeObject(e.body))); + } + + var data = ConvertToBytes(message); + try { + _outputStream.Write(data, 0, data.Length); + _outputStream.Flush(); + } + catch (Exception) { + // ignore + } + } + + private static byte[] ConvertToBytes(ProtocolMessage request) + { + var asJson = JsonConvert.SerializeObject(request); + byte[] jsonBytes = Encoding.GetBytes(asJson); + + string header = string.Format("Content-Length: {0}{1}", jsonBytes.Length, TWO_CRLF); + byte[] headerBytes = Encoding.GetBytes(header); + + byte[] data = new byte[headerBytes.Length + jsonBytes.Length]; + System.Buffer.BlockCopy(headerBytes, 0, data, 0, headerBytes.Length); + System.Buffer.BlockCopy(jsonBytes, 0, data, headerBytes.Length, jsonBytes.Length); + + return data; + } + } + + //-------------------------------------------------------------------------------------- + + class ByteBuffer + { + private byte[] _buffer; + + public ByteBuffer() { + _buffer = new byte[0]; + } + + public int Length { + get { return _buffer.Length; } + } + + public string GetString(Encoding enc) + { + return enc.GetString(_buffer); + } + + public void Append(byte[] b, int length) + { + byte[] newBuffer = new byte[_buffer.Length + length]; + System.Buffer.BlockCopy(_buffer, 0, newBuffer, 0, _buffer.Length); + System.Buffer.BlockCopy(b, 0, newBuffer, _buffer.Length, length); + _buffer = newBuffer; + } + + public byte[] RemoveFirst(int n) + { + byte[] b = new byte[n]; + System.Buffer.BlockCopy(_buffer, 0, b, 0, n); + byte[] newBuffer = new byte[_buffer.Length - n]; + System.Buffer.BlockCopy(_buffer, n, newBuffer, 0, _buffer.Length - n); + _buffer = newBuffer; + return b; + } + } +} diff --git a/src/DebugServer/Utilities.cs b/src/DebugServer/Utilities.cs new file mode 100644 index 000000000..96a1a6840 --- /dev/null +++ b/src/DebugServer/Utilities.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; + +namespace DebugServer +{ + static class Utilities + { + private static readonly Regex VARIABLE = new Regex(@"\{(\w+)\}"); + + public static string ExpandVariables(string format, dynamic variables, bool underscoredOnly = true) + { + if (variables == null) + { + variables = new { }; + } + Type type = variables.GetType(); + return VARIABLE.Replace(format, match => { + string name = match.Groups[1].Value; + if (!underscoredOnly || name.StartsWith("_")) + { + + PropertyInfo property = type.GetProperty(name); + if (property != null) + { + object value = property.GetValue(variables, null); + return value.ToString(); + } + return '{' + name + ": not found}"; + } + return match.Groups[0].Value; + }); + } + } +} diff --git a/src/DebugServer/packages.config b/src/DebugServer/packages.config new file mode 100644 index 000000000..9d64bf364 --- /dev/null +++ b/src/DebugServer/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file From 6b7c9fc3185c3f1b08482e2683b39eebd7cb19c8 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Thu, 9 Mar 2017 15:33:50 +0300 Subject: [PATCH 017/230] =?UTF-8?q?=D0=A0=D0=B5=D1=84=D0=B0=D0=BA=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=B8=D0=BD=D0=B3:=20=D0=BF=D0=BE=D0=BB=D1=83?= =?UTF-8?q?=D1=87=D0=B5=D0=BD=D0=B8=D0=B5=20=D1=81=D0=B2=D0=BE=D0=B9=D1=81?= =?UTF-8?q?=D1=82=D0=B2=20=D0=BF=D1=80=D0=B8=20=D0=B8=D0=BD=D0=B6=D0=B5?= =?UTF-8?q?=D0=BA=D1=82=D0=B5=20=D0=BE=D0=B1=D1=8A=D0=B5=D0=BA=D1=82=D0=B0?= =?UTF-8?q?=20=D0=B2=20=D0=B3=D0=BB=D0=BE=D0=B1.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Machine/IRuntimeContextInstance.cs | 25 +++++++++++++++++++ src/ScriptEngine/RuntimeEnvironment.cs | 14 +++-------- 2 files changed, 29 insertions(+), 10 deletions(-) diff --git a/src/ScriptEngine/Machine/IRuntimeContextInstance.cs b/src/ScriptEngine/Machine/IRuntimeContextInstance.cs index 7c07484fe..917a6ca57 100644 --- a/src/ScriptEngine/Machine/IRuntimeContextInstance.cs +++ b/src/ScriptEngine/Machine/IRuntimeContextInstance.cs @@ -36,4 +36,29 @@ public interface IRuntimeContextInstance } + public static class RCIHelperExtensions + { + // TODO: kill GetMethods in IRuntimeContextInstance + public static IEnumerable _GetMethods(this IRuntimeContextInstance context) + { + return context.GetMethods(); + } + + public static IEnumerable GetProperties(this IRuntimeContextInstance context) + { + VariableInfo[] infos = new VariableInfo[context.GetPropCount()]; + for (int i = 0; i < infos.Length; i++) + { + infos[i] = new VariableInfo() + { + Identifier = context.GetPropName(i), + Type = SymbolType.ContextProperty, + Index = i + }; + } + + return infos; + } + } + } \ No newline at end of file diff --git a/src/ScriptEngine/RuntimeEnvironment.cs b/src/ScriptEngine/RuntimeEnvironment.cs index b191f74a3..3f039c13f 100644 --- a/src/ScriptEngine/RuntimeEnvironment.cs +++ b/src/ScriptEngine/RuntimeEnvironment.cs @@ -112,20 +112,14 @@ private void RegisterSymbolScope(IAttachableContext provider, bool asDynamicScop { var scope = new SymbolScope(); scope.IsDynamicScope = asDynamicScope; - - IVariable[] vars; - MethodInfo[] methods; - IRuntimeContextInstance inst; - - provider.OnAttach(null, out vars, out methods, out inst); - + _symbolScopes.PushScope(scope); - foreach (var item in vars) + foreach (var item in provider.GetProperties()) { - _symbolScopes.DefineVariable(item.Name); + _symbolScopes.DefineVariable(item.Identifier); } - foreach (var item in methods) + foreach (var item in provider.GetMethods()) { _symbolScopes.DefineMethod(item); } From 94174f31121383cb351a401a3bb7c62df25e4f33 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Thu, 9 Mar 2017 15:34:41 +0300 Subject: [PATCH 018/230] =?UTF-8?q?=D0=A0=D0=B5=D1=84=D0=B0=D0=BA=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=B8=D0=BD=D0=B3:=20IAttachableContext=20=D1=82?= =?UTF-8?q?=D0=B5=D0=BF=D0=B5=D1=80=D1=8C=20=D1=8F=D0=B2=D0=BB=D1=8F=D0=B5?= =?UTF-8?q?=D1=82=D1=81=D1=8F=20IRuntimeContext?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Library/SystemGlobalContext.cs | 20 ++----------------- .../Machine/Contexts/GlobalContextBase.cs | 3 +-- .../Machine/Contexts/ScriptDrivenObject.cs | 3 +-- .../Machine/IAttachableContext.cs | 5 ++--- src/ScriptEngine/Machine/MachineInstance.cs | 5 ++--- src/ScriptEngine/Machine/PropertyBag.cs | 3 +-- src/oscript/CgiBehavior.cs | 3 +-- 7 files changed, 10 insertions(+), 32 deletions(-) diff --git a/src/ScriptEngine.HostedScript/Library/SystemGlobalContext.cs b/src/ScriptEngine.HostedScript/Library/SystemGlobalContext.cs index 92bbe81f7..850116fa9 100644 --- a/src/ScriptEngine.HostedScript/Library/SystemGlobalContext.cs +++ b/src/ScriptEngine.HostedScript/Library/SystemGlobalContext.cs @@ -482,28 +482,12 @@ public void FillPropertyValues(IRuntimeContextInstance acceptor, IRuntimeContext public void OnAttach(MachineInstance machine, out IVariable[] variables, - out MethodInfo[] methods, - out IRuntimeContextInstance instance) + out MethodInfo[] methods) { variables = _state; methods = GetMethods().ToArray(); - instance = this; } - - public IEnumerable GetProperties() - { - VariableInfo[] array = new VariableInfo[_properties.Count]; - foreach (var propKeyValue in _propHolder.GetProperties()) - { - var descr = new VariableInfo(); - descr.Identifier = propKeyValue.Key; - descr.Type = SymbolType.ContextProperty; - array[propKeyValue.Value] = descr; - } - - return array; - } - + public IEnumerable GetMethods() { var array = new MethodInfo[_methods.Count]; diff --git a/src/ScriptEngine/Machine/Contexts/GlobalContextBase.cs b/src/ScriptEngine/Machine/Contexts/GlobalContextBase.cs index 15965cc8d..c2ab6b966 100644 --- a/src/ScriptEngine/Machine/Contexts/GlobalContextBase.cs +++ b/src/ScriptEngine/Machine/Contexts/GlobalContextBase.cs @@ -122,11 +122,10 @@ public virtual void CallAsFunction(int methodNumber, IValue[] arguments, out IVa #region IAttachableContext members - public virtual void OnAttach(MachineInstance machine, out IVariable[] variables, out MethodInfo[] methods, out IRuntimeContextInstance instance) + public virtual void OnAttach(MachineInstance machine, out IVariable[] variables, out MethodInfo[] methods) { variables = new IVariable[0]; methods = GetMethods().ToArray(); - instance = this; } public virtual IEnumerable GetMethods() diff --git a/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs b/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs index 54bbc5706..14119a057 100644 --- a/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs +++ b/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs @@ -196,13 +196,12 @@ protected virtual IValue CallOwnFunction(int index, IValue[] arguments) #region IAttachableContext Members - public void OnAttach(MachineInstance machine, out IVariable[] variables, out MethodInfo[] methods, out IRuntimeContextInstance instance) + public void OnAttach(MachineInstance machine, out IVariable[] variables, out MethodInfo[] methods) { UpdateState(); variables = _state; methods = AttachMethods(); - instance = this; _machine = machine; diff --git a/src/ScriptEngine/Machine/IAttachableContext.cs b/src/ScriptEngine/Machine/IAttachableContext.cs index baaaadaa7..3d90d3439 100644 --- a/src/ScriptEngine/Machine/IAttachableContext.cs +++ b/src/ScriptEngine/Machine/IAttachableContext.cs @@ -11,12 +11,11 @@ This Source Code Form is subject to the terms of the namespace ScriptEngine.Machine { - public interface IAttachableContext + public interface IAttachableContext : IRuntimeContextInstance { void OnAttach(MachineInstance machine, out IVariable[] variables, - out MethodInfo[] methods, - out IRuntimeContextInstance instance); + out MethodInfo[] methods); } } diff --git a/src/ScriptEngine/Machine/MachineInstance.cs b/src/ScriptEngine/Machine/MachineInstance.cs index eb2a4bb51..14a46e35e 100644 --- a/src/ScriptEngine/Machine/MachineInstance.cs +++ b/src/ScriptEngine/Machine/MachineInstance.cs @@ -51,13 +51,12 @@ public void AttachContext(IAttachableContext context, bool detachable) { IVariable[] vars; MethodInfo[] methods; - IRuntimeContextInstance instance; - context.OnAttach(this, out vars, out methods, out instance); + context.OnAttach(this, out vars, out methods); var scope = new Scope() { Variables = vars, Methods = methods, - Instance = instance, + Instance = context, Detachable = detachable }; diff --git a/src/ScriptEngine/Machine/PropertyBag.cs b/src/ScriptEngine/Machine/PropertyBag.cs index 45dab6c9c..2aaca2122 100644 --- a/src/ScriptEngine/Machine/PropertyBag.cs +++ b/src/ScriptEngine/Machine/PropertyBag.cs @@ -78,7 +78,7 @@ public int Count #region IAttachableContext Members - public void OnAttach(MachineInstance machine, out IVariable[] variables, out MethodInfo[] methods, out IRuntimeContextInstance instance) + public void OnAttach(MachineInstance machine, out IVariable[] variables, out MethodInfo[] methods) { variables = new IVariable[this.Count]; var props = GetProperties().OrderBy(x => x.Value).Select(x=>x.Key).ToArray(); @@ -90,7 +90,6 @@ public void OnAttach(MachineInstance machine, out IVariable[] variables, out Met } methods = new MethodInfo[0]; - instance = this; } #endregion diff --git a/src/oscript/CgiBehavior.cs b/src/oscript/CgiBehavior.cs index 8e7dcb53e..e318052b3 100644 --- a/src/oscript/CgiBehavior.cs +++ b/src/oscript/CgiBehavior.cs @@ -153,11 +153,10 @@ public string[] GetCommandLineArguments() #endregion - public void OnAttach(MachineInstance machine, out IVariable[] variables, out MethodInfo[] methods, out IRuntimeContextInstance instance) + public void OnAttach(MachineInstance machine, out IVariable[] variables, out MethodInfo[] methods) { variables = new IVariable[0]; methods = (MethodInfo[])GetMethods(); - instance = this; } public IEnumerable GetMethods() From 817c97fa3a6f0f2c57fb5a831fba3e8d15de3155 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Thu, 9 Mar 2017 19:23:52 +0300 Subject: [PATCH 019/230] =?UTF-8?q?=D0=A0=D0=B5=D1=84=D0=B0=D0=BA=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=B8=D0=BD=D0=B3=20=D0=BF=D0=BE=D0=BB=D1=83=D1=87?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=BA=D0=BE=D0=BB=D0=B8=D1=87=D0=B5?= =?UTF-8?q?=D1=81=D1=82=D0=B2=D0=B0=20=D0=BC=D0=B5=D1=82=D0=BE=D0=B4=D0=BE?= =?UTF-8?q?=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Library/CommandLineArguments.cs | 4 ++-- .../Library/FixedStructureImpl.cs | 7 ++----- .../Library/StringOperations.cs | 9 ++------- .../Library/StructureImpl.cs | 7 ++----- .../Library/SystemGlobalContext.cs | 7 ++++++- src/ScriptEngine/Machine/Contexts/AutoContext.cs | 7 ++----- .../Machine/Contexts/ContextIValueImpl.cs | 2 +- .../Machine/Contexts/DynamicPropertiesHolder.cs | 1 - .../Machine/Contexts/GlobalContextBase.cs | 12 +++--------- .../Machine/Contexts/ReflectableSDO.cs | 4 ++-- .../Machine/Contexts/UserScriptContextInstance.cs | 12 +++--------- .../Machine/IRuntimeContextInstance.cs | 15 ++++++++++----- src/oscript/CgiBehavior.cs | 14 ++++---------- 13 files changed, 39 insertions(+), 62 deletions(-) diff --git a/src/ScriptEngine.HostedScript/Library/CommandLineArguments.cs b/src/ScriptEngine.HostedScript/Library/CommandLineArguments.cs index 91932abea..694cfd28a 100644 --- a/src/ScriptEngine.HostedScript/Library/CommandLineArguments.cs +++ b/src/ScriptEngine.HostedScript/Library/CommandLineArguments.cs @@ -56,9 +56,9 @@ public override int FindMethod(string name) throw RuntimeException.MethodNotFoundException(name); } - public override IEnumerable GetMethods() + public override int GetMethodsCount() { - yield return GetMethodInfo(0); + return 1; } public override void CallAsFunction(int methodNumber, IValue[] arguments, out IValue retValue) diff --git a/src/ScriptEngine.HostedScript/Library/FixedStructureImpl.cs b/src/ScriptEngine.HostedScript/Library/FixedStructureImpl.cs index 888da444d..d3689a22b 100644 --- a/src/ScriptEngine.HostedScript/Library/FixedStructureImpl.cs +++ b/src/ScriptEngine.HostedScript/Library/FixedStructureImpl.cs @@ -93,12 +93,9 @@ public override int FindMethod(string name) #region IReflectableContext Members - public override IEnumerable GetMethods() + public override int GetMethodsCount() { - for (int i = 0; i < _methods.Count; i++) - { - yield return _methods.GetMethodInfo(i); - } + return _methods.Count; } #endregion diff --git a/src/ScriptEngine.HostedScript/Library/StringOperations.cs b/src/ScriptEngine.HostedScript/Library/StringOperations.cs index 7f43c1368..18cafa857 100644 --- a/src/ScriptEngine.HostedScript/Library/StringOperations.cs +++ b/src/ScriptEngine.HostedScript/Library/StringOperations.cs @@ -222,14 +222,9 @@ public override int FindMethod(string name) return base.FindMethod(name); } - public override IEnumerable GetMethods() + public override int GetMethodsCount() { - var fullList = new List(base.GetMethods()); - var strTemplateMethodInfo = CreateStrTemplateMethodInfo(); - - fullList.Add(strTemplateMethodInfo); - return fullList; - + return base.GetMethodsCount() + 1; } private static MethodInfo CreateStrTemplateMethodInfo() diff --git a/src/ScriptEngine.HostedScript/Library/StructureImpl.cs b/src/ScriptEngine.HostedScript/Library/StructureImpl.cs index 99b33835c..3f7448db5 100644 --- a/src/ScriptEngine.HostedScript/Library/StructureImpl.cs +++ b/src/ScriptEngine.HostedScript/Library/StructureImpl.cs @@ -145,12 +145,9 @@ public override int FindMethod(string name) #region IReflectableContext Members - public override IEnumerable GetMethods() + public override int GetMethodsCount() { - for (int i = 0; i < _methods.Count; i++) - { - yield return _methods.GetMethodInfo(i); - } + return _methods.Count; } #endregion diff --git a/src/ScriptEngine.HostedScript/Library/SystemGlobalContext.cs b/src/ScriptEngine.HostedScript/Library/SystemGlobalContext.cs index 850116fa9..bbc81c59b 100644 --- a/src/ScriptEngine.HostedScript/Library/SystemGlobalContext.cs +++ b/src/ScriptEngine.HostedScript/Library/SystemGlobalContext.cs @@ -18,7 +18,7 @@ namespace ScriptEngine.HostedScript.Library /// Глобальный контекст. Представляет глобально доступные свойства и методы. /// [GlobalContext(Category="Процедуры и функции взаимодействия с системой", ManualRegistration=true)] - class SystemGlobalContext : IRuntimeContextInstance, IAttachableContext + class SystemGlobalContext : IAttachableContext { private IVariable[] _state; private CommandLineArguments _args; @@ -574,6 +574,11 @@ public MethodInfo GetMethodInfo(int methodNumber) return _methods.GetMethodInfo(methodNumber); } + public int GetMethodsCount() + { + return _methods.Count; + } + public void CallAsProcedure(int methodNumber, IValue[] arguments) { _methods.GetMethod(methodNumber)(this, arguments); diff --git a/src/ScriptEngine/Machine/Contexts/AutoContext.cs b/src/ScriptEngine/Machine/Contexts/AutoContext.cs index 9f12272f4..fb4c8caf0 100644 --- a/src/ScriptEngine/Machine/Contexts/AutoContext.cs +++ b/src/ScriptEngine/Machine/Contexts/AutoContext.cs @@ -69,12 +69,9 @@ public override int FindMethod(string name) return _methods.FindMethod(name); } - public override IEnumerable GetMethods() + public override int GetMethodsCount() { - for (int i = 0; i < _methods.Count; i++) - { - yield return _methods.GetMethodInfo(i); - } + return _methods.Count; } public override MethodInfo GetMethodInfo(int methodNumber) diff --git a/src/ScriptEngine/Machine/Contexts/ContextIValueImpl.cs b/src/ScriptEngine/Machine/Contexts/ContextIValueImpl.cs index 2506813b9..f1edaf825 100644 --- a/src/ScriptEngine/Machine/Contexts/ContextIValueImpl.cs +++ b/src/ScriptEngine/Machine/Contexts/ContextIValueImpl.cs @@ -178,7 +178,7 @@ public virtual string GetPropName(int propNum) throw new NotImplementedException(); } - public virtual IEnumerable GetMethods() + public virtual int GetMethodsCount() { throw new NotImplementedException(); } diff --git a/src/ScriptEngine/Machine/Contexts/DynamicPropertiesHolder.cs b/src/ScriptEngine/Machine/Contexts/DynamicPropertiesHolder.cs index a7c545527..a004b15f6 100644 --- a/src/ScriptEngine/Machine/Contexts/DynamicPropertiesHolder.cs +++ b/src/ScriptEngine/Machine/Contexts/DynamicPropertiesHolder.cs @@ -34,7 +34,6 @@ public int RegisterProperty(string name) public void RemoveProperty(string name) { - var idx = _propNumbers[name]; _propNumbers.Remove(name); } diff --git a/src/ScriptEngine/Machine/Contexts/GlobalContextBase.cs b/src/ScriptEngine/Machine/Contexts/GlobalContextBase.cs index c2ab6b966..7424b7cec 100644 --- a/src/ScriptEngine/Machine/Contexts/GlobalContextBase.cs +++ b/src/ScriptEngine/Machine/Contexts/GlobalContextBase.cs @@ -125,18 +125,12 @@ public virtual void CallAsFunction(int methodNumber, IValue[] arguments, out IVa public virtual void OnAttach(MachineInstance machine, out IVariable[] variables, out MethodInfo[] methods) { variables = new IVariable[0]; - methods = GetMethods().ToArray(); + methods = this.GetMethods().ToArray(); } - public virtual IEnumerable GetMethods() + public virtual int GetMethodsCount() { - var array = new MethodInfo[_methods.Count]; - for (int i = 0; i < _methods.Count; i++) - { - array[i] = _methods.GetMethodInfo(i); - } - - return array; + return _methods.Count; } #endregion diff --git a/src/ScriptEngine/Machine/Contexts/ReflectableSDO.cs b/src/ScriptEngine/Machine/Contexts/ReflectableSDO.cs index 0ad534b2a..dbfba83f5 100644 --- a/src/ScriptEngine/Machine/Contexts/ReflectableSDO.cs +++ b/src/ScriptEngine/Machine/Contexts/ReflectableSDO.cs @@ -335,9 +335,9 @@ public string GetPropName(int propNum) return _instance.GetPropName(propNum); } - public IEnumerable GetMethods() + public int GetMethodsCount() { - return _instance.GetMethods(); + return _instance.GetMethodsCount(); } public int FindMethod(string name) diff --git a/src/ScriptEngine/Machine/Contexts/UserScriptContextInstance.cs b/src/ScriptEngine/Machine/Contexts/UserScriptContextInstance.cs index 6fa32ed82..4be2794d3 100644 --- a/src/ScriptEngine/Machine/Contexts/UserScriptContextInstance.cs +++ b/src/ScriptEngine/Machine/Contexts/UserScriptContextInstance.cs @@ -82,17 +82,11 @@ protected override string GetOwnPropName(int index) var prop = _module.ExportedProperies[index]; return prop.SymbolicName; } - - #region IReflectableContext Members - public override IEnumerable GetMethods() + public override int GetMethodsCount() { - foreach (var item in _module.ExportedMethods) - { - yield return GetMethodInfo(item.Index); - } + return _module.ExportedMethods.Length; } - - #endregion + } } diff --git a/src/ScriptEngine/Machine/IRuntimeContextInstance.cs b/src/ScriptEngine/Machine/IRuntimeContextInstance.cs index 917a6ca57..03d72be51 100644 --- a/src/ScriptEngine/Machine/IRuntimeContextInstance.cs +++ b/src/ScriptEngine/Machine/IRuntimeContextInstance.cs @@ -27,9 +27,9 @@ public interface IRuntimeContextInstance int GetPropCount(); string GetPropName(int propNum); - - IEnumerable GetMethods(); + int FindMethod(string name); + int GetMethodsCount(); MethodInfo GetMethodInfo(int methodNumber); void CallAsProcedure(int methodNumber, IValue[] arguments); void CallAsFunction(int methodNumber, IValue[] arguments, out IValue retValue); @@ -38,10 +38,15 @@ public interface IRuntimeContextInstance public static class RCIHelperExtensions { - // TODO: kill GetMethods in IRuntimeContextInstance - public static IEnumerable _GetMethods(this IRuntimeContextInstance context) + public static IEnumerable GetMethods(this IRuntimeContextInstance context) { - return context.GetMethods(); + MethodInfo[] methods = new MethodInfo[context.GetMethodsCount()]; + for (int i = 0; i < methods.Length; i++) + { + methods[i] = context.GetMethodInfo(i); + } + + return methods; } public static IEnumerable GetProperties(this IRuntimeContextInstance context) diff --git a/src/oscript/CgiBehavior.cs b/src/oscript/CgiBehavior.cs index e318052b3..bf4bcf46f 100644 --- a/src/oscript/CgiBehavior.cs +++ b/src/oscript/CgiBehavior.cs @@ -16,7 +16,7 @@ This Source Code Form is subject to the terms of the namespace oscript { - class CgiBehavior : AppBehavior, IHostApplication, IRuntimeContextInstance, IAttachableContext + class CgiBehavior : AppBehavior, IHostApplication, IAttachableContext { private bool _isContentEchoed; private readonly HashSet _headersWritten = new HashSet(StringComparer.OrdinalIgnoreCase); @@ -156,18 +156,12 @@ public string[] GetCommandLineArguments() public void OnAttach(MachineInstance machine, out IVariable[] variables, out MethodInfo[] methods) { variables = new IVariable[0]; - methods = (MethodInfo[])GetMethods(); + methods = this.GetMethods().ToArray(); } - public IEnumerable GetMethods() + public int GetMethodsCount() { - var array = new MethodInfo[_methods.Count]; - for (int i = 0; i < _methods.Count; i++) - { - array[i] = _methods.GetMethodInfo(i); - } - - return array; + return _methods.Count; } #region IRuntimeContextInstance Members From c975e910ffa8b604323ab077d7113c466572d8ff Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Thu, 9 Mar 2017 19:26:24 +0300 Subject: [PATCH 020/230] =?UTF-8?q?=D0=9D=D0=B5=D0=B8=D1=81=D0=BF=D0=BE?= =?UTF-8?q?=D0=BB=D1=8C=D0=B7=D1=83=D0=B5=D0=BC=D0=BE=D0=B5=20=D0=BF=D0=B5?= =?UTF-8?q?=D1=80=D0=B5=D1=87=D0=B8=D1=81=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine.HostedScript/LibraryLoader.cs | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/ScriptEngine.HostedScript/LibraryLoader.cs b/src/ScriptEngine.HostedScript/LibraryLoader.cs index a1e06b298..98602c257 100644 --- a/src/ScriptEngine.HostedScript/LibraryLoader.cs +++ b/src/ScriptEngine.HostedScript/LibraryLoader.cs @@ -30,14 +30,7 @@ private struct DelayLoadedScriptData public string identifier; public bool asClass; } - - private enum MethodNumbers - { - AddClass, - AddProperty, - LastNotAMethod - } - + private LibraryLoader(LoadedModuleHandle moduleHandle, RuntimeEnvironment _env, ScriptingEngine _engine): base(moduleHandle) { this._env = _env; From 4b2fddf0957be796d7ecf7c923126639a9192e93 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Thu, 9 Mar 2017 19:45:07 +0300 Subject: [PATCH 021/230] =?UTF-8?q?=D0=98=D0=B4=D0=B5=D0=BD=D1=82=D0=B8?= =?UTF-8?q?=D1=84=D0=B8=D0=BA=D0=B0=D1=82=D0=BE=D1=80=D1=8B=20=D0=B4=D0=BB?= =?UTF-8?q?=D1=8F=20COM=20=D1=81=D0=B4=D0=B5=D0=BB=D0=B0=D0=BD=D1=8B=20?= =?UTF-8?q?=D0=B8=D0=BD=D0=BA=D1=80=D0=B5=D0=BC=D0=B5=D0=BD=D1=82=D0=B0?= =?UTF-8?q?=D0=BB=D1=8C=D0=BD=D1=8B=D0=BC=D0=B8,=20=D0=B0=20=D0=BD=D0=B5?= =?UTF-8?q?=20=D0=B2=20=D0=B2=D0=B8=D0=B4=D0=B5=20dispId.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Machine/ComReflectionNameToIdMapper.cs | 12 ++--- .../Contexts/UnmanagedRCWComContext.cs | 53 +++++++++++-------- 2 files changed, 35 insertions(+), 30 deletions(-) diff --git a/src/ScriptEngine/Machine/ComReflectionNameToIdMapper.cs b/src/ScriptEngine/Machine/ComReflectionNameToIdMapper.cs index c7c5d8051..b044a75a4 100644 --- a/src/ScriptEngine/Machine/ComReflectionNameToIdMapper.cs +++ b/src/ScriptEngine/Machine/ComReflectionNameToIdMapper.cs @@ -15,14 +15,10 @@ namespace ScriptEngine.Machine class ComReflectionNameToIdMapper { private readonly Type _reflectedType; - - readonly IndexedNamesCollection _propertyNames; - - readonly IndexedNamesCollection _methodNames; - - readonly List _propertyCache; - - readonly List _methodsCache; + private readonly IndexedNamesCollection _propertyNames; + private readonly IndexedNamesCollection _methodNames; + private readonly List _propertyCache; + private readonly List _methodsCache; public ComReflectionNameToIdMapper(Type type) { diff --git a/src/ScriptEngine/Machine/Contexts/UnmanagedRCWComContext.cs b/src/ScriptEngine/Machine/Contexts/UnmanagedRCWComContext.cs index 91327656e..a61732624 100644 --- a/src/ScriptEngine/Machine/Contexts/UnmanagedRCWComContext.cs +++ b/src/ScriptEngine/Machine/Contexts/UnmanagedRCWComContext.cs @@ -19,10 +19,9 @@ class UnmanagedRCWComContext : COMWrapperContext private const uint E_DISP_MEMBERNOTFOUND = 0x80020003; private bool? _isIndexed; - private readonly Dictionary _dispIdCache = new Dictionary(StringComparer.InvariantCultureIgnoreCase); - private readonly Dictionary _membersCache = new Dictionary(); - private readonly Dictionary _methodBinding = new Dictionary(); - + private readonly Dictionary _dispIdIndexes = new Dictionary(StringComparer.InvariantCultureIgnoreCase); + private readonly List _dispIds = new List(); + public UnmanagedRCWComContext(object instance) { _instance = instance; @@ -41,10 +40,9 @@ private void InitByInstance() protected override void Dispose(bool manualDispose) { base.Dispose(manualDispose); - - _membersCache.Clear(); - _methodBinding.Clear(); - _dispIdCache.Clear(); + + _dispIdIndexes.Clear(); + _dispIds.Clear(); if (_instance != null) { @@ -131,12 +129,15 @@ public override object UnderlyingObject public override int FindProperty(string name) { - int dispId; - if (!_dispIdCache.TryGetValue(name, out dispId)) + int knownDIIndex; + if (!_dispIdIndexes.TryGetValue(name, out knownDIIndex)) { + int dispId; if (DispatchUtility.TryGetDispId(_instance, name, out dispId)) { - _dispIdCache.Add(name, dispId); + knownDIIndex = _dispIds.Count; + _dispIds.Add(dispId); + _dispIdIndexes.Add(name, knownDIIndex); } else { @@ -144,7 +145,12 @@ public override int FindProperty(string name) } } - return dispId; + return knownDIIndex; + } + + private int GetDispIdByIndex(int index) + { + return _dispIds[index]; } public override bool IsPropReadable(int propNum) @@ -163,7 +169,7 @@ public override IValue GetPropValue(int propNum) { try { - var result = DispatchUtility.Invoke(_instance, propNum, null); + var result = DispatchUtility.Invoke(_instance, GetDispIdByIndex(propNum), null); return CreateIValue(result); } catch (System.Reflection.TargetInvocationException e) @@ -173,11 +179,11 @@ public override IValue GetPropValue(int propNum) } catch (System.MissingMemberException) { - throw RuntimeException.PropNotFoundException("dispid[" + propNum.ToString() + "]"); + throw RuntimeException.PropNotFoundException("dispid[" + GetDispIdByIndex(propNum) + "]"); } catch (System.MemberAccessException) { - throw RuntimeException.PropIsNotReadableException("dispid[" + propNum.ToString() + "]"); + throw RuntimeException.PropIsNotReadableException("dispid[" + GetDispIdByIndex(propNum) + "]"); } } @@ -204,7 +210,7 @@ public override void SetPropValue(int propNum, IValue newVal) { argToPass = MarshalIValue(newVal); } - DispatchUtility.InvokeSetProperty(_instance, propNum, argToPass); + DispatchUtility.InvokeSetProperty(_instance, GetDispIdByIndex(propNum), argToPass); } catch (System.Reflection.TargetInvocationException e) { @@ -213,22 +219,25 @@ public override void SetPropValue(int propNum, IValue newVal) } catch (System.MissingMemberException) { - throw RuntimeException.PropNotFoundException("dispid[" + propNum.ToString() + "]"); + throw RuntimeException.PropNotFoundException("dispid[" + GetDispIdByIndex(propNum) + "]"); } catch (System.MemberAccessException) { - throw RuntimeException.PropIsNotWritableException("dispid[" + propNum.ToString() + "]"); + throw RuntimeException.PropIsNotWritableException("dispid[" + GetDispIdByIndex(propNum) + "]"); } } public override int FindMethod(string name) { - int dispId; - if (!_dispIdCache.TryGetValue(name, out dispId)) + int knownDiIndex; + if (!_dispIdIndexes.TryGetValue(name, out knownDiIndex)) { + int dispId; if (DispatchUtility.TryGetDispId(_instance, name, out dispId)) { - _dispIdCache.Add(name, dispId); + knownDiIndex = _dispIds.Count; + _dispIds.Add(dispId); + _dispIdIndexes.Add(name, knownDiIndex); } else { @@ -236,7 +245,7 @@ public override int FindMethod(string name) } } - return dispId; + return knownDiIndex; } public override MethodInfo GetMethodInfo(int methodNumber) From 7a934fe1108649b542439e6d1ba60191d918a257 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Thu, 9 Mar 2017 19:48:34 +0300 Subject: [PATCH 022/230] =?UTF-8?q?=D0=92=D1=8B=D0=B4=D0=B5=D0=BB=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=BC=D0=B5=D1=82=D0=BE=D0=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Contexts/UnmanagedRCWComContext.cs | 33 +++++++++---------- 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/src/ScriptEngine/Machine/Contexts/UnmanagedRCWComContext.cs b/src/ScriptEngine/Machine/Contexts/UnmanagedRCWComContext.cs index a61732624..efc059bf7 100644 --- a/src/ScriptEngine/Machine/Contexts/UnmanagedRCWComContext.cs +++ b/src/ScriptEngine/Machine/Contexts/UnmanagedRCWComContext.cs @@ -129,23 +129,11 @@ public override object UnderlyingObject public override int FindProperty(string name) { - int knownDIIndex; - if (!_dispIdIndexes.TryGetValue(name, out knownDIIndex)) - { - int dispId; - if (DispatchUtility.TryGetDispId(_instance, name, out dispId)) - { - knownDIIndex = _dispIds.Count; - _dispIds.Add(dispId); - _dispIdIndexes.Add(name, knownDIIndex); - } - else - { - throw RuntimeException.PropNotFoundException(name); - } - } + var idx = FindMemberIndex(name); + if (idx < 0) + throw RuntimeException.PropNotFoundException(name); - return knownDIIndex; + return idx; } private int GetDispIdByIndex(int index) @@ -227,7 +215,7 @@ public override void SetPropValue(int propNum, IValue newVal) } } - public override int FindMethod(string name) + public int FindMemberIndex(string name) { int knownDiIndex; if (!_dispIdIndexes.TryGetValue(name, out knownDiIndex)) @@ -241,13 +229,22 @@ public override int FindMethod(string name) } else { - throw RuntimeException.MethodNotFoundException(name); + knownDiIndex = -1; } } return knownDiIndex; } + public override int FindMethod(string name) + { + var idx = FindMemberIndex(name); + if (idx < 0) + throw RuntimeException.MethodNotFoundException(name); + + return idx; + } + public override MethodInfo GetMethodInfo(int methodNumber) { return GetMethodDescription(methodNumber); From dfd29f3bdc494974895f5bdf2c8f78376caa4a4b Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Thu, 9 Mar 2017 20:27:02 +0300 Subject: [PATCH 023/230] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BE=D1=88=D0=B8=D0=B1=D0=BA=D0=B8=20=D1=81?= =?UTF-8?q?=D1=82=D0=B0=D1=80=D1=82=D0=B0=20=D0=BF=D1=80=D0=B8=D0=BB=D0=BE?= =?UTF-8?q?=D0=B6=D0=B5=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine.HostedScript/LibraryLoader.cs | 8 ++++++++ src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/ScriptEngine.HostedScript/LibraryLoader.cs b/src/ScriptEngine.HostedScript/LibraryLoader.cs index 98602c257..c0d1a1a0c 100644 --- a/src/ScriptEngine.HostedScript/LibraryLoader.cs +++ b/src/ScriptEngine.HostedScript/LibraryLoader.cs @@ -139,6 +139,14 @@ protected override int FindOwnProperty(string name) return base.FindOwnProperty(name); } + protected override string GetOwnPropName(int index) + { + if (index == 0) + return "ЭтотОбъект"; + + throw new ArgumentException(); + } + protected override bool IsOwnPropReadable(int index) { return true; diff --git a/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs b/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs index 14119a057..48c2df7be 100644 --- a/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs +++ b/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs @@ -62,7 +62,7 @@ public void InitOwnData() if (i < VARIABLE_COUNT) _state[i] = Variable.CreateContextPropertyReference(this, i, GetOwnPropName(i)); else - _state[i] = Variable.Create(ValueFactory.Create(), _module.Variables[i]); + _state[i] = Variable.Create(ValueFactory.Create(), _module.Variables[i-VARIABLE_COUNT]); } ReadExportedSymbols(_module.ExportedMethods, _methodSearchCache); From 1ad4588b6b9edceb5235368ac6e6f2d836026dfb Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sun, 12 Mar 2017 09:00:47 +0300 Subject: [PATCH 024/230] =?UTF-8?q?=D0=94=D0=BE=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D0=BA=D0=B0=20=D1=81=D0=B2=D0=BE=D0=B9=D1=81=D1=82=D0=B2?= =?UTF-8?q?=20=D1=83=20=D1=81=D1=82=D1=80=D0=BE=D0=BA=20=D1=82=D0=B0=D0=B1?= =?UTF-8?q?=D0=BB=D0=B8=D1=86=D0=B8=20=D0=B8=20=D0=B4=D0=B5=D1=80=D0=B5?= =?UTF-8?q?=D0=B2=D0=B0=20=D0=B7=D0=BD=D0=B0=D1=87=D0=B5=D0=BD=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Library/ValueTable/ValueTableRow.cs | 10 ++++++++++ .../Library/ValueTree/ValueTreeRow.cs | 10 ++++++++++ 2 files changed, 20 insertions(+) diff --git a/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableRow.cs b/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableRow.cs index bfc4982a9..77a8861dd 100644 --- a/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableRow.cs +++ b/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableRow.cs @@ -112,6 +112,16 @@ public override int FindProperty(string name) return C.ID; } + public override bool IsPropReadable(int propNum) + { + return true; + } + + public override bool IsPropWritable(int propNum) + { + return true; + } + public override IValue GetPropValue(int propNum) { ValueTableColumn C = Owner().Columns.FindColumnById(propNum); diff --git a/src/ScriptEngine.HostedScript/Library/ValueTree/ValueTreeRow.cs b/src/ScriptEngine.HostedScript/Library/ValueTree/ValueTreeRow.cs index 6a67d3686..c574d18d7 100644 --- a/src/ScriptEngine.HostedScript/Library/ValueTree/ValueTreeRow.cs +++ b/src/ScriptEngine.HostedScript/Library/ValueTree/ValueTreeRow.cs @@ -162,6 +162,16 @@ public override int FindProperty(string name) return column.ID; } + public override bool IsPropReadable(int propNum) + { + return true; + } + + public override bool IsPropWritable(int propNum) + { + return true; + } + public override IValue GetPropValue(int propNum) { var column = Owner().Columns.FindColumnById(propNum); From e4656347378048ef67b877e309c39e1b9a1cd17d Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sun, 12 Mar 2017 10:42:46 +0300 Subject: [PATCH 025/230] =?UTF-8?q?=D0=BF=D0=BB=D0=BE=D1=85=D0=BE=D0=B9=20?= =?UTF-8?q?=D1=80=D0=B5=D0=B7=D1=83=D0=BB=D1=8C=D1=82=D0=B0=D1=82=20merge?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine.HostedScript/HostedScriptEngine.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/ScriptEngine.HostedScript/HostedScriptEngine.cs b/src/ScriptEngine.HostedScript/HostedScriptEngine.cs index 2ee71207b..c9a19ffc2 100644 --- a/src/ScriptEngine.HostedScript/HostedScriptEngine.cs +++ b/src/ScriptEngine.HostedScript/HostedScriptEngine.cs @@ -232,7 +232,6 @@ public void EnableCodeStatistics(string outputFileName) public void Dispose() { _codeStat?.OutputCodeStat(); - _env.EnvironmentChanged -= LoadUserModuleAsProperty; } } } From f96914af9825b9570503ea33d115e59cf81a011f Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sun, 12 Mar 2017 10:43:07 +0300 Subject: [PATCH 026/230] =?UTF-8?q?=D0=A0=D0=B5=D1=84=D0=B0=D0=BA=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=B8=D0=BD=D0=B3=20=D1=80=D0=B0=D0=B7=D0=B1=D0=BE?= =?UTF-8?q?=D1=80=D0=B0=20=D0=BA=D0=BE=D0=BC=D0=B0=D0=BD=D0=B4=D0=BD=D0=BE?= =?UTF-8?q?=D0=B9=20=D1=81=D1=82=D1=80=D0=BE=D0=BA=D0=B8=20oscript.exe?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/oscript/BehaviorSelector.cs | 170 ++++++++++++++++++-------------- src/oscript/CmdLineHelper.cs | 39 ++++++++ src/oscript/oscript.csproj | 1 + 3 files changed, 135 insertions(+), 75 deletions(-) create mode 100644 src/oscript/CmdLineHelper.cs diff --git a/src/oscript/BehaviorSelector.cs b/src/oscript/BehaviorSelector.cs index aefa40ae2..777690a29 100644 --- a/src/oscript/BehaviorSelector.cs +++ b/src/oscript/BehaviorSelector.cs @@ -17,100 +17,120 @@ static class BehaviorSelector { public static AppBehavior Select(string[] cmdLineArgs) { - if (cmdLineArgs.Length == 0) - { + var helper = new CmdLineHelper(cmdLineArgs); + string arg = helper.Next(); + + if(arg == null) return new ShowUsageBehavior(); + + if (!arg.StartsWith("-")) + { + var path = arg; + return new ExecuteScriptBehavior(path, helper.Tail()); } - else + + var selected = SelectParametrized(helper); + if(selected == null) + selected = new ShowUsageBehavior(); + + return selected; + + } + + private static AppBehavior SelectParametrized(CmdLineHelper helper) + { + var param = helper.Current().ToLowerInvariant(); + if (param == "-measure") { - if (!cmdLineArgs[0].StartsWith("-")) + var path = helper.Next(); + if (path != null) { - var path = cmdLineArgs[0]; - return new ExecuteScriptBehavior(path, cmdLineArgs.Skip(1).ToArray()); - } else if (cmdLineArgs[0].ToLower() == "-measure") + return new MeasureBehavior(path, helper.Tail()); + } + } + else if (param == "-compile") + { + var path = helper.Next(); + if (path != null) { - if (cmdLineArgs.Length > 1) - { - var path = cmdLineArgs[1]; - return new MeasureBehavior(path, cmdLineArgs.Skip(2).ToArray()); - } - } else if (cmdLineArgs[0].ToLower() == "-compile") + return new ShowCompiledBehavior(path); + } + } + else if (param == "-check") + { + if (helper.Next() != null) { - if (cmdLineArgs.Length > 1) + bool cgi_mode = false; + var arg = helper.Current(); + if (arg.ToLowerInvariant() == "-cgi") { - var path = cmdLineArgs[1]; - return new ShowCompiledBehavior(path); + cgi_mode = true; + arg = helper.Next(); } - } else if (cmdLineArgs[0].ToLower() == "-check") - { - if (cmdLineArgs.Length > 1) - { - bool cgi_mode = false; - int paramIndex = 1; - if (cmdLineArgs[paramIndex].ToLower() == "-cgi") - { - ++paramIndex; - cgi_mode = true; - } - - var path = cmdLineArgs[paramIndex]; - ++paramIndex; - string env = null; - if (cmdLineArgs.Length > paramIndex && cmdLineArgs[paramIndex].StartsWith("-env=")) - { - env = cmdLineArgs[paramIndex].Substring(5); - } - return new CheckSyntaxBehavior(path, env, cgi_mode); - } - } else if (cmdLineArgs[0].ToLower() == "-make") - { - if (cmdLineArgs.Length == 3) + var path = arg; + var env = helper.Next(); + if (env != null && env.StartsWith("-env=")) { - var codepath = cmdLineArgs[1]; - var output = cmdLineArgs[2]; - return new MakeAppBehavior(codepath, output); + env = env.Substring(5); } - } else if (cmdLineArgs[0].ToLower() == "-cgi") - { - return new CgiBehavior(); - } else if (cmdLineArgs[0].ToLower() == "-version") + + return new CheckSyntaxBehavior(path, env, cgi_mode); + } + } + else if (param == "-make") + { + var codepath = helper.Next(); + var output = helper.Next(); + + if (output != null && codepath != null) { - return new ShowVersionBehavior(); - } else if (cmdLineArgs[0].StartsWith("-encoding=")) + return new MakeAppBehavior(codepath, output); + } + } + else if (param == "-cgi") + { + return new CgiBehavior(); + } + else if (param == "-version") + { + return new ShowVersionBehavior(); + } + else if (param.StartsWith("-encoding=")) + { + var prefixLen = ("-encoding=").Length; + if (param.Length > prefixLen) { - var prefixLen = ("-encoding=").Length; - if (cmdLineArgs[0].Length > prefixLen) + var encValue = param.Substring(prefixLen); + Encoding encoding; + try { - var encValue = cmdLineArgs[0].Substring(prefixLen); - Encoding encoding; - try - { - encoding = Encoding.GetEncoding(encValue); - } catch - { - Output.WriteLine("Wrong console encoding"); - encoding = null; - } - - if (encoding != null) - Program.ConsoleOutputEncoding = encoding; - - return Select(cmdLineArgs.Skip(1).ToArray()); + encoding = Encoding.GetEncoding(encValue); } - } else if (cmdLineArgs[0].StartsWith("-codestat=")) { - var prefixLen = ("-codestat=").Length; - if (cmdLineArgs[0].Length > prefixLen) + catch { - var outputStatFile = cmdLineArgs[0].Substring(prefixLen); - ScriptFileHelper.EnableCodeStatistics(outputStatFile); - return Select(cmdLineArgs.Skip(1).ToArray()); + Output.WriteLine("Wrong console encoding"); + encoding = null; } + + if (encoding != null) + Program.ConsoleOutputEncoding = encoding; + + return Select(helper.Tail()); } } - - return new ShowUsageBehavior(); - + else if (param.StartsWith("-codestat=")) + { + var prefixLen = ("-codestat=").Length; + if (param.Length > prefixLen) + { + var outputStatFile = param.Substring(prefixLen); + ScriptFileHelper.EnableCodeStatistics(outputStatFile); + return Select(helper.Tail()); + } + } + + return null; } } diff --git a/src/oscript/CmdLineHelper.cs b/src/oscript/CmdLineHelper.cs new file mode 100644 index 000000000..404eb1cbd --- /dev/null +++ b/src/oscript/CmdLineHelper.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace oscript +{ + class CmdLineHelper + { + private string[] _args; + private int _index = 0; + + public CmdLineHelper(string[] args) + { + _args = args; + } + + public string Next() + { + if (_index == _args.Length) + return null; + + return _args[_index++]; + } + + public string Current() + { + if (_index < 0 || _index >= _args.Length) + return null; + + return _args[_index]; + } + + public string[] Tail() + { + return _args.Skip(_index).ToArray(); + } + } +} diff --git a/src/oscript/oscript.csproj b/src/oscript/oscript.csproj index 53ef2012e..db3712ca3 100644 --- a/src/oscript/oscript.csproj +++ b/src/oscript/oscript.csproj @@ -94,6 +94,7 @@ + From 9a5012c2a00a2d350be619b896f01695f28fe407 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sun, 12 Mar 2017 11:18:28 +0300 Subject: [PATCH 027/230] =?UTF-8?q?=D0=95=D1=89=D0=B5=20=D0=BD=D0=B5=D0=BC?= =?UTF-8?q?=D0=BD=D0=BE=D0=B6=D0=BA=D0=BE=20=D1=80=D0=B5=D1=84=D0=B0=D0=BA?= =?UTF-8?q?=D1=82=D0=BE=D1=80=D0=B8=D0=BD=D0=B3=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/oscript/BehaviorSelector.cs | 93 +++++++++++++++++++-------------- 1 file changed, 54 insertions(+), 39 deletions(-) diff --git a/src/oscript/BehaviorSelector.cs b/src/oscript/BehaviorSelector.cs index 777690a29..3067ac4d1 100644 --- a/src/oscript/BehaviorSelector.cs +++ b/src/oscript/BehaviorSelector.cs @@ -58,25 +58,7 @@ private static AppBehavior SelectParametrized(CmdLineHelper helper) } else if (param == "-check") { - if (helper.Next() != null) - { - bool cgi_mode = false; - var arg = helper.Current(); - if (arg.ToLowerInvariant() == "-cgi") - { - cgi_mode = true; - arg = helper.Next(); - } - - var path = arg; - var env = helper.Next(); - if (env != null && env.StartsWith("-env=")) - { - env = env.Substring(5); - } - - return new CheckSyntaxBehavior(path, env, cgi_mode); - } + return ProcessCheckKey(helper); } else if (param == "-make") { @@ -98,26 +80,7 @@ private static AppBehavior SelectParametrized(CmdLineHelper helper) } else if (param.StartsWith("-encoding=")) { - var prefixLen = ("-encoding=").Length; - if (param.Length > prefixLen) - { - var encValue = param.Substring(prefixLen); - Encoding encoding; - try - { - encoding = Encoding.GetEncoding(encValue); - } - catch - { - Output.WriteLine("Wrong console encoding"); - encoding = null; - } - - if (encoding != null) - Program.ConsoleOutputEncoding = encoding; - - return Select(helper.Tail()); - } + return ProcessEncodingKey(helper); } else if (param.StartsWith("-codestat=")) { @@ -132,6 +95,58 @@ private static AppBehavior SelectParametrized(CmdLineHelper helper) return null; } + + private static AppBehavior ProcessCheckKey(CmdLineHelper helper) + { + if (helper.Next() != null) + { + bool cgi_mode = false; + var arg = helper.Current(); + if (arg.ToLowerInvariant() == "-cgi") + { + cgi_mode = true; + arg = helper.Next(); + } + + var path = arg; + var env = helper.Next(); + if (env != null && env.StartsWith("-env=")) + { + env = env.Substring(5); + } + + return new CheckSyntaxBehavior(path, env, cgi_mode); + } + + return null; + } + + private static AppBehavior ProcessEncodingKey(CmdLineHelper helper) + { + var param = helper.Current(); + var prefixLen = ("-encoding=").Length; + if (param.Length > prefixLen) + { + var encValue = param.Substring(prefixLen); + Encoding encoding; + try + { + encoding = Encoding.GetEncoding(encValue); + } + catch + { + Output.WriteLine("Wrong console encoding"); + encoding = null; + } + + if (encoding != null) + Program.ConsoleOutputEncoding = encoding; + + return Select(helper.Tail()); + } + + return null; + } } } From 6ddf6384141f395a3ea69e2797fd78229284e727 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sun, 12 Mar 2017 21:36:41 +0300 Subject: [PATCH 028/230] =?UTF-8?q?=D0=9E=D0=B1=D0=B2=D1=8F=D0=B7=D0=BA?= =?UTF-8?q?=D0=B0=20=D0=B4=D0=BB=D1=8F=20=D0=BE=D1=82=D0=BB=D0=B0=D0=B4?= =?UTF-8?q?=D1=87=D0=B8=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../HostedScriptEngine.cs | 6 ++ src/ScriptEngine.HostedScript/Process.cs | 2 + src/ScriptEngine/Machine/IDebugController.cs | 14 ++++ src/ScriptEngine/ScriptEngine.csproj | 1 + src/ScriptEngine/ScriptingEngine.cs | 2 + src/oscript/BehaviorSelector.cs | 23 ++++++ src/oscript/DebugBehavior.cs | 77 +++++++++++++++++++ src/oscript/DebugCommandDispatcher.cs | 64 +++++++++++++++ src/oscript/ExecuteScriptBehavior.cs | 3 + src/oscript/oscript.csproj | 2 + 10 files changed, 194 insertions(+) create mode 100644 src/ScriptEngine/Machine/IDebugController.cs create mode 100644 src/oscript/DebugBehavior.cs create mode 100644 src/oscript/DebugCommandDispatcher.cs diff --git a/src/ScriptEngine.HostedScript/HostedScriptEngine.cs b/src/ScriptEngine.HostedScript/HostedScriptEngine.cs index c9a19ffc2..888e21080 100644 --- a/src/ScriptEngine.HostedScript/HostedScriptEngine.cs +++ b/src/ScriptEngine.HostedScript/HostedScriptEngine.cs @@ -143,6 +143,12 @@ public ICodeSourceFactory Loader } } + public IDebugController DebugController + { + get { return _engine.DebugController; } + set { _engine.DebugController = value; } + } + private void InitializeDirectiveResolver() { var ignoreDirectiveResolver = new DirectiveIgnorer(); diff --git a/src/ScriptEngine.HostedScript/Process.cs b/src/ScriptEngine.HostedScript/Process.cs index 4cb3388da..8bcfd64b0 100644 --- a/src/ScriptEngine.HostedScript/Process.cs +++ b/src/ScriptEngine.HostedScript/Process.cs @@ -33,6 +33,7 @@ public int Start() { try { + _engine.DebugController?.WaitForExecutionSignal(); _engine.UpdateContexts(); _engine.NewObject(_module); return 0; @@ -48,6 +49,7 @@ public int Start() } finally { + _engine.DebugController?.NotifyProcessExit(); _engine.Dispose(); _engine = null; } diff --git a/src/ScriptEngine/Machine/IDebugController.cs b/src/ScriptEngine/Machine/IDebugController.cs new file mode 100644 index 000000000..68eacd143 --- /dev/null +++ b/src/ScriptEngine/Machine/IDebugController.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace ScriptEngine.Machine +{ + public interface IDebugController + { + void WaitForExecutionSignal(); + + void NotifyProcessExit(); + } +} diff --git a/src/ScriptEngine/ScriptEngine.csproj b/src/ScriptEngine/ScriptEngine.csproj index ae4b6524a..43a0e426e 100644 --- a/src/ScriptEngine/ScriptEngine.csproj +++ b/src/ScriptEngine/ScriptEngine.csproj @@ -139,6 +139,7 @@ + diff --git a/src/ScriptEngine/ScriptingEngine.cs b/src/ScriptEngine/ScriptingEngine.cs index 300687999..b7c395f5f 100644 --- a/src/ScriptEngine/ScriptingEngine.cs +++ b/src/ScriptEngine/ScriptingEngine.cs @@ -147,6 +147,8 @@ public AttachedScriptsFactory AttachedScriptsFactory } } + public IDebugController DebugController { get; set; } + public void SetCodeStatisticsCollector(ICodeStatCollector collector) { ProduceExtraCode = true; diff --git a/src/oscript/BehaviorSelector.cs b/src/oscript/BehaviorSelector.cs index 3067ac4d1..1cb9e9be9 100644 --- a/src/oscript/BehaviorSelector.cs +++ b/src/oscript/BehaviorSelector.cs @@ -92,6 +92,29 @@ private static AppBehavior SelectParametrized(CmdLineHelper helper) return Select(helper.Tail()); } } + else if (param == "-debug") + { + var arg = helper.Next(); + int port = 2801; + if (arg != null && arg.StartsWith("-port=")) + { + var prefixLen = ("-port=").Length; + if (arg.Length > prefixLen) + { + var value = arg.Substring(prefixLen); + if (!Int32.TryParse(value, out port)) + { + Output.WriteLine("Incorrect port: " + value); + return null; + } + } + } + else if(arg != null) + { + var path = arg; + return new DebugBehavior(port, path, helper.Tail()); + } + } return null; } diff --git a/src/oscript/DebugBehavior.cs b/src/oscript/DebugBehavior.cs new file mode 100644 index 000000000..972cbec0b --- /dev/null +++ b/src/oscript/DebugBehavior.cs @@ -0,0 +1,77 @@ +using System; +using System.Net; +using System.Net.Sockets; +using System.Threading; + +using ScriptEngine.HostedScript.Library.Net; +using ScriptEngine.Machine; + +namespace oscript +{ + internal class DebugBehavior : AppBehavior, IDebugController + { + private readonly string[] _args; + private readonly string _path; + private readonly int _port; + + private Thread _listenerThread; + private ManualResetEventSlim _debugCommandEvent; + private DebugCommandDispatcher _dispatcher = new DebugCommandDispatcher(); + + public DebugBehavior(int port, string path, string[] args) + { + _args = args; + _path = path; + _port = port; + _debugCommandEvent = new ManualResetEventSlim(); + } + + public override int Execute() + { + var executor = new ExecuteScriptBehavior(_path, _args); + executor.DebugController = this; + + return executor.Execute(); + } + + public void WaitForExecutionSignal() + { + _listenerThread = new Thread(ListenerThreadProc); + _listenerThread.Start(); + _debugCommandEvent.Wait(); // процесс 1скрипт не стартует, пока не получено разрешение от дебагера + + } + + public void NotifyProcessExit() + { + _dispatcher.Post("stop"); + } + + private void ListenerThreadProc() + { + _dispatcher.Start(this, _port); + + try + { + string command; + while (_dispatcher.GetCommand(out command)) + { + switch (command) + { + case "start": + _debugCommandEvent.Set(); + break; + case "stop": + _dispatcher.Stop(); + break; + } + } + } + catch(Exception e) + { + Output.WriteLine("DBG Listener:\n" + e.ToString()); + throw; + } + } + } +} \ No newline at end of file diff --git a/src/oscript/DebugCommandDispatcher.cs b/src/oscript/DebugCommandDispatcher.cs new file mode 100644 index 000000000..871ad0d3d --- /dev/null +++ b/src/oscript/DebugCommandDispatcher.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.Serialization.Formatters.Binary; +using System.Text; +using System.Threading; + +using ScriptEngine.Machine; + +namespace oscript +{ + class DebugCommandDispatcher + { + private IDebugController _controller; + private TcpListener _socket; + private TcpClient _connection; + + private bool _isStopped = false; + + public bool GetCommand(out string command) + { + if (_isStopped || _connection == null) + { + command = null; + return false; + } + + using (var stream = _connection.GetStream()) + { + var fmt = new BinaryFormatter(); + command = (string) fmt.Deserialize(stream); + return true; + } + + } + + public void Start(IDebugController controller, int port) + { + _controller = controller; + + var endPoint = new IPEndPoint(IPAddress.Loopback, port); + _socket = new TcpListener(endPoint); + _socket.Start(1); + + _connection = _socket.AcceptTcpClient(); + + } + + public void Stop() + { + _socket.Stop(); + _connection.Close(); + _connection = null; + _isStopped = true; + } + + public void Post(string stop) + { + throw new NotImplementedException(); + } + } +} diff --git a/src/oscript/ExecuteScriptBehavior.cs b/src/oscript/ExecuteScriptBehavior.cs index c23627e43..a6bea6df3 100644 --- a/src/oscript/ExecuteScriptBehavior.cs +++ b/src/oscript/ExecuteScriptBehavior.cs @@ -27,6 +27,8 @@ public ExecuteScriptBehavior(string path, string[] args) _path = path; } + public IDebugController DebugController { get; set; } + public override int Execute() { if (!System.IO.File.Exists(_path)) @@ -38,6 +40,7 @@ public override int Execute() SystemLogger.SetWriter(this); var hostedScript = new HostedScriptEngine(); + hostedScript.DebugController = DebugController; hostedScript.CustomConfig = ScriptFileHelper.CustomConfigPath(_path); ScriptFileHelper.OnBeforeScriptRead(hostedScript); var source = hostedScript.Loader.FromFile(_path); diff --git a/src/oscript/oscript.csproj b/src/oscript/oscript.csproj index db3712ca3..8133fe76f 100644 --- a/src/oscript/oscript.csproj +++ b/src/oscript/oscript.csproj @@ -96,6 +96,8 @@ + + From a4108b19b619df0205a54b2847f69b66e7deb6b0 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sun, 12 Mar 2017 22:51:22 +0300 Subject: [PATCH 029/230] =?UTF-8?q?=D0=97=D0=B0=D0=B3=D0=BE=D1=82=D0=BE?= =?UTF-8?q?=D0=B2=D0=BA=D0=B0=20=D0=B4=D0=BB=D1=8F=20=D0=BF=D0=B0=D0=BA?= =?UTF-8?q?=D0=B5=D1=82=D0=B0=20=D0=BE=D1=82=D0=BB=D0=B0=D0=B4=D1=87=D0=B8?= =?UTF-8?q?=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + src/DebugServer/package.json | 105 +++++++++++++++++++++++++++++++++++ 2 files changed, 106 insertions(+) create mode 100644 src/DebugServer/package.json diff --git a/.gitignore b/.gitignore index 1df48b45b..7e0e6cbe9 100644 --- a/.gitignore +++ b/.gitignore @@ -55,3 +55,4 @@ src/ScriptEngine.Snegopat/Snegopat_h.h # Песональный вспомагательный скрипт build.user.bat src/packages/ +src/DebugServer/node_modules/ diff --git a/src/DebugServer/package.json b/src/DebugServer/package.json new file mode 100644 index 000000000..d911de331 --- /dev/null +++ b/src/DebugServer/package.json @@ -0,0 +1,105 @@ +{ + "name": "oscript-debug", + "displayName": "OneScript Debug", + "version": "0.1.0", + "publisher": "EvilBeaver", + "description": "Visual Studio Code debugger extension for OneScript", + "icon": "images/mono-debug-icon.svg", + "categories": [ + "Debuggers" + ], + "author": { + "name": "EvilBeaver " + }, + "license": "MPL-2.0", + "private": true, + "engines": { + "vscode": "^1.0.0" + }, + "dependencies": { + }, + "repository": { + "type": "git", + "url": "https://github.com/EvilBeaver/OneScript.git" + }, + "bugs": { + "url": "https://github.com/EvilBeaver/OneScript/issues" + }, + "contributes": { + "breakpoints": [ + { + "language": "bsl" + } + ], + "debuggers": [ + { + "type": "oscript", + "label": "1Script Debugger", + "program": "./bin/DebugServer.exe", + "osx": { + "runtime": "mono" + }, + "linux": { + "runtime": "mono" + }, + "initialConfigurations": [ + { + "name": "%oscript.launch.config.name%", + "type": "oscript", + "request": "launch", + "program": "${workspaceRoot}/main.os", + "args": [], + "cwd": "${workspaceRoot}", + "preLaunchTask": "", + "runtimeExecutable": null, + "env": {}, + "debugPort": null + } + ], + "configurationAttributes": { + "launch": { + "required": [ "program" ], + "properties": { + "program": { + "type": "string", + "description": "%oscript.launch.program.description%" + }, + "args": { + "type": "array", + "description": "%oscript.launch.args.description%", + "items": { "type": "string" }, + "default": [] + }, + "cwd": { + "type": "string", + "description": "%oscript.launch.cwd.description%", + "default": "." + }, + "runtimeExecutable": { + "type": [ "string", "null" ], + "description": "%oscript.launch.runtimeExecutable.description%", + "default": null + }, + "runtimeArgs": { + "type": "array", + "description": "%oscript.launch.runtimeArgs.description%", + "items": { "type": "string" }, + "default": [] + }, + "env": { + "type": "object", + "description": "%oscript.launch.env.description%", + "default": {} + }, + "debugPort": { + "type": "number", + "description": "%oscript.launch.debugPort.description%", + "default": 2801 + } + } + } + } + } + ] + } +} \ No newline at end of file From 2eb20dd5efe10c3015f732c956be8d0012399923 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sun, 12 Mar 2017 22:53:59 +0300 Subject: [PATCH 030/230] =?UTF-8?q?=D0=97=D0=B0=D0=B3=D0=BE=D1=82=D0=BE?= =?UTF-8?q?=D0=B2=D0=BA=D0=B0=20=D0=B4=D0=BB=D1=8F=20=D0=BF=D0=B0=D0=BA?= =?UTF-8?q?=D0=B5=D1=82=D0=B0=20=D0=BE=D1=82=D0=BB=D0=B0=D0=B4=D1=87=D0=B8?= =?UTF-8?q?=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/1Script.sln | 1 - src/DebugServer/DebugServer.csproj | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/src/1Script.sln b/src/1Script.sln index 4f3ad7cd0..64d2fe515 100644 --- a/src/1Script.sln +++ b/src/1Script.sln @@ -87,7 +87,6 @@ Global {C979F151-AA29-47E4-B020-3039BA0986D9}.Release|Any CPU.ActiveCfg = Release|Any CPU {C979F151-AA29-47E4-B020-3039BA0986D9}.Release|Any CPU.Build.0 = Release|Any CPU {C979F151-AA29-47E4-B020-3039BA0986D9}.Release|x86.ActiveCfg = Release|Any CPU - {C979F151-AA29-47E4-B020-3039BA0986D9}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/src/DebugServer/DebugServer.csproj b/src/DebugServer/DebugServer.csproj index 4e44ef9a0..617490cb7 100644 --- a/src/DebugServer/DebugServer.csproj +++ b/src/DebugServer/DebugServer.csproj @@ -56,6 +56,7 @@ + From 7e66e1239d94201a2f186949501f59c9aba7170b Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sun, 19 Mar 2017 22:19:31 +0300 Subject: [PATCH 031/230] =?UTF-8?q?=D0=97=D0=B0=D0=BF=D1=83=D1=81=D0=BA=20?= =?UTF-8?q?=D0=B0=D0=B4=D0=B0=D0=BF=D1=82=D0=B5=D1=80=D0=B0=20=D0=BE=D1=82?= =?UTF-8?q?=D0=BB=D0=B0=D0=B4=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/DebugServer/.vscode/launch.json | 28 +++++++++ src/DebugServer/OscriptDebugSession.cs | 81 ++++++++++++++++++++++++-- 2 files changed, 103 insertions(+), 6 deletions(-) create mode 100644 src/DebugServer/.vscode/launch.json diff --git a/src/DebugServer/.vscode/launch.json b/src/DebugServer/.vscode/launch.json new file mode 100644 index 000000000..a3ee80929 --- /dev/null +++ b/src/DebugServer/.vscode/launch.json @@ -0,0 +1,28 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "type": "extensionHost", + "request": "launch", + "name": "Extension", + "runtimeExecutable": "${execPath}", + "args": [ + "--extensionDevelopmentPath=${workspaceRoot}" + ], + "stopOnEntry": false + }, + { + "type": "oscript", + "request": "launch", + "name": "Server", + "program": "${workspaceRoot}/bin/x86/Debug/DebugServer.exe", + "args": [ "-trace" ] + } + ], + "compounds": [ + { + "name": "Extension + Server", + "configurations": [ "Extension", "Server" ] + } + ] +} \ No newline at end of file diff --git a/src/DebugServer/OscriptDebugSession.cs b/src/DebugServer/OscriptDebugSession.cs index 0493b1a39..674c29c37 100644 --- a/src/DebugServer/OscriptDebugSession.cs +++ b/src/DebugServer/OscriptDebugSession.cs @@ -1,5 +1,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics; +using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -16,12 +18,79 @@ public OscriptDebugSession() : base(true, false) public override void Initialize(Response response, dynamic args) { - throw new NotImplementedException(); - } - - public override void Launch(Response response, dynamic arguments) - { - throw new NotImplementedException(); + SendResponse(response, new Capabilities() + { + supportsConditionalBreakpoints = false, + supportsFunctionBreakpoints = false, + supportsConfigurationDoneRequest = false, + exceptionBreakpointFilters = new dynamic[0], + supportsEvaluateForHovers = false + }); + + SendEvent(new InitializedEvent()); + } + + public override void Launch(Response response, dynamic args) + { + var startupScript = (string)args["program"]; + if (startupScript == null) + { + SendErrorResponse(response, 1001, "Property 'program' is missing or empty."); + return; + } + + if (!File.Exists(startupScript) && !Directory.Exists(startupScript)) + { + SendErrorResponse(response, 1002, "Program '{path}' does not exist.", new { path = startupScript }); + return; + } + + // validate argument 'args' + string[] arguments = null; + if (args.args != null) + { + arguments = args.args.ToObject(); + if (arguments != null && arguments.Length == 0) + { + arguments = null; + } + } + + // validate argument 'cwd' + var workingDirectory = (string)args.cwd; + if (workingDirectory != null) + { + workingDirectory = workingDirectory.Trim(); + if (workingDirectory.Length == 0) + { + SendErrorResponse(response, 3003, "Property 'cwd' is empty."); + return; + } + workingDirectory = ConvertClientPathToDebugger(workingDirectory); + if (!Directory.Exists(workingDirectory)) + { + SendErrorResponse(response, 3004, "Working directory '{path}' does not exist.", new { path = workingDirectory }); + return; + } + } + + // validate argument 'runtimeExecutable' + var runtimeExecutable = (string)args.runtimeExecutable; + if (runtimeExecutable != null) + { + runtimeExecutable = runtimeExecutable.Trim(); + if (runtimeExecutable.Length == 0) + { + SendErrorResponse(response, 3005, "Property 'runtimeExecutable' is empty."); + return; + } + runtimeExecutable = ConvertClientPathToDebugger(runtimeExecutable); + if (!File.Exists(runtimeExecutable)) + { + SendErrorResponse(response, 3006, "Runtime executable '{path}' does not exist.", new { path = runtimeExecutable }); + return; + } + } } public override void Attach(Response response, dynamic arguments) From ca7740d6dc2dfcef6bda9d2322364baf50885997 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B5=D1=80=D0=B3=D1=A3=D0=B9=20=D0=91=D0=B0=D1=82?= =?UTF-8?q?=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Tue, 21 Mar 2017 23:08:25 +0300 Subject: [PATCH 032/230] Makefile --- Makefile | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Makefile diff --git a/Makefile b/Makefile new file mode 100644 index 000000000..a30c15256 --- /dev/null +++ b/Makefile @@ -0,0 +1,28 @@ +PLATFORM="Any CPU" +CONFIGURATION=Release +SOURCEBINDIR=src/oscript/bin/${CONFIGURATION} +BIN_OUTPUTDIR=bin +LIB_OUTPUTDIR=lib +OSCRIPTEXE=${BIN_OUTPUTDIR}/oscript.exe +OPMOS=${LIB_OUTPUTDIR}/opm/opm.os +OPM="${OSCRIPTEXE} ${OPMOS}" + +all: dist + +dist: ${OSCRIPTEXE} lib + +lib: ${OSCRIPTEXE} + test -d ${LIB_OUTPUTDIR} && rm -rf ${LIB_OUTPUTDIR} + mkdir -p ${LIB_OUTPUTDIR} + cp -r oscript-library/src/* ${LIB_OUTPUTDIR} + +${OSCRIPTEXE}: + xbuild /p:Platform=${PLATFORM} /p:Configuration=${CONFIGURATION} src/1Script_Mono.sln + test -d ${BIN_OUTPUTDIR} || mkdir -p ${BIN_OUTPUTDIR} + cp ${SOURCEBINDIR}/*.dll ${BIN_OUTPUTDIR} + cp ${SOURCEBINDIR}/*.exe ${BIN_OUTPUTDIR} + cp ${SOURCEBINDIR}/*.cfg ${BIN_OUTPUTDIR} + +${OPMOS}: + +.PHONY: all install uninstall dist lib From cde4a7c8980e8cc0a6fe80e5c3574d74792b9f19 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Tue, 21 Mar 2017 23:44:08 +0300 Subject: [PATCH 033/230] =?UTF-8?q?=D0=94=D0=BE=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D0=BA=D0=B0=20=D0=BF=D0=BE=20=D0=A2=D0=97=20=D0=B8=20?= =?UTF-8?q?=D0=94=D0=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Library/ValueTable/ValueTableRow.cs | 10 ++++++++++ .../Library/ValueTree/ValueTreeRow.cs | 10 ++++++++++ 2 files changed, 20 insertions(+) diff --git a/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableRow.cs b/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableRow.cs index 77a8861dd..0f67a532e 100644 --- a/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableRow.cs +++ b/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableRow.cs @@ -102,6 +102,16 @@ public CollectionEnumerator GetManagedIterator() return new CollectionEnumerator(GetEnumerator()); } + public override int GetPropCount() + { + return Count(); + } + + public override string GetPropName(int propNum) + { + return Owner().Columns.GetPropName(propNum); + } + public override int FindProperty(string name) { ValueTableColumn C = Owner().Columns.FindColumnByName(name); diff --git a/src/ScriptEngine.HostedScript/Library/ValueTree/ValueTreeRow.cs b/src/ScriptEngine.HostedScript/Library/ValueTree/ValueTreeRow.cs index c574d18d7..17b53ca07 100644 --- a/src/ScriptEngine.HostedScript/Library/ValueTree/ValueTreeRow.cs +++ b/src/ScriptEngine.HostedScript/Library/ValueTree/ValueTreeRow.cs @@ -150,6 +150,16 @@ public CollectionEnumerator GetManagedIterator() private static readonly ContextPropertyMapper _properties = new ContextPropertyMapper(); + public override int GetPropCount() + { + return Count(); + } + + public override string GetPropName(int propNum) + { + return Owner().Columns.GetPropName(propNum); + } + public override int FindProperty(string name) { var column = Owner().Columns.FindColumnByName(name); From 4b00a26c65d6ac476bc87871c62c311dead01772 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sun, 26 Mar 2017 22:02:39 +0300 Subject: [PATCH 034/230] =?UTF-8?q?=D0=A1=D1=82=D0=B0=D1=80=D1=82=20=D1=81?= =?UTF-8?q?=D0=B5=D1=80=D0=B2=D0=B5=D1=80=D0=B0=20=D0=BE=D1=82=D0=BB=D0=B0?= =?UTF-8?q?=D0=B4=D0=BA=D0=B8=20=D0=B8=20=D0=BE=D1=82=D0=BB=D0=B0=D0=B6?= =?UTF-8?q?=D0=B8=D0=B2=D0=B0=D0=B5=D0=BC=D0=BE=D0=B3=D0=BE=20=D0=BF=D1=80?= =?UTF-8?q?=D0=BE=D1=86=D0=B5=D1=81=D1=81=D0=B0.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/DebugServer/.vscode/launch.json | 13 -- src/DebugServer/DebugServer.csproj | 2 + src/DebugServer/DebugSession.cs | 3 +- src/DebugServer/DebugeeProcess.cs | 117 ++++++++++++++++++ src/DebugServer/OscriptDebugSession.cs | 87 ++++++++++++- src/DebugServer/Program.cs | 51 +++++++- src/DebugServer/SessionLog.cs | 37 ++++++ src/DebugServer/Utilities.cs | 16 ++- src/DebugServer/package.json | 20 +-- src/ScriptEngine.HostedScript/Process.cs | 2 +- src/ScriptEngine/Machine/DebugEvent.cs | 7 ++ src/ScriptEngine/Machine/IDebugController.cs | 2 +- src/ScriptEngine/ScriptEngine.csproj | 1 + src/oscript/CmdLineHelper.cs | 7 +- src/oscript/DebugBehavior.cs | 58 ++------- src/oscript/DebugCommandDispatcher.cs | 64 ---------- .../DebugServer/DebugCommandCommunicator.cs | 110 ++++++++++++++++ .../DebugServer/OscriptDebugController.cs | 67 ++++++++++ src/oscript/ExecuteScriptBehavior.cs | 2 +- src/oscript/oscript.csproj | 4 +- 20 files changed, 518 insertions(+), 152 deletions(-) create mode 100644 src/DebugServer/DebugeeProcess.cs create mode 100644 src/DebugServer/SessionLog.cs create mode 100644 src/ScriptEngine/Machine/DebugEvent.cs delete mode 100644 src/oscript/DebugCommandDispatcher.cs create mode 100644 src/oscript/DebugServer/DebugCommandCommunicator.cs create mode 100644 src/oscript/DebugServer/OscriptDebugController.cs diff --git a/src/DebugServer/.vscode/launch.json b/src/DebugServer/.vscode/launch.json index a3ee80929..11c116d2f 100644 --- a/src/DebugServer/.vscode/launch.json +++ b/src/DebugServer/.vscode/launch.json @@ -10,19 +10,6 @@ "--extensionDevelopmentPath=${workspaceRoot}" ], "stopOnEntry": false - }, - { - "type": "oscript", - "request": "launch", - "name": "Server", - "program": "${workspaceRoot}/bin/x86/Debug/DebugServer.exe", - "args": [ "-trace" ] - } - ], - "compounds": [ - { - "name": "Extension + Server", - "configurations": [ "Extension", "Server" ] } ] } \ No newline at end of file diff --git a/src/DebugServer/DebugServer.csproj b/src/DebugServer/DebugServer.csproj index 617490cb7..69eef6f39 100644 --- a/src/DebugServer/DebugServer.csproj +++ b/src/DebugServer/DebugServer.csproj @@ -47,11 +47,13 @@ + + diff --git a/src/DebugServer/DebugSession.cs b/src/DebugServer/DebugSession.cs index 3a25a6323..71ade3f7f 100644 --- a/src/DebugServer/DebugSession.cs +++ b/src/DebugServer/DebugSession.cs @@ -394,7 +394,8 @@ protected override void DispatchRequest(string command, dynamic args, Response r } } catch (Exception e) { - SendErrorResponse(response, 1104, "error while processing request '{_request}' (exception: {_exception})", new { _request = command, _exception = e.Message }); + SessionLog.WriteLine(e.ToString()); + SendErrorResponse(response, 1104, "error while processing request '{_request}' (exception: {_exception})", new { _request = command, _exception = e.Message }); } if (command == "disconnect") { diff --git a/src/DebugServer/DebugeeProcess.cs b/src/DebugServer/DebugeeProcess.cs new file mode 100644 index 000000000..7b24cc3a3 --- /dev/null +++ b/src/DebugServer/DebugeeProcess.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net.Sockets; +using System.Runtime.Serialization.Formatters.Binary; +using System.Text; +using System.Threading.Tasks; + +namespace DebugServer +{ + class DebugeeOutputEventArgs : EventArgs + { + public DebugeeOutputEventArgs(string category, string content) + { + Category = category; + Content = Content; + } + + public string Category { get; } + public string Content { get; } + } + + class DebugeeProcess + { + + private Process _process; + private TcpClient _client; + + + public string RuntimeExecutable { get; set; } + public string WorkingDirectory { get; set; } + public string StartupScript { get; set; } + public string ScriptArguments { get; set; } + public string RuntimeArguments { get; set; } + + public int ExitCode => _process.ExitCode; + + public void Start() + { + _process = new Process(); + var psi = _process.StartInfo; + psi.FileName = RuntimeExecutable; + psi.UseShellExecute = false; + psi.Arguments = $"-debug {RuntimeArguments} {StartupScript} {ScriptArguments}"; + psi.WorkingDirectory = WorkingDirectory; + psi.RedirectStandardError = true; + psi.RedirectStandardOutput = true; + + _process.EnableRaisingEvents = true; + _process.OutputDataReceived += Process_OutputDataReceived; + _process.ErrorDataReceived += Process_ErrorDataReceived; + _process.Exited += Process_Exited; + + SessionLog.WriteLine($"Starting {psi.FileName} with args {psi.Arguments}"); + SessionLog.WriteLine($"cwd = {WorkingDirectory}"); + + _process.Start(); + _process.BeginOutputReadLine(); + _process.BeginErrorReadLine(); + } + + public void Connect(int port) + { + _client = new TcpClient("localhost", port); + } + + public void Send(object something) + { + var fmt = new BinaryFormatter(); + using (var s = _client.GetStream()) + { + fmt.Serialize(s, something); + } + } + + public event EventHandler OutputReceived; + public event EventHandler ProcessExited; + + + private void Process_Exited(object sender, EventArgs e) + { + ProcessExited?.Invoke(this, new EventArgs()); + } + + private void Process_ErrorDataReceived(object sender, DataReceivedEventArgs e) + { + if (e.Data == null) + { + //_stderrEOF = true; + } + SendOutput("stderr", e.Data); + } + + private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e) + { + if (e.Data == null) + { + //_stderrEOF = true; + } + SendOutput("stderr", e.Data); + } + + private void SendOutput(string category, string data) + { + OutputReceived?.Invoke(this, new DebugeeOutputEventArgs(category, data)); + } + + public void Kill() + { + if (!_process.HasExited) + { + _process.Kill(); + } + } + } +} diff --git a/src/DebugServer/OscriptDebugSession.cs b/src/DebugServer/OscriptDebugSession.cs index 674c29c37..539c479f4 100644 --- a/src/DebugServer/OscriptDebugSession.cs +++ b/src/DebugServer/OscriptDebugSession.cs @@ -3,6 +3,7 @@ using System.Diagnostics; using System.IO; using System.Linq; +using System.Net.Sockets; using System.Text; using System.Threading.Tasks; @@ -15,7 +16,7 @@ class OscriptDebugSession : DebugSession public OscriptDebugSession() : base(true, false) { } - + public override void Initialize(Response response, dynamic args) { SendResponse(response, new Capabilities() @@ -41,7 +42,7 @@ public override void Launch(Response response, dynamic args) if (!File.Exists(startupScript) && !Directory.Exists(startupScript)) { - SendErrorResponse(response, 1002, "Program '{path}' does not exist.", new { path = startupScript }); + SendErrorResponse(response, 1002, "Script '{path}' does not exist.", new { path = startupScript }); return; } @@ -73,6 +74,10 @@ public override void Launch(Response response, dynamic args) return; } } + else + { + workingDirectory = Path.GetDirectoryName(startupScript); + } // validate argument 'runtimeExecutable' var runtimeExecutable = (string)args.runtimeExecutable; @@ -84,15 +89,91 @@ public override void Launch(Response response, dynamic args) SendErrorResponse(response, 3005, "Property 'runtimeExecutable' is empty."); return; } + runtimeExecutable = ConvertClientPathToDebugger(runtimeExecutable); if (!File.Exists(runtimeExecutable)) { - SendErrorResponse(response, 3006, "Runtime executable '{path}' does not exist.", new { path = runtimeExecutable }); + SendErrorResponse(response, 3006, "Runtime executable '{path}' does not exist.", new + { + path = runtimeExecutable + }); return; } } + else + { + runtimeExecutable = "oscript.exe"; + } + + var process = new DebugeeProcess(); + process.RuntimeExecutable = runtimeExecutable; + process.RuntimeArguments = Utilities.ConcatArguments(args.runtimeArgs); + process.StartupScript = startupScript; + process.ScriptArguments = Utilities.ConcatArguments(args.args); + process.WorkingDirectory = workingDirectory; + + process.OutputReceived += (s, e) => + { + SendOutput(e.Category, e.Content); + }; + + process.ProcessExited += (s, e) => + { + SendEvent(new ExitedEvent(((DebugeeProcess)s).ExitCode)); + }; + + try + { + process.Start(); + } + catch (Exception e) + { + SendErrorResponse(response, 3012, "Can't launch debugee ({reason}).", new { reason = e.Message }); + return; + } + + var port = getInt(args, "debugPort", 2801); + try + { + process.Connect(port); + } + catch (Exception) + { + process.Kill(); + SendErrorResponse(response, 4550, "Process socket doesn't respond"); + return; + } + + SendResponse(response); + + } + + private void SendOutput(string category, string data) + { + if (!String.IsNullOrEmpty(data)) + { + if (data[data.Length - 1] != '\n') + { + data += '\n'; + } + SendEvent(new OutputEvent(category, data)); + } } + private static int getInt(dynamic container, string propertyName, int dflt = 0) + { + try + { + return (int)container[propertyName]; + } + catch (Exception) + { + // ignore and return default value + } + return dflt; + } + + public override void Attach(Response response, dynamic arguments) { throw new NotImplementedException(); diff --git a/src/DebugServer/Program.cs b/src/DebugServer/Program.cs index c82fd9782..d6f1633b4 100644 --- a/src/DebugServer/Program.cs +++ b/src/DebugServer/Program.cs @@ -2,6 +2,8 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Net; +using System.Net.Sockets; using System.Text; using System.Threading.Tasks; @@ -24,15 +26,58 @@ static void Main(string[] args) } StartSession(showTrace, Console.OpenStandardInput(), Console.OpenStandardOutput()); - } - + private static void StartSession(bool showTrace, Stream input, Stream output) { var session = new OscriptDebugSession(); session.TRACE = showTrace; session.TRACE_RESPONSE = showTrace; - session.Start(input, output).Wait(); + SessionLog.Open(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "/debug.log"); + try + { + session.Start(input, output).Wait(); + } + finally + { + SessionLog.Close(); + } + } + + +#if DEBUG + private static void RunServer(int port) + { + TcpListener serverSocket = new TcpListener(IPAddress.Parse("127.0.0.1"), port); + serverSocket.Start(); + + new System.Threading.Thread(() => { + while (true) + { + var clientSocket = serverSocket.AcceptSocket(); + if (clientSocket != null) + { + Console.Error.WriteLine(">> accepted connection from client"); + + new System.Threading.Thread(() => { + using (var networkStream = new NetworkStream(clientSocket)) + { + try + { + StartSession(true, networkStream, networkStream); + } + catch (Exception e) + { + Console.Error.WriteLine("Exception: " + e); + } + } + clientSocket.Close(); + Console.Error.WriteLine(">> client connection closed"); + }).Start(); + } + } + }).Start(); } } +#endif } diff --git a/src/DebugServer/SessionLog.cs b/src/DebugServer/SessionLog.cs new file mode 100644 index 000000000..da8a1e531 --- /dev/null +++ b/src/DebugServer/SessionLog.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DebugServer +{ + static class SessionLog + { + private static StreamWriter _log; + + [Conditional("DEBUG")] + public static void Open(string path) + { + _log = new StreamWriter(path); + _log.AutoFlush = true; + _log.WriteLine("started: " + DateTime.Now); + } + + public static void WriteLine(string text) + { +#if DEBUG + _log.WriteLine(text); +#endif + } + + [Conditional("DEBUG")] + public static void Close() + { + _log.WriteLine("closed: " + DateTime.Now); + _log.Dispose(); + } + } +} diff --git a/src/DebugServer/Utilities.cs b/src/DebugServer/Utilities.cs index 96a1a6840..b86bcdd45 100644 --- a/src/DebugServer/Utilities.cs +++ b/src/DebugServer/Utilities.cs @@ -1,5 +1,5 @@ using System; -using System.Collections.Generic; +using System.Collections; using System.Linq; using System.Reflection; using System.Text; @@ -12,6 +12,20 @@ static class Utilities { private static readonly Regex VARIABLE = new Regex(@"\{(\w+)\}"); + public static string ConcatArguments(IEnumerable args) + { + var sb = new StringBuilder(); + foreach (var stringArg in args) + { + sb.Append(' '); + sb.Append('\"'); + sb.Append(stringArg.ToString()); + sb.Append('\"'); + } + + return sb.ToString(); + } + public static string ExpandVariables(string format, dynamic variables, bool underscoredOnly = true) { if (variables == null) diff --git a/src/DebugServer/package.json b/src/DebugServer/package.json index d911de331..1e3dc90ce 100644 --- a/src/DebugServer/package.json +++ b/src/DebugServer/package.json @@ -35,7 +35,7 @@ { "type": "oscript", "label": "1Script Debugger", - "program": "./bin/DebugServer.exe", + "program": "./bin/Debug/DebugServer.exe", "osx": { "runtime": "mono" }, @@ -50,10 +50,8 @@ "program": "${workspaceRoot}/main.os", "args": [], "cwd": "${workspaceRoot}", - "preLaunchTask": "", "runtimeExecutable": null, - "env": {}, - "debugPort": null + "debugPort": 2801 } ], "configurationAttributes": { @@ -86,17 +84,21 @@ "items": { "type": "string" }, "default": [] }, - "env": { - "type": "object", - "description": "%oscript.launch.env.description%", - "default": {} - }, "debugPort": { "type": "number", "description": "%oscript.launch.debugPort.description%", "default": 2801 } } + }, + "attach": { + "properties": { + "debugPort": { + "type": "number", + "description": "%oscript.attach.debugPort.description%", + "default": 2801 + } + } } } } diff --git a/src/ScriptEngine.HostedScript/Process.cs b/src/ScriptEngine.HostedScript/Process.cs index 8bcfd64b0..2b601fcf5 100644 --- a/src/ScriptEngine.HostedScript/Process.cs +++ b/src/ScriptEngine.HostedScript/Process.cs @@ -33,7 +33,7 @@ public int Start() { try { - _engine.DebugController?.WaitForExecutionSignal(); + _engine.DebugController?.WaitForDebugEvent(DebugEvent.BeginExecution); _engine.UpdateContexts(); _engine.NewObject(_module); return 0; diff --git a/src/ScriptEngine/Machine/DebugEvent.cs b/src/ScriptEngine/Machine/DebugEvent.cs new file mode 100644 index 000000000..c71e95725 --- /dev/null +++ b/src/ScriptEngine/Machine/DebugEvent.cs @@ -0,0 +1,7 @@ +namespace ScriptEngine.Machine +{ + public enum DebugEvent + { + BeginExecution + } +} diff --git a/src/ScriptEngine/Machine/IDebugController.cs b/src/ScriptEngine/Machine/IDebugController.cs index 68eacd143..971efe7cd 100644 --- a/src/ScriptEngine/Machine/IDebugController.cs +++ b/src/ScriptEngine/Machine/IDebugController.cs @@ -7,7 +7,7 @@ namespace ScriptEngine.Machine { public interface IDebugController { - void WaitForExecutionSignal(); + void WaitForDebugEvent(DebugEvent theEvent); void NotifyProcessExit(); } diff --git a/src/ScriptEngine/ScriptEngine.csproj b/src/ScriptEngine/ScriptEngine.csproj index 43a0e426e..9ed83545e 100644 --- a/src/ScriptEngine/ScriptEngine.csproj +++ b/src/ScriptEngine/ScriptEngine.csproj @@ -135,6 +135,7 @@ + diff --git a/src/oscript/CmdLineHelper.cs b/src/oscript/CmdLineHelper.cs index 404eb1cbd..6917a5f98 100644 --- a/src/oscript/CmdLineHelper.cs +++ b/src/oscript/CmdLineHelper.cs @@ -8,7 +8,7 @@ namespace oscript class CmdLineHelper { private string[] _args; - private int _index = 0; + private int _index = -1; public CmdLineHelper(string[] args) { @@ -17,10 +17,11 @@ public CmdLineHelper(string[] args) public string Next() { + _index++; if (_index == _args.Length) return null; - return _args[_index++]; + return _args[_index]; } public string Current() @@ -33,7 +34,7 @@ public string Current() public string[] Tail() { - return _args.Skip(_index).ToArray(); + return _args.Skip(_index+1).ToArray(); } } } diff --git a/src/oscript/DebugBehavior.cs b/src/oscript/DebugBehavior.cs index 972cbec0b..632ab3143 100644 --- a/src/oscript/DebugBehavior.cs +++ b/src/oscript/DebugBehavior.cs @@ -1,77 +1,33 @@ using System; -using System.Net; -using System.Net.Sockets; using System.Threading; -using ScriptEngine.HostedScript.Library.Net; +using oscript.DebugServer; + using ScriptEngine.Machine; namespace oscript { - internal class DebugBehavior : AppBehavior, IDebugController + internal class DebugBehavior : AppBehavior { private readonly string[] _args; private readonly string _path; private readonly int _port; - - private Thread _listenerThread; - private ManualResetEventSlim _debugCommandEvent; - private DebugCommandDispatcher _dispatcher = new DebugCommandDispatcher(); - + public DebugBehavior(int port, string path, string[] args) { _args = args; _path = path; _port = port; - _debugCommandEvent = new ManualResetEventSlim(); } public override int Execute() { var executor = new ExecuteScriptBehavior(_path, _args); - executor.DebugController = this; + executor.DebugController = new OscriptDebugController(_port); return executor.Execute(); } - - public void WaitForExecutionSignal() - { - _listenerThread = new Thread(ListenerThreadProc); - _listenerThread.Start(); - _debugCommandEvent.Wait(); // процесс 1скрипт не стартует, пока не получено разрешение от дебагера - - } - - public void NotifyProcessExit() - { - _dispatcher.Post("stop"); - } - - private void ListenerThreadProc() - { - _dispatcher.Start(this, _port); - - try - { - string command; - while (_dispatcher.GetCommand(out command)) - { - switch (command) - { - case "start": - _debugCommandEvent.Set(); - break; - case "stop": - _dispatcher.Stop(); - break; - } - } - } - catch(Exception e) - { - Output.WriteLine("DBG Listener:\n" + e.ToString()); - throw; - } - } + + } } \ No newline at end of file diff --git a/src/oscript/DebugCommandDispatcher.cs b/src/oscript/DebugCommandDispatcher.cs deleted file mode 100644 index 871ad0d3d..000000000 --- a/src/oscript/DebugCommandDispatcher.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Sockets; -using System.Runtime.Serialization.Formatters.Binary; -using System.Text; -using System.Threading; - -using ScriptEngine.Machine; - -namespace oscript -{ - class DebugCommandDispatcher - { - private IDebugController _controller; - private TcpListener _socket; - private TcpClient _connection; - - private bool _isStopped = false; - - public bool GetCommand(out string command) - { - if (_isStopped || _connection == null) - { - command = null; - return false; - } - - using (var stream = _connection.GetStream()) - { - var fmt = new BinaryFormatter(); - command = (string) fmt.Deserialize(stream); - return true; - } - - } - - public void Start(IDebugController controller, int port) - { - _controller = controller; - - var endPoint = new IPEndPoint(IPAddress.Loopback, port); - _socket = new TcpListener(endPoint); - _socket.Start(1); - - _connection = _socket.AcceptTcpClient(); - - } - - public void Stop() - { - _socket.Stop(); - _connection.Close(); - _connection = null; - _isStopped = true; - } - - public void Post(string stop) - { - throw new NotImplementedException(); - } - } -} diff --git a/src/oscript/DebugServer/DebugCommandCommunicator.cs b/src/oscript/DebugServer/DebugCommandCommunicator.cs new file mode 100644 index 000000000..3102f57f9 --- /dev/null +++ b/src/oscript/DebugServer/DebugCommandCommunicator.cs @@ -0,0 +1,110 @@ +using System; +using System.Collections.Concurrent; +using System.Net; +using System.Net.Sockets; +using System.Runtime.Serialization.Formatters.Binary; +using System.Security.Cryptography; +using System.Threading; + +using ScriptEngine.Machine; + +namespace oscript.DebugServer +{ + class DebugCommandCommunicator + { + private const string QUIT_MESSAGE = "quit"; + + private IDebugController _controller; + private TcpListener _socket; + private TcpClient _connection; + + private ConcurrentQueue _q = new ConcurrentQueue(); + private AutoResetEvent _queueAddedEvent = new AutoResetEvent(false); + + private bool _isStopped; + + public bool GetCommand(out string command) + { + if (_isStopped || _connection == null) + { + command = null; + return false; + } + + if (GetCommandFromQueue(out command)) + return true; + + ThreadPool.QueueUserWorkItem(GetMessageFromNetwork); + + _queueAddedEvent.WaitOne(); + + return GetCommandFromQueue(out command); + } + + private void GetMessageFromNetwork(object state) + { + using (var stream = _connection.GetStream()) + { + var fmt = new BinaryFormatter(); + var msg = (string)fmt.Deserialize(stream); + if (msg == null) + { + // TODO: when it happens? + PostMessage(QUIT_MESSAGE); + return; + } + + PostMessage(msg); + } + } + + private void PostMessage(string message) + { + _q.Enqueue(message); + _queueAddedEvent.Set(); + } + + private bool GetCommandFromQueue(out string command) + { + if (_q.TryDequeue(out command)) + { + if (command == QUIT_MESSAGE) + return false; + + return true; + } + + return false; + } + + public void Start(IDebugController controller, int port) + { + _controller = controller; + + var endPoint = new IPEndPoint(IPAddress.Loopback, port); + _socket = new TcpListener(endPoint); + _socket.Start(1); + + _connection = _socket.AcceptTcpClient(); + + } + + public void Stop() + { + PostMessage(QUIT_MESSAGE); + _socket.Stop(); + _connection.Close(); + _connection = null; + _isStopped = true; + } + + public void Send(string command) + { + using (var stream = _connection.GetStream()) + { + var fmt = new BinaryFormatter(); + fmt.Serialize(stream, command); + } + } + } +} diff --git a/src/oscript/DebugServer/OscriptDebugController.cs b/src/oscript/DebugServer/OscriptDebugController.cs new file mode 100644 index 000000000..fc19f3737 --- /dev/null +++ b/src/oscript/DebugServer/OscriptDebugController.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; + +using ScriptEngine.Machine; + +namespace oscript.DebugServer +{ + class OscriptDebugController : IDebugController + { + private Thread _listenerThread; + private readonly ManualResetEventSlim _debugCommandEvent = new ManualResetEventSlim(); + private readonly DebugCommandCommunicator _connection = new DebugCommandCommunicator(); + + private readonly int _port; + + public OscriptDebugController(int listenerPort) + { + _port = listenerPort; + } + + public void WaitForDebugEvent(DebugEvent theEvent) + { + switch (theEvent) + { + case DebugEvent.BeginExecution: + _listenerThread = new Thread(ListenerThreadProc); + _listenerThread.Start(); + _debugCommandEvent.Wait(); // процесс 1скрипт не стартует, пока не получено разрешение от дебагера + break; + default: + throw new InvalidOperationException($"event {theEvent} cant't be waited"); + } + + } + + public void NotifyProcessExit() + { + _connection.Send("exited"); + _connection.Stop(); + } + + private void ListenerThreadProc() + { + Output.WriteLine("start listening"); + _connection.Start(this, _port); + + try + { + string command; + while (_connection.GetCommand(out command)) + { + Output.WriteLine("DBG Listener:\n" + command); + if(command == "go") + _debugCommandEvent.Set(); + } + } + catch (Exception e) + { + Output.WriteLine("DBG Listener:\n" + e.ToString()); + throw; + } + } + } +} diff --git a/src/oscript/ExecuteScriptBehavior.cs b/src/oscript/ExecuteScriptBehavior.cs index a6bea6df3..2e3bebbbe 100644 --- a/src/oscript/ExecuteScriptBehavior.cs +++ b/src/oscript/ExecuteScriptBehavior.cs @@ -33,7 +33,7 @@ public override int Execute() { if (!System.IO.File.Exists(_path)) { - Echo(String.Format("Script file is not found '{0}'", _path)); + Echo($"Script file is not found '{_path}'"); return 2; } diff --git a/src/oscript/oscript.csproj b/src/oscript/oscript.csproj index 8133fe76f..687463a3c 100644 --- a/src/oscript/oscript.csproj +++ b/src/oscript/oscript.csproj @@ -97,7 +97,8 @@ - + + @@ -133,6 +134,7 @@ + From d460e517b6ebb5e2cf1c60efe9b6afa85c90dc1c Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Mon, 27 Mar 2017 00:03:24 +0300 Subject: [PATCH 035/230] =?UTF-8?q?=D0=B2=D0=B7=D0=B0=D0=B8=D0=BC=D0=BE?= =?UTF-8?q?=D0=B4=D0=B5=D0=B9=D1=81=D1=82=D0=B2=D0=B8=D0=B5=20=D0=BC=D0=B5?= =?UTF-8?q?=D0=B6=D0=B4=D1=83=20=D0=BF=D1=80=D0=BE=D1=86=D0=B5=D1=81=D1=81?= =?UTF-8?q?=D0=B0=D0=BC=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/DebugServer/DebugeeProcess.cs | 39 ++++++++++++++++++++------ src/DebugServer/OscriptDebugSession.cs | 24 ++++++++++++++-- src/DebugServer/Utilities.cs | 3 ++ 3 files changed, 55 insertions(+), 11 deletions(-) diff --git a/src/DebugServer/DebugeeProcess.cs b/src/DebugServer/DebugeeProcess.cs index 7b24cc3a3..b08a46fdb 100644 --- a/src/DebugServer/DebugeeProcess.cs +++ b/src/DebugServer/DebugeeProcess.cs @@ -1,20 +1,23 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.IO; using System.Linq; using System.Net.Sockets; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; +using VSCodeDebug; + namespace DebugServer { class DebugeeOutputEventArgs : EventArgs { public DebugeeOutputEventArgs(string category, string content) { - Category = category; - Content = Content; + this.Category = category; + this.Content = content; } public string Category { get; } @@ -27,6 +30,9 @@ class DebugeeProcess private Process _process; private TcpClient _client; + private bool _terminated; + private bool _stdoutEOF; + private bool _stderrEOF; public string RuntimeExecutable { get; set; } public string WorkingDirectory { get; set; } @@ -80,23 +86,24 @@ public void Send(object something) private void Process_Exited(object sender, EventArgs e) { + Terminate(); ProcessExited?.Invoke(this, new EventArgs()); } - private void Process_ErrorDataReceived(object sender, DataReceivedEventArgs e) + private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e) { if (e.Data == null) { - //_stderrEOF = true; + _stdoutEOF = true; } - SendOutput("stderr", e.Data); + SendOutput("stdout", e.Data); } - private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e) + private void Process_ErrorDataReceived(object sender, DataReceivedEventArgs e) { if (e.Data == null) { - //_stderrEOF = true; + _stderrEOF = true; } SendOutput("stderr", e.Data); } @@ -106,9 +113,25 @@ private void SendOutput(string category, string data) OutputReceived?.Invoke(this, new DebugeeOutputEventArgs(category, data)); } + private void Terminate() + { + if (!_terminated) + { + + // wait until we've seen the end of stdout and stderr + for (int i = 0; i < 100 && (_stdoutEOF == false || _stderrEOF == false); i++) + { + System.Threading.Thread.Sleep(100); + } + + _terminated = true; + _process = null; + } + } + public void Kill() { - if (!_process.HasExited) + if (_process != null && !_process.HasExited) { _process.Kill(); } diff --git a/src/DebugServer/OscriptDebugSession.cs b/src/DebugServer/OscriptDebugSession.cs index 539c479f4..bce47db51 100644 --- a/src/DebugServer/OscriptDebugSession.cs +++ b/src/DebugServer/OscriptDebugSession.cs @@ -13,6 +13,8 @@ namespace DebugServer { class OscriptDebugSession : DebugSession { + private DebugeeProcess _process; + public OscriptDebugSession() : base(true, false) { } @@ -106,6 +108,8 @@ public override void Launch(Response response, dynamic args) } var process = new DebugeeProcess(); + _process = process; + process.RuntimeExecutable = runtimeExecutable; process.RuntimeArguments = Utilities.ConcatArguments(args.runtimeArgs); process.StartupScript = startupScript; @@ -114,12 +118,15 @@ public override void Launch(Response response, dynamic args) process.OutputReceived += (s, e) => { + SessionLog.WriteLine("output received: " + e.Content); SendOutput(e.Category, e.Content); }; process.ProcessExited += (s, e) => { + SessionLog.WriteLine("process exited"); SendEvent(new ExitedEvent(((DebugeeProcess)s).ExitCode)); + SendEvent(new TerminatedEvent()); }; try @@ -181,12 +188,14 @@ public override void Attach(Response response, dynamic arguments) public override void Disconnect(Response response, dynamic arguments) { - throw new NotImplementedException(); + _process.Kill(); + SendResponse(response); } public override void SetBreakpoints(Response response, dynamic arguments) { - throw new NotImplementedException(); + RequestDummy("SetBreakpoints request accepted", response, null); + _process.Send("go"); } public override void Continue(Response response, dynamic arguments) @@ -231,12 +240,21 @@ public override void Variables(Response response, dynamic arguments) public override void Threads(Response response, dynamic arguments) { - throw new NotImplementedException(); + var threads = new List(); + threads.Add(new Thread(1, "main")); + SessionLog.WriteLine("Threads request accepted"); + SendResponse(response, new ThreadsResponseBody(threads)); } public override void Evaluate(Response response, dynamic arguments) { throw new NotImplementedException(); } + + private void RequestDummy(string message, Response response, dynamic arguments) + { + SessionLog.WriteLine(message); + SendResponse(response, arguments); + } } } diff --git a/src/DebugServer/Utilities.cs b/src/DebugServer/Utilities.cs index b86bcdd45..2005fc2ce 100644 --- a/src/DebugServer/Utilities.cs +++ b/src/DebugServer/Utilities.cs @@ -14,6 +14,9 @@ static class Utilities public static string ConcatArguments(IEnumerable args) { + if (args == null) + return string.Empty; + var sb = new StringBuilder(); foreach (var stringArg in args) { From f33a44adf5d7dfae476f9f283f792cbc5d60e3a8 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Mon, 27 Mar 2017 01:31:46 +0300 Subject: [PATCH 036/230] =?UTF-8?q?=D0=B2=D0=B7=D0=B0=D0=B8=D0=BC=D0=BE?= =?UTF-8?q?=D0=B4=D0=B5=D0=B9=D1=81=D1=82=D0=B2=D0=B8=D0=B5=20=D0=BC=D0=B5?= =?UTF-8?q?=D0=B6=D0=B4=D1=83=20=D0=BF=D1=80=D0=BE=D1=86=D0=B5=D1=81=D1=81?= =?UTF-8?q?=D0=B0=D0=BC=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/DebugServer/DebugeeProcess.cs | 17 +++++++++----- .../DebugServer/DebugCommandCommunicator.cs | 22 +++++++------------ 2 files changed, 19 insertions(+), 20 deletions(-) diff --git a/src/DebugServer/DebugeeProcess.cs b/src/DebugServer/DebugeeProcess.cs index b08a46fdb..ee57f426f 100644 --- a/src/DebugServer/DebugeeProcess.cs +++ b/src/DebugServer/DebugeeProcess.cs @@ -71,13 +71,18 @@ public void Connect(int port) _client = new TcpClient("localhost", port); } - public void Send(object something) + public void Send(string something) { - var fmt = new BinaryFormatter(); - using (var s = _client.GetStream()) - { - fmt.Serialize(s, something); - } + SessionLog.WriteLine("Sending " + something); + var ms = new MemoryStream(); + var writer = new BinaryWriter(ms, Encoding.UTF8, true); + writer.Write(something); + writer.Dispose(); + + var s = _client.GetStream(); + var bytes = ms.GetBuffer(); + s.Write(bytes, 0, (int)ms.Length); + ms.Dispose(); } public event EventHandler OutputReceived; diff --git a/src/oscript/DebugServer/DebugCommandCommunicator.cs b/src/oscript/DebugServer/DebugCommandCommunicator.cs index 3102f57f9..7fa8fce0b 100644 --- a/src/oscript/DebugServer/DebugCommandCommunicator.cs +++ b/src/oscript/DebugServer/DebugCommandCommunicator.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Concurrent; +using System.IO; using System.Net; using System.Net.Sockets; using System.Runtime.Serialization.Formatters.Binary; using System.Security.Cryptography; +using System.Text; using System.Threading; using ScriptEngine.Machine; @@ -35,7 +37,7 @@ public bool GetCommand(out string command) return true; ThreadPool.QueueUserWorkItem(GetMessageFromNetwork); - + _queueAddedEvent.WaitOne(); return GetCommandFromQueue(out command); @@ -43,19 +45,11 @@ public bool GetCommand(out string command) private void GetMessageFromNetwork(object state) { - using (var stream = _connection.GetStream()) - { - var fmt = new BinaryFormatter(); - var msg = (string)fmt.Deserialize(stream); - if (msg == null) - { - // TODO: when it happens? - PostMessage(QUIT_MESSAGE); - return; - } - - PostMessage(msg); - } + var stream = _connection.GetStream(); + var reader = new BinaryReader(stream, Encoding.UTF8); + var msg = reader.ReadString(); + + PostMessage(msg); } private void PostMessage(string message) From 93436476e177fd7363126242c89bd70b242c35a3 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Thu, 30 Mar 2017 12:38:03 +0300 Subject: [PATCH 037/230] =?UTF-8?q?=D0=9A=D0=BE=D1=80=D1=80=D0=B5=D0=BA?= =?UTF-8?q?=D1=82=D0=BD=D0=BE=D0=B5=20=D0=B7=D0=B0=D0=B2=D0=B5=D1=80=D1=88?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BF=D1=80=D0=BE=D1=86=D0=B5=D1=81?= =?UTF-8?q?=D1=81=D0=B0=20oscript.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/DebugServer/DebugeeProcess.cs | 1 + src/DebugServer/OscriptDebugSession.cs | 4 ++-- src/oscript/DebugServer/DebugCommandCommunicator.cs | 1 - src/oscript/DebugServer/OscriptDebugController.cs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/DebugServer/DebugeeProcess.cs b/src/DebugServer/DebugeeProcess.cs index ee57f426f..4dd25ed00 100644 --- a/src/DebugServer/DebugeeProcess.cs +++ b/src/DebugServer/DebugeeProcess.cs @@ -40,6 +40,7 @@ class DebugeeProcess public string ScriptArguments { get; set; } public string RuntimeArguments { get; set; } + public bool HasExited => _process.HasExited; public int ExitCode => _process.ExitCode; public void Start() diff --git a/src/DebugServer/OscriptDebugSession.cs b/src/DebugServer/OscriptDebugSession.cs index bce47db51..168cd2a1e 100644 --- a/src/DebugServer/OscriptDebugSession.cs +++ b/src/DebugServer/OscriptDebugSession.cs @@ -125,7 +125,7 @@ public override void Launch(Response response, dynamic args) process.ProcessExited += (s, e) => { SessionLog.WriteLine("process exited"); - SendEvent(new ExitedEvent(((DebugeeProcess)s).ExitCode)); + //SendEvent(new ExitedEvent(((DebugeeProcess)s).ExitCode)); SendEvent(new TerminatedEvent()); }; @@ -242,7 +242,7 @@ public override void Threads(Response response, dynamic arguments) { var threads = new List(); threads.Add(new Thread(1, "main")); - SessionLog.WriteLine("Threads request accepted"); + SessionLog.WriteLine("Threads request accepted: " + _process?.HasExited); SendResponse(response, new ThreadsResponseBody(threads)); } diff --git a/src/oscript/DebugServer/DebugCommandCommunicator.cs b/src/oscript/DebugServer/DebugCommandCommunicator.cs index 7fa8fce0b..7dd4c034b 100644 --- a/src/oscript/DebugServer/DebugCommandCommunicator.cs +++ b/src/oscript/DebugServer/DebugCommandCommunicator.cs @@ -48,7 +48,6 @@ private void GetMessageFromNetwork(object state) var stream = _connection.GetStream(); var reader = new BinaryReader(stream, Encoding.UTF8); var msg = reader.ReadString(); - PostMessage(msg); } diff --git a/src/oscript/DebugServer/OscriptDebugController.cs b/src/oscript/DebugServer/OscriptDebugController.cs index fc19f3737..adce56bd2 100644 --- a/src/oscript/DebugServer/OscriptDebugController.cs +++ b/src/oscript/DebugServer/OscriptDebugController.cs @@ -38,7 +38,7 @@ public void WaitForDebugEvent(DebugEvent theEvent) public void NotifyProcessExit() { - _connection.Send("exited"); + Console.WriteLine("Sending stop to debug listener"); _connection.Stop(); } From f1b1116d732ce0892c95d09fbc4cb3a5d8d99ef2 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Thu, 30 Mar 2017 16:08:13 +0300 Subject: [PATCH 038/230] =?UTF-8?q?=D0=94=D0=BE=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D0=BA=D0=B0=20=D0=B2=20=D0=BA=D0=BE=D0=BB=D0=BB=D0=B5?= =?UTF-8?q?=D0=BA=D1=86=D0=B8=D1=8F=D1=85=20=D0=BA=D0=BE=D0=BB=D0=BE=D0=BD?= =?UTF-8?q?=D0=BE=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Library/ValueTable/ValueTableColumnCollection.cs | 5 +++++ .../Library/ValueTree/ValueTreeColumnCollection.cs | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableColumnCollection.cs b/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableColumnCollection.cs index f7b2ac14a..c5440f34c 100644 --- a/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableColumnCollection.cs +++ b/src/ScriptEngine.HostedScript/Library/ValueTable/ValueTableColumnCollection.cs @@ -127,6 +127,11 @@ public override int FindProperty(string name) return Column.ID; } + public override string GetPropName(int propNum) + { + return FindColumnByIndex(propNum).Name; + } + public override IValue GetPropValue(int propNum) { return FindColumnById(propNum); diff --git a/src/ScriptEngine.HostedScript/Library/ValueTree/ValueTreeColumnCollection.cs b/src/ScriptEngine.HostedScript/Library/ValueTree/ValueTreeColumnCollection.cs index 2622f8927..05164adfa 100644 --- a/src/ScriptEngine.HostedScript/Library/ValueTree/ValueTreeColumnCollection.cs +++ b/src/ScriptEngine.HostedScript/Library/ValueTree/ValueTreeColumnCollection.cs @@ -220,6 +220,11 @@ public override int FindProperty(string name) return column.ID; } + public override string GetPropName(int propNum) + { + return FindColumnByIndex(propNum).Name; + } + public override IValue GetPropValue(int propNum) { return FindColumnById(propNum); From 691cf850ddb0c470fad04a7da024c1d2e2a176bc Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Thu, 30 Mar 2017 16:08:30 +0300 Subject: [PATCH 039/230] =?UTF-8?q?=D0=9F=D1=80=D0=BE=D0=B4=D0=BE=D0=BB?= =?UTF-8?q?=D0=B6=D0=B5=D0=BD=D0=B8=D0=B5=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=20=D0=BF=D0=BE=20=D0=BE=D1=82=D0=BB=D0=B0=D0=B4=D1=87=D0=B8?= =?UTF-8?q?=D0=BA=D1=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/DebugServer/DebugEventListener.cs | 77 +++++++++++++++++++ src/DebugServer/DebugServer.csproj | 1 + src/DebugServer/DebugeeProcess.cs | 68 +++++++++++++--- src/DebugServer/OscriptDebugSession.cs | 65 +++++++++------- src/DebugServer/Program.cs | 10 +++ src/DebugServer/SessionLog.cs | 10 +++ .../DebugServer/DebugCommandCommunicator.cs | 1 + 7 files changed, 193 insertions(+), 39 deletions(-) create mode 100644 src/DebugServer/DebugEventListener.cs diff --git a/src/DebugServer/DebugEventListener.cs b/src/DebugServer/DebugEventListener.cs new file mode 100644 index 000000000..8f9165c91 --- /dev/null +++ b/src/DebugServer/DebugEventListener.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Net.Sockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace DebugServer +{ + internal class DebugEventListener + { + private Thread _networkThread; + private readonly Action _eventReceivedHandler; + private readonly TcpClient _client; + private readonly AutoResetEvent _readWaitEvent = new AutoResetEvent(false); + private ConcurrentQueue _q = new ConcurrentQueue(); + + private bool _listenerCancelled; + + public DebugEventListener(TcpClient client, Action handler) + { + _eventReceivedHandler = handler; + _client = client; + } + + public void Start() + { + _networkThread = new Thread(ListenerThreadBody); + _networkThread.IsBackground = true; + _networkThread.Start(); + SessionLog.WriteLine("event listener started"); + } + + public void Stop() + { + _listenerCancelled = true; + _readWaitEvent.Set(); + SessionLog.WriteLine("event listener stopped"); + } + + private void ListenerThreadBody() + { + while (!_listenerCancelled) + { + ThreadPool.QueueUserWorkItem((o) => + { + try + { + var stream = _client.GetStream(); + var reader = new BinaryReader(stream, Encoding.UTF8, true); + var msg = reader.ReadString(); + if (msg == "onStop") + { + Stop(); + return; + } + + _eventReceivedHandler("event", msg); + _readWaitEvent.Set(); + + } + catch (Exception e) + { + _eventReceivedHandler("error", e.ToString()); + Stop(); + } + }); + + _readWaitEvent.WaitOne(); + } + } + } +} diff --git a/src/DebugServer/DebugServer.csproj b/src/DebugServer/DebugServer.csproj index 69eef6f39..027951fb2 100644 --- a/src/DebugServer/DebugServer.csproj +++ b/src/DebugServer/DebugServer.csproj @@ -48,6 +48,7 @@ + diff --git a/src/DebugServer/DebugeeProcess.cs b/src/DebugServer/DebugeeProcess.cs index 4dd25ed00..a95a7a576 100644 --- a/src/DebugServer/DebugeeProcess.cs +++ b/src/DebugServer/DebugeeProcess.cs @@ -1,18 +1,12 @@ using System; -using System.Collections.Generic; using System.Diagnostics; using System.IO; -using System.Linq; using System.Net.Sockets; -using System.Runtime.Serialization.Formatters.Binary; using System.Text; -using System.Threading.Tasks; - -using VSCodeDebug; namespace DebugServer { - class DebugeeOutputEventArgs : EventArgs + internal class DebugeeOutputEventArgs : EventArgs { public DebugeeOutputEventArgs(string category, string content) { @@ -24,7 +18,13 @@ public DebugeeOutputEventArgs(string category, string content) public string Content { get; } } - class DebugeeProcess + internal class DebuggeeEventEventArgs : EventArgs + { + public string Event { get; set; } + public string Body { get; set; } + } + + internal class DebugeeProcess { private Process _process; @@ -34,6 +34,10 @@ class DebugeeProcess private bool _stdoutEOF; private bool _stderrEOF; + private DebugEventListener _listener; + + private EventHandler _dbgEventHandler; + public string RuntimeExecutable { get; set; } public string WorkingDirectory { get; set; } public string StartupScript { get; set; } @@ -43,6 +47,12 @@ class DebugeeProcess public bool HasExited => _process.HasExited; public int ExitCode => _process.ExitCode; + public DebugeeProcess() + { + // null handler + _dbgEventHandler += (s1, s2) => { }; + } + public void Start() { _process = new Process(); @@ -86,10 +96,39 @@ public void Send(string something) ms.Dispose(); } + private void OnDebugEventReceived(string category, string body) + { + SessionLog.WriteLine($"on event received {body}"); + lock (_dbgEventHandler) + { + _dbgEventHandler(this, new DebuggeeEventEventArgs() + { + Event = category, + Body = body + }); + } + } + public event EventHandler OutputReceived; public event EventHandler ProcessExited; - - + public event EventHandler DebugEventReceived + { + add + { + lock (_dbgEventHandler) + { + _dbgEventHandler += value; + } + } + remove + { + lock (_dbgEventHandler) + { + _dbgEventHandler -= value; + } + } + } + private void Process_Exited(object sender, EventArgs e) { Terminate(); @@ -132,15 +171,24 @@ private void Terminate() _terminated = true; _process = null; + _listener?.Stop(); } } public void Kill() { + _listener?.Stop(); + if (_process != null && !_process.HasExited) { _process.Kill(); } } + + public void ListenToEvents() + { + _listener = new DebugEventListener(_client, OnDebugEventReceived); + _listener.Start(); + } } } diff --git a/src/DebugServer/OscriptDebugSession.cs b/src/DebugServer/OscriptDebugSession.cs index 168cd2a1e..8f90ebd08 100644 --- a/src/DebugServer/OscriptDebugSession.cs +++ b/src/DebugServer/OscriptDebugSession.cs @@ -125,7 +125,6 @@ public override void Launch(Response response, dynamic args) process.ProcessExited += (s, e) => { SessionLog.WriteLine("process exited"); - //SendEvent(new ExitedEvent(((DebugeeProcess)s).ExitCode)); SendEvent(new TerminatedEvent()); }; @@ -144,10 +143,10 @@ public override void Launch(Response response, dynamic args) { process.Connect(port); } - catch (Exception) + catch (Exception e) { process.Kill(); - SendErrorResponse(response, 4550, "Process socket doesn't respond"); + SendErrorResponse(response, 4550, "Process socket doesn't respond: " + e.ToString()); return; } @@ -155,32 +154,6 @@ public override void Launch(Response response, dynamic args) } - private void SendOutput(string category, string data) - { - if (!String.IsNullOrEmpty(data)) - { - if (data[data.Length - 1] != '\n') - { - data += '\n'; - } - SendEvent(new OutputEvent(category, data)); - } - } - - private static int getInt(dynamic container, string propertyName, int dflt = 0) - { - try - { - return (int)container[propertyName]; - } - catch (Exception) - { - // ignore and return default value - } - return dflt; - } - - public override void Attach(Response response, dynamic arguments) { throw new NotImplementedException(); @@ -195,9 +168,16 @@ public override void Disconnect(Response response, dynamic arguments) public override void SetBreakpoints(Response response, dynamic arguments) { RequestDummy("SetBreakpoints request accepted", response, null); + _process.DebugEventReceived += ProcessOnDebugEventReceived; + _process.ListenToEvents(); _process.Send("go"); } + private void ProcessOnDebugEventReceived(object sender, DebuggeeEventEventArgs args) + { + SessionLog.WriteLine($"got event: {args.Event},\n {args.Body}"); + } + public override void Continue(Response response, dynamic arguments) { throw new NotImplementedException(); @@ -251,6 +231,33 @@ public override void Evaluate(Response response, dynamic arguments) throw new NotImplementedException(); } + + private void SendOutput(string category, string data) + { + if (!String.IsNullOrEmpty(data)) + { + if (data[data.Length - 1] != '\n') + { + data += '\n'; + } + SendEvent(new OutputEvent(category, data)); + } + } + + private static int getInt(dynamic container, string propertyName, int dflt = 0) + { + try + { + return (int)container[propertyName]; + } + catch (Exception) + { + // ignore and return default value + } + return dflt; + } + + private void RequestDummy(string message, Response response, dynamic arguments) { SessionLog.WriteLine(message); diff --git a/src/DebugServer/Program.cs b/src/DebugServer/Program.cs index d6f1633b4..b65734839 100644 --- a/src/DebugServer/Program.cs +++ b/src/DebugServer/Program.cs @@ -25,6 +25,12 @@ static void Main(string[] args) } } + AppDomain currentDomain = AppDomain.CurrentDomain; + currentDomain.UnhandledException += (s, e) => + { + SessionLog.WriteLine(e.ExceptionObject.ToString()); + }; + StartSession(showTrace, Console.OpenStandardInput(), Console.OpenStandardOutput()); } @@ -38,6 +44,10 @@ private static void StartSession(bool showTrace, Stream input, Stream output) { session.Start(input, output).Wait(); } + catch (Exception e) + { + SessionLog.WriteLine(e.ToString()); + } finally { SessionLog.Close(); diff --git a/src/DebugServer/SessionLog.cs b/src/DebugServer/SessionLog.cs index da8a1e531..2b0f923e6 100644 --- a/src/DebugServer/SessionLog.cs +++ b/src/DebugServer/SessionLog.cs @@ -12,9 +12,11 @@ static class SessionLog { private static StreamWriter _log; + private static string _path; [Conditional("DEBUG")] public static void Open(string path) { + _path = path; _log = new StreamWriter(path); _log.AutoFlush = true; _log.WriteLine("started: " + DateTime.Now); @@ -23,6 +25,13 @@ public static void Open(string path) public static void WriteLine(string text) { #if DEBUG + if (_log == null) + { + _log = new StreamWriter(_path); + _log.AutoFlush = true; + _log.WriteLine("started: " + DateTime.Now); + } + _log.WriteLine(text); #endif } @@ -32,6 +41,7 @@ public static void Close() { _log.WriteLine("closed: " + DateTime.Now); _log.Dispose(); + _log = null; } } } diff --git a/src/oscript/DebugServer/DebugCommandCommunicator.cs b/src/oscript/DebugServer/DebugCommandCommunicator.cs index 7dd4c034b..dfe6ead11 100644 --- a/src/oscript/DebugServer/DebugCommandCommunicator.cs +++ b/src/oscript/DebugServer/DebugCommandCommunicator.cs @@ -85,6 +85,7 @@ public void Start(IDebugController controller, int port) public void Stop() { PostMessage(QUIT_MESSAGE); + Send("onStop"); _socket.Stop(); _connection.Close(); _connection = null; From bbc37e12f9dbcb03c1f96481c7a77eefb85bbd41 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Thu, 30 Mar 2017 19:07:47 +0300 Subject: [PATCH 040/230] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D1=88=D0=B5?= =?UTF-8?q?=D0=BB=20=D0=BD=D0=B0=20=D0=BE=D0=B1=D1=8A=D0=B5=D0=BA=D1=82?= =?UTF-8?q?=D1=8B=20=D0=B2=20=D0=BF=D1=80=D0=BE=D1=82=D0=BE=D0=BA=D0=BE?= =?UTF-8?q?=D0=BB=D0=B5=20=D0=BE=D1=82=D0=BB=D0=B0=D0=B4=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/1Script.sln | 10 +++ src/DebugServer/App.config | 6 +- src/DebugServer/DebugEventListener.cs | 18 +++--- src/DebugServer/DebugServer.csproj | 13 +++- src/DebugServer/DebugeeProcess.cs | 25 +++----- src/DebugServer/OscriptDebugSession.cs | 6 +- src/DebugServer/Program.cs | 2 +- src/DebugServer/Protocol.cs | 4 +- src/DebugServer/packages.config | 2 +- src/OneScript.DebugProtocol/Breakpoints.cs | 16 +++++ src/OneScript.DebugProtocol/DebugEventType.cs | 13 ++++ .../EngineDebugEvent.cs | 56 +++++++++++++++++ .../IDebugController.cs | 9 +++ .../OneScript.DebugProtocol.csproj | 62 +++++++++++++++++++ .../Properties/AssemblyInfo.cs | 18 ++++++ .../HostedScriptEngine.cs | 2 + src/ScriptEngine.HostedScript/Process.cs | 4 +- .../ScriptEngine.HostedScript.csproj | 4 ++ src/ScriptEngine/Machine/DebugEvent.cs | 7 --- src/ScriptEngine/Machine/IDebugController.cs | 14 ----- src/ScriptEngine/ScriptEngine.csproj | 23 +++---- src/ScriptEngine/ScriptingEngine.cs | 2 + .../DebugServer/DebugCommandCommunicator.cs | 28 ++++----- .../DebugServer/OscriptDebugController.cs | 10 +-- src/oscript/ExecuteScriptBehavior.cs | 3 + src/oscript/oscript.csproj | 4 ++ 26 files changed, 272 insertions(+), 89 deletions(-) create mode 100644 src/OneScript.DebugProtocol/Breakpoints.cs create mode 100644 src/OneScript.DebugProtocol/DebugEventType.cs create mode 100644 src/OneScript.DebugProtocol/EngineDebugEvent.cs create mode 100644 src/OneScript.DebugProtocol/IDebugController.cs create mode 100644 src/OneScript.DebugProtocol/OneScript.DebugProtocol.csproj create mode 100644 src/OneScript.DebugProtocol/Properties/AssemblyInfo.cs delete mode 100644 src/ScriptEngine/Machine/DebugEvent.cs delete mode 100644 src/ScriptEngine/Machine/IDebugController.cs diff --git a/src/1Script.sln b/src/1Script.sln index 64d2fe515..ba5cc79d6 100644 --- a/src/1Script.sln +++ b/src/1Script.sln @@ -28,6 +28,8 @@ Project("{930C7802-8A8C-48F9-8165-68863BCCD9DD}") = "Installer", "Installer\Inst EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DebugServer", "DebugServer\DebugServer.csproj", "{C979F151-AA29-47E4-B020-3039BA0986D9}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OneScript.DebugProtocol", "OneScript.DebugProtocol\OneScript.DebugProtocol.csproj", "{727A498F-BF50-42F8-8523-40C0B5B1B233}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -87,6 +89,14 @@ Global {C979F151-AA29-47E4-B020-3039BA0986D9}.Release|Any CPU.ActiveCfg = Release|Any CPU {C979F151-AA29-47E4-B020-3039BA0986D9}.Release|Any CPU.Build.0 = Release|Any CPU {C979F151-AA29-47E4-B020-3039BA0986D9}.Release|x86.ActiveCfg = Release|Any CPU + {727A498F-BF50-42F8-8523-40C0B5B1B233}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {727A498F-BF50-42F8-8523-40C0B5B1B233}.Debug|Any CPU.Build.0 = Debug|Any CPU + {727A498F-BF50-42F8-8523-40C0B5B1B233}.Debug|x86.ActiveCfg = Debug|Any CPU + {727A498F-BF50-42F8-8523-40C0B5B1B233}.Debug|x86.Build.0 = Debug|Any CPU + {727A498F-BF50-42F8-8523-40C0B5B1B233}.Release|Any CPU.ActiveCfg = Release|Any CPU + {727A498F-BF50-42F8-8523-40C0B5B1B233}.Release|Any CPU.Build.0 = Release|Any CPU + {727A498F-BF50-42F8-8523-40C0B5B1B233}.Release|x86.ActiveCfg = Release|Any CPU + {727A498F-BF50-42F8-8523-40C0B5B1B233}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/src/DebugServer/App.config b/src/DebugServer/App.config index 88fa4027b..74ade9db5 100644 --- a/src/DebugServer/App.config +++ b/src/DebugServer/App.config @@ -1,6 +1,6 @@ - + - + - \ No newline at end of file + diff --git a/src/DebugServer/DebugEventListener.cs b/src/DebugServer/DebugEventListener.cs index 8f9165c91..31b858f54 100644 --- a/src/DebugServer/DebugEventListener.cs +++ b/src/DebugServer/DebugEventListener.cs @@ -9,19 +9,21 @@ using System.Threading; using System.Threading.Tasks; +using OneScript.DebugProtocol; + namespace DebugServer { internal class DebugEventListener { private Thread _networkThread; - private readonly Action _eventReceivedHandler; + private readonly Action _eventReceivedHandler; private readonly TcpClient _client; private readonly AutoResetEvent _readWaitEvent = new AutoResetEvent(false); private ConcurrentQueue _q = new ConcurrentQueue(); private bool _listenerCancelled; - public DebugEventListener(TcpClient client, Action handler) + public DebugEventListener(TcpClient client, Action handler) { _eventReceivedHandler = handler; _client = client; @@ -51,21 +53,21 @@ private void ListenerThreadBody() try { var stream = _client.GetStream(); - var reader = new BinaryReader(stream, Encoding.UTF8, true); - var msg = reader.ReadString(); - if (msg == "onStop") + var msg = EngineDebugEvent.Deserialize(stream); + + if (msg.EventType == DebugEventType.ProcessExited) { Stop(); return; } - _eventReceivedHandler("event", msg); + _eventReceivedHandler(msg); _readWaitEvent.Set(); } - catch (Exception e) + catch { - _eventReceivedHandler("error", e.ToString()); + // ошибки возникают только при обрыве соединения Stop(); } }); diff --git a/src/DebugServer/DebugServer.csproj b/src/DebugServer/DebugServer.csproj index 027951fb2..fcf6c7dd3 100644 --- a/src/DebugServer/DebugServer.csproj +++ b/src/DebugServer/DebugServer.csproj @@ -9,9 +9,10 @@ Properties DebugServer DebugServer - v4.5.2 + v4.0 512 true + AnyCPU @@ -33,8 +34,8 @@ 4 - - ..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll + + ..\packages\Newtonsoft.Json.10.0.1\lib\net40\Newtonsoft.Json.dll True @@ -62,6 +63,12 @@ + + + {727A498F-BF50-42F8-8523-40C0B5B1B233} + OneScript.DebugProtocol + + + \ No newline at end of file diff --git a/src/OneScript.DebugProtocol/Properties/AssemblyInfo.cs b/src/OneScript.DebugProtocol/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..514690555 --- /dev/null +++ b/src/OneScript.DebugProtocol/Properties/AssemblyInfo.cs @@ -0,0 +1,18 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OneScript.DebugProtocol")] +[assembly: AssemblyProduct("OneScript.DebugProtocol")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("727a498f-bf50-42f8-8523-40c0b5b1b233")] + diff --git a/src/ScriptEngine.HostedScript/HostedScriptEngine.cs b/src/ScriptEngine.HostedScript/HostedScriptEngine.cs index 888e21080..691cd64f7 100644 --- a/src/ScriptEngine.HostedScript/HostedScriptEngine.cs +++ b/src/ScriptEngine.HostedScript/HostedScriptEngine.cs @@ -12,6 +12,8 @@ This Source Code Form is subject to the terms of the using System.Collections.Generic; using System.Linq; +using OneScript.DebugProtocol; + namespace ScriptEngine.HostedScript { public class HostedScriptEngine diff --git a/src/ScriptEngine.HostedScript/Process.cs b/src/ScriptEngine.HostedScript/Process.cs index 2b601fcf5..7f1d8cb42 100644 --- a/src/ScriptEngine.HostedScript/Process.cs +++ b/src/ScriptEngine.HostedScript/Process.cs @@ -10,7 +10,7 @@ This Source Code Form is subject to the terms of the using System.Text; using ScriptEngine.Environment; using ScriptEngine.Machine; -using ScriptEngine.Machine.Contexts; +using OneScript.DebugProtocol; namespace ScriptEngine.HostedScript { @@ -33,7 +33,7 @@ public int Start() { try { - _engine.DebugController?.WaitForDebugEvent(DebugEvent.BeginExecution); + _engine.DebugController?.WaitForDebugEvent(DebugEventType.BeginExecution); _engine.UpdateContexts(); _engine.NewObject(_module); return 0; diff --git a/src/ScriptEngine.HostedScript/ScriptEngine.HostedScript.csproj b/src/ScriptEngine.HostedScript/ScriptEngine.HostedScript.csproj index 2485e4c26..91840557d 100644 --- a/src/ScriptEngine.HostedScript/ScriptEngine.HostedScript.csproj +++ b/src/ScriptEngine.HostedScript/ScriptEngine.HostedScript.csproj @@ -213,6 +213,10 @@ + + {727a498f-bf50-42f8-8523-40c0b5b1b233} + OneScript.DebugProtocol + {F062D1D9-D307-492A-A56B-FF3C55F8F6C0} ScriptEngine diff --git a/src/ScriptEngine/Machine/DebugEvent.cs b/src/ScriptEngine/Machine/DebugEvent.cs deleted file mode 100644 index c71e95725..000000000 --- a/src/ScriptEngine/Machine/DebugEvent.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ScriptEngine.Machine -{ - public enum DebugEvent - { - BeginExecution - } -} diff --git a/src/ScriptEngine/Machine/IDebugController.cs b/src/ScriptEngine/Machine/IDebugController.cs deleted file mode 100644 index 971efe7cd..000000000 --- a/src/ScriptEngine/Machine/IDebugController.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace ScriptEngine.Machine -{ - public interface IDebugController - { - void WaitForDebugEvent(DebugEvent theEvent); - - void NotifyProcessExit(); - } -} diff --git a/src/ScriptEngine/ScriptEngine.csproj b/src/ScriptEngine/ScriptEngine.csproj index 9ed83545e..1dfa0c425 100644 --- a/src/ScriptEngine/ScriptEngine.csproj +++ b/src/ScriptEngine/ScriptEngine.csproj @@ -81,9 +81,7 @@ - - ..\packages\Newtonsoft.Json.9.0.1\lib\net40\Newtonsoft.Json.dll @@ -135,12 +133,10 @@ - - @@ -197,7 +193,12 @@ - + + + {727a498f-bf50-42f8-8523-40c0b5b1b233} + OneScript.DebugProtocol + + @@ -210,11 +211,11 @@ xcopy "$(TargetDir)ScriptEngine.dll" "$(SolutionDir)StandaloneRunner\" /Y /E /D cp -f "$(TargetDir)ScriptEngine.dll" "$(SolutionDir)StandaloneRunner/" - \ No newline at end of file diff --git a/src/ScriptEngine/ScriptingEngine.cs b/src/ScriptEngine/ScriptingEngine.cs index b7c395f5f..5ce15fe39 100644 --- a/src/ScriptEngine/ScriptingEngine.cs +++ b/src/ScriptEngine/ScriptingEngine.cs @@ -7,6 +7,8 @@ This Source Code Form is subject to the terms of the using System; using System.Linq; +using OneScript.DebugProtocol; + using ScriptEngine.Compiler; using ScriptEngine.Environment; using ScriptEngine.Machine; diff --git a/src/oscript/DebugServer/DebugCommandCommunicator.cs b/src/oscript/DebugServer/DebugCommandCommunicator.cs index dfe6ead11..5438d5ee8 100644 --- a/src/oscript/DebugServer/DebugCommandCommunicator.cs +++ b/src/oscript/DebugServer/DebugCommandCommunicator.cs @@ -8,24 +8,27 @@ using System.Text; using System.Threading; +using OneScript.DebugProtocol; + using ScriptEngine.Machine; namespace oscript.DebugServer { class DebugCommandCommunicator { - private const string QUIT_MESSAGE = "quit"; + private class QuitEvent : EngineDebugEvent { } + private readonly QuitEvent QUIT_MESSAGE = new QuitEvent(); private IDebugController _controller; private TcpListener _socket; private TcpClient _connection; - private ConcurrentQueue _q = new ConcurrentQueue(); + private ConcurrentQueue _q = new ConcurrentQueue(); private AutoResetEvent _queueAddedEvent = new AutoResetEvent(false); private bool _isStopped; - public bool GetCommand(out string command) + public bool GetCommand(out EngineDebugEvent command) { if (_isStopped || _connection == null) { @@ -46,22 +49,21 @@ public bool GetCommand(out string command) private void GetMessageFromNetwork(object state) { var stream = _connection.GetStream(); - var reader = new BinaryReader(stream, Encoding.UTF8); - var msg = reader.ReadString(); + var msg = EngineDebugEvent.Deserialize(stream); PostMessage(msg); } - private void PostMessage(string message) + private void PostMessage(EngineDebugEvent message) { _q.Enqueue(message); _queueAddedEvent.Set(); } - private bool GetCommandFromQueue(out string command) + private bool GetCommandFromQueue(out EngineDebugEvent command) { if (_q.TryDequeue(out command)) { - if (command == QUIT_MESSAGE) + if (command is QuitEvent) return false; return true; @@ -85,20 +87,16 @@ public void Start(IDebugController controller, int port) public void Stop() { PostMessage(QUIT_MESSAGE); - Send("onStop"); + Send(new EngineDebugEvent(DebugEventType.ProcessExited)); _socket.Stop(); _connection.Close(); _connection = null; _isStopped = true; } - public void Send(string command) + public void Send(EngineDebugEvent dbgEvent) { - using (var stream = _connection.GetStream()) - { - var fmt = new BinaryFormatter(); - fmt.Serialize(stream, command); - } + EngineDebugEvent.Serialize(_connection.GetStream(), dbgEvent); } } } diff --git a/src/oscript/DebugServer/OscriptDebugController.cs b/src/oscript/DebugServer/OscriptDebugController.cs index adce56bd2..72ba7075e 100644 --- a/src/oscript/DebugServer/OscriptDebugController.cs +++ b/src/oscript/DebugServer/OscriptDebugController.cs @@ -4,6 +4,8 @@ using System.Text; using System.Threading; +using OneScript.DebugProtocol; + using ScriptEngine.Machine; namespace oscript.DebugServer @@ -21,11 +23,11 @@ public OscriptDebugController(int listenerPort) _port = listenerPort; } - public void WaitForDebugEvent(DebugEvent theEvent) + public void WaitForDebugEvent(DebugEventType theEvent) { switch (theEvent) { - case DebugEvent.BeginExecution: + case DebugEventType.BeginExecution: _listenerThread = new Thread(ListenerThreadProc); _listenerThread.Start(); _debugCommandEvent.Wait(); // процесс 1скрипт не стартует, пока не получено разрешение от дебагера @@ -49,11 +51,11 @@ private void ListenerThreadProc() try { - string command; + EngineDebugEvent command; while (_connection.GetCommand(out command)) { Output.WriteLine("DBG Listener:\n" + command); - if(command == "go") + if(command.EventType == DebugEventType.BeginExecution) _debugCommandEvent.Set(); } } diff --git a/src/oscript/ExecuteScriptBehavior.cs b/src/oscript/ExecuteScriptBehavior.cs index 2e3bebbbe..ae8c4e420 100644 --- a/src/oscript/ExecuteScriptBehavior.cs +++ b/src/oscript/ExecuteScriptBehavior.cs @@ -8,6 +8,9 @@ This Source Code Form is subject to the terms of the using System.Collections.Generic; using System.Linq; using System.Text; + +using OneScript.DebugProtocol; + using ScriptEngine; using ScriptEngine.Compiler; using ScriptEngine.HostedScript; diff --git a/src/oscript/oscript.csproj b/src/oscript/oscript.csproj index 687463a3c..dedeccfbf 100644 --- a/src/oscript/oscript.csproj +++ b/src/oscript/oscript.csproj @@ -122,6 +122,10 @@ + + {727a498f-bf50-42f8-8523-40c0b5b1b233} + OneScript.DebugProtocol + {F09A46BD-5737-45E7-BA60-A47C9F7821A9} ScriptEngine.HostedScript From a5917fcc7379385067c37f6d7269ea41fcf113f7 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Thu, 30 Mar 2017 22:04:18 +0300 Subject: [PATCH 041/230] =?UTF-8?q?=D0=A0=D0=B0=D0=B7=D0=B2=D0=B8=D1=82?= =?UTF-8?q?=D0=B8=D0=B5=20=D0=BF=D1=80=D0=BE=D1=82=D0=BE=D0=BA=D0=BE=D0=BB?= =?UTF-8?q?=D0=B0=20=D0=B2=D0=B7=D0=B0=D0=B8=D0=BC=D0=BE=D0=B4=D0=B5=D0=B9?= =?UTF-8?q?=D1=81=D1=82=D0=B2=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/DebugServer/OscriptDebugSession.cs | 16 ++++- src/OneScript.DebugProtocol/Breakpoints.cs | 4 -- src/OneScript.DebugProtocol/DebugEventType.cs | 3 - .../EngineDebugEvent.cs | 72 ++++++++++++------- .../IDebugController.cs | 2 + .../OneScript.DebugProtocol.csproj | 7 ++ src/OneScript.DebugProtocol/packages.config | 4 ++ .../DebugServer/DebugCommandCommunicator.cs | 12 ++-- .../DebugServer/OscriptDebugController.cs | 25 +++++-- 9 files changed, 103 insertions(+), 42 deletions(-) create mode 100644 src/OneScript.DebugProtocol/packages.config diff --git a/src/DebugServer/OscriptDebugSession.cs b/src/DebugServer/OscriptDebugSession.cs index 77c4a129c..3821de1f1 100644 --- a/src/DebugServer/OscriptDebugSession.cs +++ b/src/DebugServer/OscriptDebugSession.cs @@ -7,10 +7,14 @@ using System.Text; using System.Threading.Tasks; +using Newtonsoft.Json; + using OneScript.DebugProtocol; using VSCodeDebug; +using Breakpoint = OneScript.DebugProtocol.Breakpoint; + namespace DebugServer { class OscriptDebugSession : DebugSession @@ -169,7 +173,17 @@ public override void Disconnect(Response response, dynamic arguments) public override void SetBreakpoints(Response response, dynamic arguments) { - RequestDummy("SetBreakpoints request accepted", response, null); + var path = (string) arguments.source.path; + path = ConvertClientPathToDebugger(path); + + foreach (var srcBreakpoint in arguments.breakpoints) + { + var bpt = new Breakpoint(); + bpt.Line = (int) srcBreakpoint.line; + bpt.Source = path; + } + + //RequestDummy("SetBreakpoints request accepted", response, null); _process.DebugEventReceived += ProcessOnDebugEventReceived; _process.ListenToEvents(); _process.Send(new EngineDebugEvent(DebugEventType.BeginExecution)); diff --git a/src/OneScript.DebugProtocol/Breakpoints.cs b/src/OneScript.DebugProtocol/Breakpoints.cs index 1c810742f..3a7a8538b 100644 --- a/src/OneScript.DebugProtocol/Breakpoints.cs +++ b/src/OneScript.DebugProtocol/Breakpoints.cs @@ -2,14 +2,10 @@ namespace OneScript.DebugProtocol { - [DataContract] public class Breakpoint { - [DataMember] public int Id { get; set; } - [DataMember] public string Source { get; set; } - [DataMember] public int Line { get; set; } } diff --git a/src/OneScript.DebugProtocol/DebugEventType.cs b/src/OneScript.DebugProtocol/DebugEventType.cs index 1db398453..ef99e290a 100644 --- a/src/OneScript.DebugProtocol/DebugEventType.cs +++ b/src/OneScript.DebugProtocol/DebugEventType.cs @@ -2,12 +2,9 @@ namespace OneScript.DebugProtocol { - [DataContract] public enum DebugEventType { - [EnumMember] BeginExecution, - [EnumMember] ProcessExited } } diff --git a/src/OneScript.DebugProtocol/EngineDebugEvent.cs b/src/OneScript.DebugProtocol/EngineDebugEvent.cs index 212598607..962cecc84 100644 --- a/src/OneScript.DebugProtocol/EngineDebugEvent.cs +++ b/src/OneScript.DebugProtocol/EngineDebugEvent.cs @@ -4,22 +4,44 @@ using System.Runtime.Serialization; using System.Text; +using Newtonsoft.Json; +using System.Collections.Generic; + namespace OneScript.DebugProtocol { - [DataContract] - public class EngineDebugEvent + public enum MessageType { - [DataMember] - public DebugEventType EventType; + Command, + Event + } - public EngineDebugEvent() + public abstract class DebugProtocolMessage + { + public MessageType Type { get; protected set; } + public string TypeName { get; protected set; } + + protected DebugProtocolMessage() { - + TypeName = this.GetType().Name; } - public EngineDebugEvent(DebugEventType type) + public static void Serialize(Stream destination, DebugProtocolMessage value) { - EventType = type; + var settings = new JsonSerializerSettings(); + settings.TypeNameHandling = TypeNameHandling.Auto; + var jsonString = JsonConvert.SerializeObject(value, settings); + var writer = new BinaryWriter(destination, Encoding.UTF8); + writer.Write(jsonString); + } + + public static T Deserialize(Stream source) where T : DebugProtocolMessage + { + var reader = new BinaryReader(source, Encoding.UTF8); + var settings = new JsonSerializerSettings(); + settings.TypeNameHandling = TypeNameHandling.Auto; + var obj = JsonConvert.DeserializeObject(reader.ReadString(), settings); + + return obj; } public string ToSerializedString() @@ -28,29 +50,31 @@ public string ToSerializedString() Serialize(ms, this); return Encoding.UTF8.GetString(ms.ToArray()); } + } - public static void Serialize(Stream destination, EngineDebugEvent value) - { - var ser = new DataContractSerializer(value.GetType()); - var ms = new MemoryStream(); - ser.WriteObject(ms, value); + public class EngineDebugEvent : DebugProtocolMessage + { + public DebugEventType EventType; - var writer = new BinaryWriter(destination, Encoding.UTF8); - writer.Write(Encoding.UTF8.GetString(ms.ToArray())); + public EngineDebugEvent() + { + Type = MessageType.Event; } - public static T Deserialize(Stream source) where T : EngineDebugEvent + public EngineDebugEvent(DebugEventType type) : this() { - var ser = new DataContractSerializer(typeof(T)); - var reader = new BinaryReader(source, Encoding.UTF8); - var data = reader.ReadString(); - var ms = new MemoryStream(); - var bytes = Encoding.UTF8.GetBytes(data); - ms.Write(bytes, 0, bytes.Length); - ms.Position = 0; - return (T)ser.ReadObject(ms); + EventType = type; } } + public class SetSourceBreakpointsCommand : DebugProtocolMessage + { + public SetSourceBreakpointsCommand() + { + Type = MessageType.Command; + } + + public Breakpoint[] Breakpoints; + } } diff --git a/src/OneScript.DebugProtocol/IDebugController.cs b/src/OneScript.DebugProtocol/IDebugController.cs index 2fa2f3459..ee86025e2 100644 --- a/src/OneScript.DebugProtocol/IDebugController.cs +++ b/src/OneScript.DebugProtocol/IDebugController.cs @@ -5,5 +5,7 @@ public interface IDebugController void WaitForDebugEvent(DebugEventType theEvent); void NotifyProcessExit(); + + int SetBreakpoint(string sourceLocation, int line); } } diff --git a/src/OneScript.DebugProtocol/OneScript.DebugProtocol.csproj b/src/OneScript.DebugProtocol/OneScript.DebugProtocol.csproj index ad92e8fca..539bfbc60 100644 --- a/src/OneScript.DebugProtocol/OneScript.DebugProtocol.csproj +++ b/src/OneScript.DebugProtocol/OneScript.DebugProtocol.csproj @@ -31,6 +31,10 @@ 4 + + ..\packages\Newtonsoft.Json.9.0.1\lib\net40\Newtonsoft.Json.dll + True + @@ -51,6 +55,9 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 27ac0a3601d335a7998681a245f0a862bf6f9df7 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Mon, 22 May 2017 21:26:04 +0300 Subject: [PATCH 065/230] =?UTF-8?q?=D0=9D=D0=B0=D0=B1=D1=80=D0=BE=D1=81?= =?UTF-8?q?=D0=BA=D0=B8=20=D0=BF=D0=BE=20=D1=88=D0=B0=D0=B3=D0=B0=D0=BD?= =?UTF-8?q?=D0=B8=D1=8E=20=D0=B2=20=D0=BE=D1=82=D0=BB=D0=B0=D0=B4=D1=87?= =?UTF-8?q?=D0=B8=D0=BA=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/DebugServer/DebugeeProcess.cs | 5 + src/DebugServer/OscriptDebugSession.cs | 10 +- .../IDebuggerService.cs | 15 +++ src/ScriptEngine/Machine/MachineInstance.cs | 117 ++++++++++-------- .../Machine/MachineStopManager.cs | 20 ++- src/ScriptEngine/ScriptingEngine.cs | 2 +- .../DebugServer/OscriptDebugController.cs | 16 +++ 7 files changed, 128 insertions(+), 57 deletions(-) diff --git a/src/DebugServer/DebugeeProcess.cs b/src/DebugServer/DebugeeProcess.cs index f32b06ed4..0b2efaaef 100644 --- a/src/DebugServer/DebugeeProcess.cs +++ b/src/DebugServer/DebugeeProcess.cs @@ -183,5 +183,10 @@ public Variable Evaluate(StackFrame frame, string expression) throw new Exception(e.Message); } } + + public void Next() + { + _debugger.Instance.Next(); + } } } diff --git a/src/DebugServer/OscriptDebugSession.cs b/src/DebugServer/OscriptDebugSession.cs index 075fde6b8..66a42067e 100644 --- a/src/DebugServer/OscriptDebugSession.cs +++ b/src/DebugServer/OscriptDebugSession.cs @@ -237,7 +237,15 @@ public override void Continue(Response response, dynamic arguments) public override void Next(Response response, dynamic arguments) { - throw new NotImplementedException(); + SendResponse(response); + lock (_process) + { + if (!_process.HasExited) + { + _process.Next(); + } + } + } public override void StepIn(Response response, dynamic arguments) diff --git a/src/OneScript.DebugProtocol/IDebuggerService.cs b/src/OneScript.DebugProtocol/IDebuggerService.cs index 8a63739da..77998dc3e 100644 --- a/src/OneScript.DebugProtocol/IDebuggerService.cs +++ b/src/OneScript.DebugProtocol/IDebuggerService.cs @@ -42,8 +42,23 @@ public interface IDebuggerService [OperationContract] Variable[] GetVariables(int frameIndex, int[] path); + /// + /// Вычисление выражения на остановленном процессе + /// + /// Кадр стека, относительно которого вычисляем + /// Выражение + /// Переменная с результатом [OperationContract] Variable Evaluate(int contextFrame, string expression); + + [OperationContract] + void Next(); + + [OperationContract] + void StepIn(); + + [OperationContract] + void StepOut(); } public interface IDebugEventListener diff --git a/src/ScriptEngine/Machine/MachineInstance.cs b/src/ScriptEngine/Machine/MachineInstance.cs index 05268a816..d743808f8 100644 --- a/src/ScriptEngine/Machine/MachineInstance.cs +++ b/src/ScriptEngine/Machine/MachineInstance.cs @@ -129,7 +129,6 @@ public void SetDebugMode(IDebugController debugContr) public bool SetBreakpoint(string source, int line, out int id) { - Console.WriteLine($"set break: {source}:{line}"); if (_stopManager == null) throw new InvalidOperationException("Machine is not in debug mode"); @@ -139,6 +138,67 @@ public bool SetBreakpoint(string source, int line, out int id) return true; } + public void StopAtNextLine() + { + if (_stopManager == null) + throw new InvalidOperationException("Machine is not in debug mode"); + + _stopManager.AddNextLineStop(_currentFrame); + } + + + public IValue Evaluate(string expression, bool separate = false) + { + var code = CompileExpressionModule(expression); + + MachineInstance runner; + if (separate) + { + runner = new MachineInstance(); + runner._scopes = new List(_scopes); + } + else + runner = this; + + var frame = new ExecutionFrame(); + frame.MethodName = code.ModuleInfo.ModuleName; + frame.Locals = new IVariable[0]; + frame.InstructionPointer = 0; + var curModule = _module; + + var mlocals = new Scope(); + mlocals.Instance = new UserScriptContextInstance(code); + mlocals.Detachable = true; + mlocals.Methods = TopScope.Methods; + mlocals.Variables = _currentFrame.Locals; + runner._scopes.Add(mlocals); + + try + { + if (!separate) + PushFrame(); + + runner.SetFrame(frame); + runner.SetModule(code); + runner.MainCommandLoop(); + } + finally + { + if (!separate) + { + DetachTopScope(out mlocals); + PopFrame(); + SetModule(curModule); + } + } + + var result = runner._operationStack.Pop(); + + return result; + + } + + #endregion internal ScriptInformationContext CurrentScript @@ -906,7 +966,7 @@ private bool MethodCallImpl(int arg, bool asFunc) else { // при вызове библиотечного метода (из другого scope) - // статус вызова текущего frame не должен изменяться. + // статус вызова текущего frames не должен изменяться. // needsDiscarding = _currentFrame.DiscardReturnValue; CallContext(scope.Instance, methodRef.CodeIndex, ref methInfo, argValues, asFunc); @@ -2342,57 +2402,6 @@ private void ModuleInfo(int arg) #endregion - public IValue Evaluate(string expression, bool separate = false) - { - var code = CompileExpressionModule(expression); - - MachineInstance runner; - if (separate) - { - runner = new MachineInstance(); - runner._scopes = new List(_scopes); - } - else - runner = this; - - var frame = new ExecutionFrame(); - frame.MethodName = code.ModuleInfo.ModuleName; - frame.Locals = new IVariable[0]; - frame.InstructionPointer = 0; - var curModule = _module; - - var mlocals = new Scope(); - mlocals.Instance = new UserScriptContextInstance(code); - mlocals.Detachable = true; - mlocals.Methods = TopScope.Methods; - mlocals.Variables = _currentFrame.Locals; - runner._scopes.Add(mlocals); - - try - { - if(!separate) - PushFrame(); - - runner.SetFrame(frame); - runner.SetModule(code); - runner.MainCommandLoop(); - } - finally - { - if (!separate) - { - DetachTopScope(out mlocals); - PopFrame(); - SetModule(curModule); - } - } - - var result = runner._operationStack.Pop(); - - return result; - - } - private LoadedModule CompileExpressionModule(string expression) { var ctx = ExtractCompilerContext(); @@ -2473,5 +2482,7 @@ private ExecutionFrameInfo FrameInfo(LoadedModule module, ExecutionFrame frame) FrameObject = frame }; } + + } } diff --git a/src/ScriptEngine/Machine/MachineStopManager.cs b/src/ScriptEngine/Machine/MachineStopManager.cs index 4a2e14b43..b65a374bf 100644 --- a/src/ScriptEngine/Machine/MachineStopManager.cs +++ b/src/ScriptEngine/Machine/MachineStopManager.cs @@ -10,7 +10,8 @@ enum StopKind { SourceLine, MethodEntry, - MethodReturn + MethodReturn, + NextLine } struct StopHandle @@ -18,7 +19,7 @@ struct StopHandle public StopKind kind; public string source; public int line; - public ExecutionFrame frame; + public ExecutionFrame[] frames; } class MachineStopManager @@ -35,6 +36,15 @@ internal void AddSourceLineStop(string source, int line) }); } + internal void AddNextLineStop(ExecutionFrame currentFrame) + { + _registeredStops.Add(new StopHandle() + { + kind = StopKind.NextLine, + frames = new []{ currentFrame } + }); + } + internal bool ShouldStopHere(string module, ExecutionFrame frame) { for (int i = _registeredStops.Count-1; i >=0; i--) @@ -44,6 +54,12 @@ internal bool ShouldStopHere(string module, ExecutionFrame frame) { return true; } + + if (stop.kind == StopKind.NextLine && stop.frames.Contains(frame)) + { + _registeredStops.RemoveAt(i); + return true; + } } return false; diff --git a/src/ScriptEngine/ScriptingEngine.cs b/src/ScriptEngine/ScriptingEngine.cs index 9676404f9..32aaa583d 100644 --- a/src/ScriptEngine/ScriptingEngine.cs +++ b/src/ScriptEngine/ScriptingEngine.cs @@ -157,7 +157,7 @@ public IDebugController DebugController set { _debugController = value; - ProduceExtraCode |= CodeGenerationFlags.DebugCode; + ProduceExtraCode = CodeGenerationFlags.DebugCode | CodeGenerationFlags.CodeStatistics; _machine.SetDebugMode(_debugController); } } diff --git a/src/oscript/DebugServer/OscriptDebugController.cs b/src/oscript/DebugServer/OscriptDebugController.cs index 306380cc2..2bef1e922 100644 --- a/src/oscript/DebugServer/OscriptDebugController.cs +++ b/src/oscript/DebugServer/OscriptDebugController.cs @@ -183,6 +183,22 @@ public Variable Evaluate(int contextFrame, string expression) } } + public void Next() + { + _machine.StopAtNextLine(); + _debugCommandEvent.Set(); + } + + public void StepIn() + { + throw new NotImplementedException(); + } + + public void StepOut() + { + throw new NotImplementedException(); + } + private static bool HasProperties(IValue variable) { if (variable.DataType == DataType.Object) From f0fd4acd8f4b5bc08fa34301af1c6179e624a86a Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Tue, 23 May 2017 15:02:17 +0300 Subject: [PATCH 066/230] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B0=20=D0=BF=D0=B5=D1=80=D0=B5=D0=B4=D0=B0?= =?UTF-8?q?=D1=87=D0=B0=20=D0=BF=D1=80=D0=BE=D0=BF=D1=83=D1=89=D0=B5=D0=BD?= =?UTF-8?q?=D0=BD=D1=8B=D1=85=20=D0=B0=D1=80=D0=B3=D1=83=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D1=82=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine/Compiler/Compiler.cs | 118 +++++++++++++++----------- 1 file changed, 67 insertions(+), 51 deletions(-) diff --git a/src/ScriptEngine/Compiler/Compiler.cs b/src/ScriptEngine/Compiler/Compiler.cs index a34e4aee8..792275f33 100644 --- a/src/ScriptEngine/Compiler/Compiler.cs +++ b/src/ScriptEngine/Compiler/Compiler.cs @@ -772,9 +772,9 @@ private void BuildForEachStatement() SetTryBlockFlag(savedTryFlag); PopStructureToken(); - if (_lastExtractedLexem.Token == Token.EndLoop) - { - AddCommand(OperationCode.LineNum, _lastExtractedLexem.LineNumber, isExtraCode: true); + if (_lastExtractedLexem.Token == Token.EndLoop) + { + AddCommand(OperationCode.LineNum, _lastExtractedLexem.LineNumber, isExtraCode: true); } AddCommand(OperationCode.Jmp, loopBegin); @@ -837,15 +837,15 @@ private void BuildCountableForStatement() SetTryBlockFlag(savedTryFlag); PopStructureToken(); - if (_lastExtractedLexem.Token == Token.EndLoop) - { - AddCommand(OperationCode.LineNum, _lastExtractedLexem.LineNumber, isExtraCode: true); + if (_lastExtractedLexem.Token == Token.EndLoop) + { + AddCommand(OperationCode.LineNum, _lastExtractedLexem.LineNumber, isExtraCode: true); } // jmp to start AddCommand(OperationCode.Jmp, indexLoopBegin); var indexLoopEnd = AddCommand(OperationCode.PopTmp, 1); - + var cmd = _module.Code[conditionIndex]; cmd.Argument = indexLoopEnd; _module.Code[conditionIndex] = cmd; @@ -853,32 +853,32 @@ private void BuildCountableForStatement() CorrectBreakStatements(_nestedLoops.Pop(), indexLoopEnd); NextToken(); - } - - private void BuildWhileStatement() - { - NextToken(); - var conditionIndex = _module.Code.Count; - var loopRecord = NestedLoopInfo.New(); - loopRecord.startPoint = conditionIndex; - _nestedLoops.Push(loopRecord); - BuildExpression(Token.Loop); - PushStructureToken(Token.EndLoop); - - var jumpFalseIndex = AddCommand(OperationCode.JmpFalse, 0); - NextToken(); - bool savedTryFlag = SetTryBlockFlag(false); - BuildCodeBatch(); - SetTryBlockFlag(savedTryFlag); - PopStructureToken(); - - if (_lastExtractedLexem.Token == Token.EndLoop) - { - AddCommand(OperationCode.LineNum, _lastExtractedLexem.LineNumber, isExtraCode: true); - } - - AddCommand(OperationCode.Jmp, conditionIndex); - + } + + private void BuildWhileStatement() + { + NextToken(); + var conditionIndex = _module.Code.Count; + var loopRecord = NestedLoopInfo.New(); + loopRecord.startPoint = conditionIndex; + _nestedLoops.Push(loopRecord); + BuildExpression(Token.Loop); + PushStructureToken(Token.EndLoop); + + var jumpFalseIndex = AddCommand(OperationCode.JmpFalse, 0); + NextToken(); + bool savedTryFlag = SetTryBlockFlag(false); + BuildCodeBatch(); + SetTryBlockFlag(savedTryFlag); + PopStructureToken(); + + if (_lastExtractedLexem.Token == Token.EndLoop) + { + AddCommand(OperationCode.LineNum, _lastExtractedLexem.LineNumber, isExtraCode: true); + } + + AddCommand(OperationCode.Jmp, conditionIndex); + var endLoop = AddCommand(OperationCode.Nop, 0); _module.Code[jumpFalseIndex] = new Command() { Code = OperationCode.JmpFalse, @@ -1463,18 +1463,43 @@ private bool[] BuildArgumentList() PushStructureToken(Token.ClosePar); List arguments = new List(); + + try + { + NextToken(); // съели открывающую скобку + while (_lastExtractedLexem.Token != Token.ClosePar) + { + PushPassedArgument(arguments); + } + + if (_lastExtractedLexem.Token != Token.ClosePar) + throw CompilerException.TokenExpected(")"); + + NextToken(); // съели закрывающую скобку + } + finally + { + PopStructureToken(); + } - NextToken(); - while (_lastExtractedLexem.Token != Token.ClosePar) + return arguments.ToArray(); + } + + private void PushPassedArgument(IList arguments) + { + if (_lastExtractedLexem.Token == Token.Comma) { - if (_lastExtractedLexem.Token == Token.Comma) + AddCommand(OperationCode.PushDefaultArg, 0); + arguments.Add(false); + NextToken(); + if (_lastExtractedLexem.Token == Token.ClosePar) { AddCommand(OperationCode.PushDefaultArg, 0); arguments.Add(false); - NextToken(); - continue; } - + } + else if (_lastExtractedLexem.Token != Token.ClosePar) + { BuildExpression(Token.Comma); arguments.Add(true); if (_lastExtractedLexem.Token == Token.Comma) @@ -1482,20 +1507,11 @@ private bool[] BuildArgumentList() NextToken(); if (_lastExtractedLexem.Token == Token.ClosePar) { - // список аргументов кончился AddCommand(OperationCode.PushDefaultArg, 0); arguments.Add(false); } } } - - if (_lastExtractedLexem.Token != Token.ClosePar) - throw CompilerException.TokenExpected(")"); - - NextToken(); // съели закрывающую скобку - PopStructureToken(); - - return arguments.ToArray(); } private void BuildLoadVariable(string identifier) @@ -1818,9 +1834,9 @@ private Token[] PopStructureToken() private int AddCommand(OperationCode code, int arg, bool isExtraCode = false) { - var addr = _module.Code.Count; - if (!isExtraCode || ProduceExtraCode.HasFlag(CodeGenerationFlags.CodeStatistics)) - { + var addr = _module.Code.Count; + if (!isExtraCode || ProduceExtraCode.HasFlag(CodeGenerationFlags.CodeStatistics)) + { _module.Code.Add(new Command() { Code = code, Argument = arg }); } return addr; From 6f91d05a08b62b2b9e7f67b35ee0c2977c810825 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9?= Date: Wed, 12 Jul 2017 08:46:50 +0300 Subject: [PATCH 067/230] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D1=81=D1=81=D1=8B=D0=BB=D0=BA=D1=83=20=D0=BD=D0=B0=20?= =?UTF-8?q?=D0=B1=D0=B8=D0=B1=D0=BB=D0=B8=D0=BE=D1=82=D0=B5=D0=BA=D1=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 53ad2986a..51851c690 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # README # - -[![Join the chat at https://gitter.im/EvilBeaver/OneScript](https://badges.gitter.im/EvilBeaver/OneScript.svg)](https://gitter.im/EvilBeaver/OneScript?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +[![Join the chat at https://gitter.im/EvilBeaver/OneScript](https://badges.gitter.im/EvilBeaver/OneScript.svg)](https://gitter.im/EvilBeaver/OneScript?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) ### Проект является независимой кросс-платформенной реализацией виртуальной машины, исполняющей скрипты на языке 1С:Предприятие. @@ -22,4 +22,4 @@ http://oscript.io ## Библиотека полезных скриптов -В поставку OneScript уже входит набор наиболее часто используемых пакетов. Эти пакеты разрабатываются в едином репозитарии на github и доступны для всем желающим. \ No newline at end of file +В поставку OneScript уже входит набор наиболее часто используемых пакетов. Эти пакеты разрабатываются в едином репозитарии на github https://github.com/oscript-library и доступны для всем желающим. From 4fa0ae6d93e4ab876dd71615e482f44917c6b94b Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Wed, 12 Jul 2017 18:01:06 +0300 Subject: [PATCH 068/230] =?UTF-8?q?=D0=B8=D0=BD=D0=BA=D1=80=D0=B5=D0=BC?= =?UTF-8?q?=D0=B5=D0=BD=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Jenkinsfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jenkinsfile b/Jenkinsfile index 5f33755c2..83a54ec2f 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -4,7 +4,7 @@ pipeline { agent none environment { - ReleaseNumber = 17 + ReleaseNumber = 18 outputEnc = '65001' } From a8cfddd740664ca1edba5c541c26a9a41a3045ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B5=D1=80=D0=B3=D1=A3=D0=B9=20=D0=91=D0=B0=D1=82?= =?UTF-8?q?=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Sat, 15 Jul 2017 22:33:17 +0300 Subject: [PATCH 069/230] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D1=8B=20=D0=BA=D0=BE=D0=BC=D0=B0=D0=BD=D0=B4=D1=8B?= =?UTF-8?q?=20=D0=B2=20bash-=D0=BF=D0=BE=D0=B4=D1=81=D0=BA=D0=B0=D0=B7?= =?UTF-8?q?=D0=BA=D1=83=20opm.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- install/builders/deb/oscript-opm-completion | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/install/builders/deb/oscript-opm-completion b/install/builders/deb/oscript-opm-completion index 9b1f647b8..9c6fa7da2 100644 --- a/install/builders/deb/oscript-opm-completion +++ b/install/builders/deb/oscript-opm-completion @@ -3,9 +3,10 @@ _opm_complete() local cur opts COMPREPLY=() cur="${COMP_WORDS[COMP_CWORD]}" - opts="build prepare install update app help" + opts="build prepare install update app help config list run test version" COMPREPLY=( $(compgen -W "$opts" -- ${cur}) ) return 0 } complete -F _opm_complete opm +# vim: filetype=sh From 3ed6931d5b0e36831925d65b9455d63603989ab5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B5=D1=80=D0=B3=D1=A3=D0=B9=20=D0=91=D0=B0=D1=82?= =?UTF-8?q?=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Sat, 15 Jul 2017 22:45:06 +0300 Subject: [PATCH 070/230] =?UTF-8?q?=D0=9F=D0=BE=D0=B4=D1=81=D1=82=D0=B0?= =?UTF-8?q?=D0=BD=D0=BE=D0=B2=D0=BA=D0=B0=20=D1=84=D0=B0=D0=B9=D0=BB=D0=BE?= =?UTF-8?q?=D0=B2=20=D0=B2=20bash-=D0=BF=D0=BE=D0=B4=D1=81=D0=BA=D0=B0?= =?UTF-8?q?=D0=B7=D0=BA=D0=B5=20opm.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- install/builders/deb/oscript-opm-completion | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/install/builders/deb/oscript-opm-completion b/install/builders/deb/oscript-opm-completion index 9c6fa7da2..8589d684b 100644 --- a/install/builders/deb/oscript-opm-completion +++ b/install/builders/deb/oscript-opm-completion @@ -3,8 +3,12 @@ _opm_complete() local cur opts COMPREPLY=() cur="${COMP_WORDS[COMP_CWORD]}" - opts="build prepare install update app help config list run test version" - COMPREPLY=( $(compgen -W "$opts" -- ${cur}) ) + if [[ $COMP_CWORD == 1 ]] ; then + opts="build prepare install update app help config list run test version" + COMPREPLY=( $(compgen -W "$opts" -- ${cur}) ) + return 0 + fi + COMPREPLY=( $(compgen -df ${cur}) ) return 0 } complete -F _opm_complete opm From f5a78cebaf7b50f5764f4889a87dd2a47859d40d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B5=D1=80=D0=B3=D1=A3=D0=B9=20=D0=91=D0=B0=D1=82?= =?UTF-8?q?=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Sun, 16 Jul 2017 16:01:25 +0300 Subject: [PATCH 071/230] make install --- Makefile | 41 +++++++++++++++++++++++++++++++++++------ 1 file changed, 35 insertions(+), 6 deletions(-) diff --git a/Makefile b/Makefile index 715a7d37e..d4fedf09b 100644 --- a/Makefile +++ b/Makefile @@ -1,23 +1,27 @@ +SOLUTION_FILE=src/1Script_Mono.sln PLATFORM="Any CPU" CONFIGURATION=Release SOURCEBINDIR=src/oscript/bin/${CONFIGURATION} -BIN_OUTPUTDIR=bin -LIB_OUTPUTDIR=lib +BIN_OUTPUTDIR=dist/bin +LIB_OUTPUTDIR=dist/lib OSCRIPTEXE=${BIN_OUTPUTDIR}/oscript.exe OPMOS=${LIB_OUTPUTDIR}/opm/opm.os OPM="${OSCRIPTEXE} ${OPMOS}" +PREFIX=/usr all: dist dist: ${OSCRIPTEXE} lib lib: ${OSCRIPTEXE} - test -d ${LIB_OUTPUTDIR} && rm -rf ${LIB_OUTPUTDIR} - mkdir -p ${LIB_OUTPUTDIR} + test -d ${LIB_OUTPUTDIR} || mkdir -p ${LIB_OUTPUTDIR} cp -r oscript-library/src/* ${LIB_OUTPUTDIR} -${OSCRIPTEXE}: - xbuild /p:Platform=${PLATFORM} /p:Configuration=${CONFIGURATION} src/1Script_Mono.sln +NUGET: + nuget restore ${SOLUTION_FILE} + +${OSCRIPTEXE}: NUGET + msbuild /p:Platform=${PLATFORM} /p:Configuration=${CONFIGURATION} ${SOLUTION_FILE} test -d ${BIN_OUTPUTDIR} || mkdir -p ${BIN_OUTPUTDIR} cp ${SOURCEBINDIR}/*.dll ${BIN_OUTPUTDIR} cp ${SOURCEBINDIR}/*.exe ${BIN_OUTPUTDIR} @@ -29,4 +33,29 @@ clean: ${OPMOS}: +install: install_bin install_lib + +install_bin: + mkdir -p ${PREFIX}/share/oscript/bin + cp ${BIN_OUTPUTDIR}/* ${PREFIX}/share/oscript/bin + cp install/builders/deb/oscript ${PREFIX}/bin/oscript + cp install/builders/deb/oscript-cgi ${PREFIX}/bin/oscript-cgi + +install_lib: + mkdir -p ${PREFIX}/share/oscript/lib + cp -r ${LIB_OUTPUTDIR}/* ${PREFIX}/share/oscript/lib + cp install/builders/deb/oscript-opm ${PREFIX}/bin/oscript-opm + ln -s ${PREFIX}/bin/oscript-opm ${PREFIX}/bin/opm + +uninstall: uninstall_lib uninstall_bin + +uninstall_bin: + rm -rf ${PREFIX}/share/oscript/bin + rm ${PREFIX}/bin/oscript + +uninstall_lib: + rm ${PREFIX}/bin/opm + rm ${PREFIX}/bin/oscript-opm + rm -rf ${PREFIX}/share/oscript/lib + .PHONY: all install uninstall dist lib clean From b836fe4e013468adc1589098fba950d31001af40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B5=D1=80=D0=B3=D1=A3=D0=B9=20=D0=91=D0=B0=D1=82?= =?UTF-8?q?=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Sun, 16 Jul 2017 16:25:38 +0300 Subject: [PATCH 072/230] =?UTF-8?q?18-=D1=8F=20=D0=B2=D0=B5=D1=80=D1=81?= =?UTF-8?q?=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- appveyor.yml | 2 +- src/GlobalAssemblyInfo.cs | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 56e68582f..f0e54c041 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,4 +1,4 @@ -version: 1.0.17-alpha{build} +version: 1.0.18-alpha{build} pull_requests: do_not_increment_build_number: true configuration: Release diff --git a/src/GlobalAssemblyInfo.cs b/src/GlobalAssemblyInfo.cs index 0130fb7a9..ce29861b5 100644 --- a/src/GlobalAssemblyInfo.cs +++ b/src/GlobalAssemblyInfo.cs @@ -17,9 +17,9 @@ This Source Code Form is subject to the terms of the [assembly: System.Reflection.AssemblyCompany("BeaverSoft")] [assembly: System.Reflection.AssemblyCopyright("Copyright (c) 2017 EvilBeaver")] [assembly: System.Reflection.AssemblyConfiguration("Commit 2a614c0")] -[assembly: System.Reflection.AssemblyVersion("1.0.17.0")] -[assembly: System.Reflection.AssemblyFileVersion("1.0.17.0")] -[assembly: System.Reflection.AssemblyInformationalVersion("1.0.17.0")] +[assembly: System.Reflection.AssemblyVersion("1.0.18.0")] +[assembly: System.Reflection.AssemblyFileVersion("1.0.18.0")] +[assembly: System.Reflection.AssemblyInformationalVersion("1.0.18.0")] @@ -31,11 +31,11 @@ internal sealed partial class ThisAssembly { internal const string AssemblyConfiguration = "Commit 2a614c0"; - internal const string AssemblyVersion = "1.0.17.0"; + internal const string AssemblyVersion = "1.0.18.0"; - internal const string AssemblyFileVersion = "1.0.17.0"; + internal const string AssemblyFileVersion = "1.0.18.0"; - internal const string AssemblyInformationalVersion = "1.0.17.0"; + internal const string AssemblyInformationalVersion = "1.0.18.0"; private ThisAssembly() { } From 2e0f9eac9a08bdbea1ba58ff58bb4a4f060b65eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B5=D1=80=D0=B3=D1=A3=D0=B9=20=D0=91=D0=B0=D1=82?= =?UTF-8?q?=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Sun, 16 Jul 2017 16:26:54 +0300 Subject: [PATCH 073/230] Makefile: rm cgi --- Makefile | 1 + 1 file changed, 1 insertion(+) diff --git a/Makefile b/Makefile index d4fedf09b..d9fc5305d 100644 --- a/Makefile +++ b/Makefile @@ -52,6 +52,7 @@ uninstall: uninstall_lib uninstall_bin uninstall_bin: rm -rf ${PREFIX}/share/oscript/bin rm ${PREFIX}/bin/oscript + rm ${PREFIX}/bin/oscript-cgi uninstall_lib: rm ${PREFIX}/bin/opm From 5489a8d10cb76b4c7c0e3df802d965c9c3463eb1 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Fri, 21 Jul 2017 14:13:01 +0300 Subject: [PATCH 074/230] =?UTF-8?q?=D0=97=D0=B0=D0=B4=D0=B5=D0=BB=20=D0=BF?= =?UTF-8?q?=D0=BE=20stepin?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/DebugServer/DebugeeProcess.cs | 5 +++ src/DebugServer/OscriptDebugSession.cs | 9 ++++- src/ScriptEngine/Machine/MachineInstance.cs | 19 ++++++++++ .../Machine/MachineStopManager.cs | 35 ++++++++++++++++++- .../DebugServer/OscriptDebugController.cs | 4 ++- src/oscript/Program.cs | 1 - 6 files changed, 69 insertions(+), 4 deletions(-) diff --git a/src/DebugServer/DebugeeProcess.cs b/src/DebugServer/DebugeeProcess.cs index 0b2efaaef..c31f36cec 100644 --- a/src/DebugServer/DebugeeProcess.cs +++ b/src/DebugServer/DebugeeProcess.cs @@ -188,5 +188,10 @@ public void Next() { _debugger.Instance.Next(); } + + public void StepIn() + { + _debugger.Instance.StepIn(); + } } } diff --git a/src/DebugServer/OscriptDebugSession.cs b/src/DebugServer/OscriptDebugSession.cs index 66a42067e..1b0ae26ed 100644 --- a/src/DebugServer/OscriptDebugSession.cs +++ b/src/DebugServer/OscriptDebugSession.cs @@ -250,7 +250,14 @@ public override void Next(Response response, dynamic arguments) public override void StepIn(Response response, dynamic arguments) { - throw new NotImplementedException(); + SendResponse(response); + lock (_process) + { + if (!_process.HasExited) + { + _process.StepIn(); + } + } } public override void StepOut(Response response, dynamic arguments) diff --git a/src/ScriptEngine/Machine/MachineInstance.cs b/src/ScriptEngine/Machine/MachineInstance.cs index 7e1c19638..01f49ff94 100644 --- a/src/ScriptEngine/Machine/MachineInstance.cs +++ b/src/ScriptEngine/Machine/MachineInstance.cs @@ -146,6 +146,21 @@ public void StopAtNextLine() _stopManager.AddNextLineStop(_currentFrame); } + public void StepIn() + { + if (_stopManager == null) + throw new InvalidOperationException("Machine is not in debug mode"); + + _stopManager.StopOnMethodEntry(); + } + + public void PrepareDebugContinuation() + { + if (_stopManager == null) + throw new InvalidOperationException("Machine is not in debug mode"); + + _stopManager.ClearSteppingStops(); + } public IValue Evaluate(string expression, bool separate = false) { @@ -953,6 +968,10 @@ private bool MethodCallImpl(int arg, bool asFunc) frame.InstructionPointer = methDescr.EntryPoint; PushFrame(); SetFrame(frame); + if (_stopManager != null) + { + _stopManager.OnFrameEntered(frame); + } needsDiscarding = methInfo.IsFunction && !asFunc; } diff --git a/src/ScriptEngine/Machine/MachineStopManager.cs b/src/ScriptEngine/Machine/MachineStopManager.cs index b65a374bf..e1e990302 100644 --- a/src/ScriptEngine/Machine/MachineStopManager.cs +++ b/src/ScriptEngine/Machine/MachineStopManager.cs @@ -45,6 +45,33 @@ internal void AddNextLineStop(ExecutionFrame currentFrame) }); } + internal void StopOnMethodEntry(ExecutionFrame returnFrame) + { + _registeredStops.Add(new StopHandle() + { + kind = StopKind.MethodEntry, + frames = new ExecutionFrame[2] + { + null, + returnFrame + } + }); + } + + internal void OnFrameEntered(ExecutionFrame frame) + { + int idx = _registeredStops.FindIndex(x => x.kind == StopKind.MethodEntry); + if (idx >= 0) + { + _registeredStops[idx].frames[0] = frame; + } + } + + internal void OnFrameExited(ExecutionFrame frame) + { + + } + internal bool ShouldStopHere(string module, ExecutionFrame frame) { for (int i = _registeredStops.Count-1; i >=0; i--) @@ -55,7 +82,7 @@ internal bool ShouldStopHere(string module, ExecutionFrame frame) return true; } - if (stop.kind == StopKind.NextLine && stop.frames.Contains(frame)) + if ((stop.kind == StopKind.NextLine||stop.kind == StopKind.MethodEntry) && stop.frames.Contains(frame)) { _registeredStops.RemoveAt(i); return true; @@ -64,5 +91,11 @@ internal bool ShouldStopHere(string module, ExecutionFrame frame) return false; } + + public void ClearSteppingStops() + { + var copy = _registeredStops.Where(x => x.kind == StopKind.SourceLine).ToList(); + _registeredStops = copy; + } } } diff --git a/src/oscript/DebugServer/OscriptDebugController.cs b/src/oscript/DebugServer/OscriptDebugController.cs index 2bef1e922..250c11462 100644 --- a/src/oscript/DebugServer/OscriptDebugController.cs +++ b/src/oscript/DebugServer/OscriptDebugController.cs @@ -87,6 +87,7 @@ private bool CallbackChannelIsReady() public void Execute() { RegisterEventListener(); + _machine.PrepareDebugContinuation(); _debugCommandEvent.Set(); } @@ -191,7 +192,8 @@ public void Next() public void StepIn() { - throw new NotImplementedException(); + _machine.StepIn(); + _debugCommandEvent.Set(); } public void StepOut() diff --git a/src/oscript/Program.cs b/src/oscript/Program.cs index dff8626ab..6dd27d819 100644 --- a/src/oscript/Program.cs +++ b/src/oscript/Program.cs @@ -16,7 +16,6 @@ class Program static int Main(string[] args) { int returnCode; - var behavior = BehaviorSelector.Select(args); try { From 0e8991f903b50b817ae00649282cb05ce2d912fc Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Fri, 28 Jul 2017 16:44:51 +0300 Subject: [PATCH 075/230] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=BF=D0=BE=D1=81=D1=82=D0=B0=D0=B2=D0=BB=D1=8F=D0=B5?= =?UTF-8?q?=D0=BC=D1=83=D1=8E=20=D0=B1=D0=B8=D0=B1=D0=BB=D0=B8=D0=BE=D1=82?= =?UTF-8?q?=D0=B5=D0=BA=D1=83.=20see=20#490?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- oscript-library | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/oscript-library b/oscript-library index 7b0c542a6..99175103f 160000 --- a/oscript-library +++ b/oscript-library @@ -1 +1 @@ -Subproject commit 7b0c542a65da429eed263d1b516a7e92e1780fed +Subproject commit 99175103f0f537cd7e12f2f58da5d8bc2a8de28e From 3d5d82d377189c604a534c19f1f4ce4b9301d28c Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Thu, 3 Aug 2017 08:17:34 +0300 Subject: [PATCH 076/230] =?UTF-8?q?=D0=9F=D1=83=D0=B1=D0=BB=D0=B8=D0=BA?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D1=8F=20=D0=BD=D0=BE=D1=87=D0=BD=D0=BE=D0=B9?= =?UTF-8?q?=20=D1=81=D0=B1=D0=BE=D1=80=D0=BA=D0=B8=20(=D1=82=D0=B5=D1=81?= =?UTF-8?q?=D1=82)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Jenkinsfile | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index 83a54ec2f..e7429005e 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -95,7 +95,7 @@ pipeline { unstash 'buildResults' //unstash 'sitedoc' bat "chcp $outputEnc > nul\r\n\"${tool 'MSBuild'}\" BuildAll.csproj /p:Configuration=Release /p:Platform=x86 /t:CreateZip;CreateInstall;CreateNuget" - archiveArtifacts artifacts: '**/dist/*.exe, **/dist/*.msi, **/dist/*.zip, **/dist/*.nupkg, **/tests/*.xml', fingerprint: true + stash includes: 'dist/*.exe, **/dist/*.msi, **/dist/*.zip, **/dist/*.nupkg', name: 'winDist' } } } @@ -122,8 +122,26 @@ pipeline { sh ./rpm-build.sh $DISTPATH '''.stripIndent() - archiveArtifacts artifacts: 'output/*', fingerprint: true + stash includes: 'output/*', name: 'linDist' + + } + + } + + stage ('Publishing night-build') { + when { branch 'develop' } + agent { label 'master' } + + dir('artifacts') { + deleteDir() + unstash 'winDist' + unstash 'linDist' + + fileOperations( + [fileCopyOperation(flattenFiles: false, includes: './*', targetLocation: '/var/www/oscript.io/download/versions/night-nuild/')] + ) + archiveArtifacts artifacts: '*', fingerprint: true } } From 12c642163c4b8d60c4e60643e868c450e90fcf23 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Thu, 3 Aug 2017 08:21:05 +0300 Subject: [PATCH 077/230] =?UTF-8?q?=D0=9E=D1=88=D0=B8=D0=B1=D0=BA=D0=B0=20?= =?UTF-8?q?=D0=B2=20jenkinsfile?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Jenkinsfile | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index e7429005e..b1e5a7df9 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -132,18 +132,19 @@ pipeline { when { branch 'develop' } agent { label 'master' } - dir('artifacts') { - deleteDir() - unstash 'winDist' - unstash 'linDist' + steps { + dir('artifacts') { + deleteDir() + unstash 'winDist' + unstash 'linDist' - fileOperations( - [fileCopyOperation(flattenFiles: false, includes: './*', targetLocation: '/var/www/oscript.io/download/versions/night-nuild/')] - ) + fileOperations( + [fileCopyOperation(flattenFiles: false, includes: './*', targetLocation: '/var/www/oscript.io/download/versions/night-nuild/')] + ) - archiveArtifacts artifacts: '*', fingerprint: true + archiveArtifacts artifacts: '*', fingerprint: true + } } - } } From 688dea537670b3d096919ea5a820c5f36729b45f Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Thu, 3 Aug 2017 08:44:35 +0300 Subject: [PATCH 078/230] Jenkinsfile --- Jenkinsfile | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index b1e5a7df9..e4b8dfaf5 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -95,7 +95,8 @@ pipeline { unstash 'buildResults' //unstash 'sitedoc' bat "chcp $outputEnc > nul\r\n\"${tool 'MSBuild'}\" BuildAll.csproj /p:Configuration=Release /p:Platform=x86 /t:CreateZip;CreateInstall;CreateNuget" - stash includes: 'dist/*.exe, **/dist/*.msi, **/dist/*.zip, **/dist/*.nupkg', name: 'winDist' + archiveArtifacts artifacts: '**/dist/*.exe, **/dist/*.msi, **/dist/*.zip, **/dist/*.nupkg', fingerprint: true + stash includes: 'dist/*.exe, **/dist/*.msi, **/dist/*.zip', name: 'winDist' } } } @@ -122,6 +123,7 @@ pipeline { sh ./rpm-build.sh $DISTPATH '''.stripIndent() + archiveArtifacts artifacts: 'output/*', fingerprint: true stash includes: 'output/*', name: 'linDist' } @@ -133,17 +135,14 @@ pipeline { agent { label 'master' } steps { - dir('artifacts') { - deleteDir() - unstash 'winDist' - unstash 'linDist' - - fileOperations( - [fileCopyOperation(flattenFiles: false, includes: './*', targetLocation: '/var/www/oscript.io/download/versions/night-nuild/')] - ) - - archiveArtifacts artifacts: '*', fingerprint: true - } + unstash 'winDist' + unstash 'linDist' + + sh ''' + TARGET="/var/www/oscript.io/download/versions/night-nuild/" + sudo rsync -v --delete --include 'dist/*.exe' --include '**/dist/*.msi' --include '**/dist/*.zip' $TARGET + sudo rsync -v --delete --include 'output/*' $TARGET + '''.stripIndent() } } From 8f2a4fa96fee1115de22385b954de07378497df9 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Thu, 3 Aug 2017 08:50:55 +0300 Subject: [PATCH 079/230] =?UTF-8?q?=D0=9E=D0=BF=D0=B5=D1=87=D0=B0=D1=82?= =?UTF-8?q?=D0=BA=D0=B0=20=D0=B2=20=D0=BF=D1=83=D1=82=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Jenkinsfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jenkinsfile b/Jenkinsfile index e4b8dfaf5..a295a176a 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -139,7 +139,7 @@ pipeline { unstash 'linDist' sh ''' - TARGET="/var/www/oscript.io/download/versions/night-nuild/" + TARGET="/var/www/oscript.io/download/versions/night-build/" sudo rsync -v --delete --include 'dist/*.exe' --include '**/dist/*.msi' --include '**/dist/*.zip' $TARGET sudo rsync -v --delete --include 'output/*' $TARGET '''.stripIndent() From 16f8ca76d2d48c7a45ce898d14bc4905d2389403 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Thu, 3 Aug 2017 08:52:40 +0300 Subject: [PATCH 080/230] =?UTF-8?q?=D0=A3=D1=82=D0=BE=D1=87=D0=BD=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=BC=D0=B0=D1=81=D0=BA=D1=83=20ZIP?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Jenkinsfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jenkinsfile b/Jenkinsfile index a295a176a..6a7fb9982 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -140,7 +140,7 @@ pipeline { sh ''' TARGET="/var/www/oscript.io/download/versions/night-build/" - sudo rsync -v --delete --include 'dist/*.exe' --include '**/dist/*.msi' --include '**/dist/*.zip' $TARGET + sudo rsync -v --delete --include 'dist/*.exe' --include '**/dist/*.msi' --include '**/dist/OneScript*.zip' $TARGET sudo rsync -v --delete --include 'output/*' $TARGET '''.stripIndent() } From 85f8580ae52bcaecbafe403b5e0943e8a34d607e Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Thu, 3 Aug 2017 09:17:24 +0300 Subject: [PATCH 081/230] =?UTF-8?q?=D0=9F=D1=80=D0=B0=D0=B2=D0=B8=D0=BB?= =?UTF-8?q?=D1=8C=D0=BD=D1=8B=D0=B9=20=D1=81=D0=B8=D0=BD=D1=82=D0=B0=D0=BA?= =?UTF-8?q?=D1=81=D0=B8=D1=81=20=D0=B4=D0=BB=D1=8F=20rsync?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Jenkinsfile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index 6a7fb9982..b4f35e850 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -140,8 +140,8 @@ pipeline { sh ''' TARGET="/var/www/oscript.io/download/versions/night-build/" - sudo rsync -v --delete --include 'dist/*.exe' --include '**/dist/*.msi' --include '**/dist/OneScript*.zip' $TARGET - sudo rsync -v --delete --include 'output/*' $TARGET + sudo rsync -rv --delete --exclude mddoc*.zip --exclude *.nuget dist/* $TARGET + sudo rsync -rv --delete --exclude *.src.rpm output/* $TARGET '''.stripIndent() } } From 982673c23ad130a2bfdaccf853d541f2daee6ffa Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Fri, 4 Aug 2017 18:39:01 +0300 Subject: [PATCH 082/230] =?UTF-8?q?=D0=9E=D1=82=D0=BD=D0=BE=D1=81=D0=B8?= =?UTF-8?q?=D1=82=D0=B5=D0=BB=D1=8C=D0=BD=D0=BE=20=D0=BD=D0=B5=D1=81=D1=82?= =?UTF-8?q?=D0=B0=D0=B1=D0=B8=D0=BB=D1=8C=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B5?= =?UTF-8?q?=D0=B0=D0=BB=D0=B8=D0=B7=D0=B0=D1=86=D0=B8=D1=8F=20=D0=BA=D0=BE?= =?UTF-8?q?=D0=BC=D0=B0=D0=BD=D0=B4=D1=8B=20StepIn?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine/Machine/MachineInstance.cs | 6 +- .../Machine/MachineStopManager.cs | 55 +++++++++++++------ 2 files changed, 40 insertions(+), 21 deletions(-) diff --git a/src/ScriptEngine/Machine/MachineInstance.cs b/src/ScriptEngine/Machine/MachineInstance.cs index 01f49ff94..952489751 100644 --- a/src/ScriptEngine/Machine/MachineInstance.cs +++ b/src/ScriptEngine/Machine/MachineInstance.cs @@ -151,14 +151,14 @@ public void StepIn() if (_stopManager == null) throw new InvalidOperationException("Machine is not in debug mode"); - _stopManager.StopOnMethodEntry(); + _stopManager.AddStopAtMethodEntry(); } public void PrepareDebugContinuation() { if (_stopManager == null) throw new InvalidOperationException("Machine is not in debug mode"); - + // ?? _stopManager.ClearSteppingStops(); } @@ -1486,7 +1486,7 @@ private void LineNum(int arg) CodeStat_LineReached(); } - if(MachineStopped != null && _stopManager != null && _stopManager.ShouldStopHere(_module.ModuleInfo.Origin, _currentFrame)) + if(MachineStopped != null && _stopManager != null && _stopManager.ShouldStopAtThisLine(_module.ModuleInfo.Origin, _currentFrame)) { CreateFullCallstack(); MachineStopped?.Invoke(this, new MachineStoppedEventArgs(MachineStopReason.Breakpoint)); diff --git a/src/ScriptEngine/Machine/MachineStopManager.cs b/src/ScriptEngine/Machine/MachineStopManager.cs index e1e990302..6aa950526 100644 --- a/src/ScriptEngine/Machine/MachineStopManager.cs +++ b/src/ScriptEngine/Machine/MachineStopManager.cs @@ -19,12 +19,15 @@ struct StopHandle public StopKind kind; public string source; public int line; - public ExecutionFrame[] frames; + public ExecutionFrame frame; } class MachineStopManager { List _registeredStops = new List(); + Stack _callStack = new Stack(); + + private bool _mustStopOnMethodEntry = false; internal void AddSourceLineStop(string source, int line) { @@ -36,43 +39,59 @@ internal void AddSourceLineStop(string source, int line) }); } + internal void AddStopAtMethodEntry() + { + _mustStopOnMethodEntry = true; + } + internal void AddNextLineStop(ExecutionFrame currentFrame) { _registeredStops.Add(new StopHandle() { kind = StopKind.NextLine, - frames = new []{ currentFrame } + frame = currentFrame }); } - internal void StopOnMethodEntry(ExecutionFrame returnFrame) + internal void AddStopOnMethodExit() { _registeredStops.Add(new StopHandle() { - kind = StopKind.MethodEntry, - frames = new ExecutionFrame[2] - { - null, - returnFrame - } + kind = StopKind.MethodReturn, + frame = _callStack.Peek() }); } - + internal void OnFrameEntered(ExecutionFrame frame) { - int idx = _registeredStops.FindIndex(x => x.kind == StopKind.MethodEntry); - if (idx >= 0) + _callStack.Push(frame); + if (_mustStopOnMethodEntry) { - _registeredStops[idx].frames[0] = frame; + _registeredStops.Add(new StopHandle() + { + frame = frame, + kind = StopKind.MethodEntry + }); + _mustStopOnMethodEntry = false; } } - internal void OnFrameExited(ExecutionFrame frame) + internal void OnFrameExited(out bool shouldStop) { - + var frame = _callStack.Pop(); + var itemIdx = _registeredStops.FindIndex(x => x.kind == StopKind.MethodReturn && x.frame == frame); + if (itemIdx >= 0) + { + shouldStop = true; + _registeredStops.RemoveAt(itemIdx); + } + else + { + shouldStop = false; + } } - - internal bool ShouldStopHere(string module, ExecutionFrame frame) + + internal bool ShouldStopAtThisLine(string module, ExecutionFrame frame) { for (int i = _registeredStops.Count-1; i >=0; i--) { @@ -82,7 +101,7 @@ internal bool ShouldStopHere(string module, ExecutionFrame frame) return true; } - if ((stop.kind == StopKind.NextLine||stop.kind == StopKind.MethodEntry) && stop.frames.Contains(frame)) + if ((stop.kind == StopKind.NextLine||stop.kind == StopKind.MethodEntry) && stop.frame == frame) { _registeredStops.RemoveAt(i); return true; From 2257b9db0615639954d82867c4b52386c83106f6 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Mon, 7 Aug 2017 18:18:59 +0300 Subject: [PATCH 083/230] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B4=D0=B5?= =?UTF-8?q?=D0=BB=D0=BA=D0=B0=20=D0=BD=D0=B0=20=D0=B4=D1=80=D1=83=D0=B3?= =?UTF-8?q?=D0=BE=D0=B9=20=D0=BF=D0=BE=D0=B4=D1=85=D0=BE=D0=B4=20=D0=BA=20?= =?UTF-8?q?=D1=88=D0=B0=D0=B3=D0=B0=D0=BC=20=D0=B8=20=D1=82=D0=BE=D1=87?= =?UTF-8?q?=D0=BA=D0=B0=D0=BC=20=D0=BE=D1=81=D1=82=D0=B0=D0=BD=D0=BE=D0=B2?= =?UTF-8?q?=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine/Machine/MachineInstance.cs | 17 +-- .../Machine/MachineStopManager.cs | 130 ++++++------------ 2 files changed, 51 insertions(+), 96 deletions(-) diff --git a/src/ScriptEngine/Machine/MachineInstance.cs b/src/ScriptEngine/Machine/MachineInstance.cs index 952489751..a02e6cb6d 100644 --- a/src/ScriptEngine/Machine/MachineInstance.cs +++ b/src/ScriptEngine/Machine/MachineInstance.cs @@ -132,9 +132,9 @@ public bool SetBreakpoint(string source, int line, out int id) if (_stopManager == null) throw new InvalidOperationException("Machine is not in debug mode"); - _stopManager.AddSourceLineStop(source, line); + throw new NotImplementedException(); + //id = _stopManager.AddSourceLineStop(source, line); - id = source.GetHashCode() + line; return true; } @@ -142,8 +142,9 @@ public void StopAtNextLine() { if (_stopManager == null) throw new InvalidOperationException("Machine is not in debug mode"); - - _stopManager.AddNextLineStop(_currentFrame); + + throw new NotImplementedException(); + //_stopManager.AddNextLineStop(_currentFrame); } public void StepIn() @@ -151,7 +152,7 @@ public void StepIn() if (_stopManager == null) throw new InvalidOperationException("Machine is not in debug mode"); - _stopManager.AddStopAtMethodEntry(); + // _stopManager.AddStopAtMethodEntry(); } public void PrepareDebugContinuation() @@ -159,7 +160,7 @@ public void PrepareDebugContinuation() if (_stopManager == null) throw new InvalidOperationException("Machine is not in debug mode"); // ?? - _stopManager.ClearSteppingStops(); + //_stopManager.ClearSteppingStops(); } public IValue Evaluate(string expression, bool separate = false) @@ -970,7 +971,7 @@ private bool MethodCallImpl(int arg, bool asFunc) SetFrame(frame); if (_stopManager != null) { - _stopManager.OnFrameEntered(frame); + //_stopManager.OnFrameEntered(frame); } needsDiscarding = methInfo.IsFunction && !asFunc; @@ -1486,7 +1487,7 @@ private void LineNum(int arg) CodeStat_LineReached(); } - if(MachineStopped != null && _stopManager != null && _stopManager.ShouldStopAtThisLine(_module.ModuleInfo.Origin, _currentFrame)) + if(MachineStopped != null && _stopManager != null /*&& _stopManager.ShouldStopAtThisLine(_module.ModuleInfo.Origin, _currentFrame)*/) { CreateFullCallstack(); MachineStopped?.Invoke(this, new MachineStoppedEventArgs(MachineStopReason.Breakpoint)); diff --git a/src/ScriptEngine/Machine/MachineStopManager.cs b/src/ScriptEngine/Machine/MachineStopManager.cs index 6aa950526..3d3b921cd 100644 --- a/src/ScriptEngine/Machine/MachineStopManager.cs +++ b/src/ScriptEngine/Machine/MachineStopManager.cs @@ -3,118 +3,72 @@ using System.Linq; using System.Text; +using ScriptEngine.Environment; + namespace ScriptEngine.Machine { - - enum StopKind - { - SourceLine, - MethodEntry, - MethodReturn, - NextLine - } - struct StopHandle + internal enum DebugState { - public StopKind kind; - public string source; - public int line; - public ExecutionFrame frame; + Running, + SteppingOver, + SteppingIn, + SteppingOut } - class MachineStopManager + internal class Breakpoint { - List _registeredStops = new List(); - Stack _callStack = new Stack(); - - private bool _mustStopOnMethodEntry = false; + public string Module; + public ExecutionFrame HitFrame; + public int LineNumber; - internal void AddSourceLineStop(string source, int line) + public Breakpoint(int id) { - _registeredStops.Add(new StopHandle() - { - kind = StopKind.SourceLine, - line = line, - source = source - }); + BreakpointId = id; } - internal void AddStopAtMethodEntry() - { - _mustStopOnMethodEntry = true; - } + public int BreakpointId { get; } + } - internal void AddNextLineStop(ExecutionFrame currentFrame) - { - _registeredStops.Add(new StopHandle() - { - kind = StopKind.NextLine, - frame = currentFrame - }); - } - internal void AddStopOnMethodExit() - { - _registeredStops.Add(new StopHandle() - { - kind = StopKind.MethodReturn, - frame = _callStack.Peek() - }); - } + internal class MachineStopManager + { + private DebugState _currentState; + private List _breakpoints; - internal void OnFrameEntered(ExecutionFrame frame) + private int _bpIdsGenerator; + + public int SetBreakpoint(string module, int line) { - _callStack.Push(frame); - if (_mustStopOnMethodEntry) + return (new Breakpoint(_bpIdsGenerator++) { - _registeredStops.Add(new StopHandle() - { - frame = frame, - kind = StopKind.MethodEntry - }); - _mustStopOnMethodEntry = false; - } + LineNumber = line, + Module = module + }).BreakpointId; } - internal void OnFrameExited(out bool shouldStop) + public void RemoveBreakpoint(int bpId) { - var frame = _callStack.Pop(); - var itemIdx = _registeredStops.FindIndex(x => x.kind == StopKind.MethodReturn && x.frame == frame); - if (itemIdx >= 0) - { - shouldStop = true; - _registeredStops.RemoveAt(itemIdx); - } - else - { - shouldStop = false; - } + int index = _breakpoints.FindIndex(x => x.BreakpointId == bpId); + if(index >= 0) + _breakpoints.RemoveAt(index); } - - internal bool ShouldStopAtThisLine(string module, ExecutionFrame frame) + + public bool LineHit(string module, ExecutionFrame currentFrame) { - for (int i = _registeredStops.Count-1; i >=0; i--) + switch (_currentState) { - var stop = _registeredStops[i]; - if (stop.kind == StopKind.SourceLine && stop.source == module && stop.line == frame.LineNumber) - { - return true; - } - - if ((stop.kind == StopKind.NextLine||stop.kind == StopKind.MethodEntry) && stop.frame == frame) - { - _registeredStops.RemoveAt(i); - return true; - } + case DebugState.Running: + throw new NotImplementedException(); + case DebugState.SteppingIn: + throw new NotImplementedException(); + case DebugState.SteppingOut: + throw new NotImplementedException(); + case DebugState.SteppingOver: + throw new NotImplementedException(); } - return false; - } - - public void ClearSteppingStops() - { - var copy = _registeredStops.Where(x => x.kind == StopKind.SourceLine).ToList(); - _registeredStops = copy; + throw new NotImplementedException(); } } } From b671771f88562cb4b93aa5538e151e091927d65d Mon Sep 17 00:00:00 2001 From: Dmitriy Kartashev Date: Tue, 8 Aug 2017 11:40:27 +0300 Subject: [PATCH 084/230] =?UTF-8?q?=D0=A2=D0=B5=D1=81=D1=82=20=D0=BF=D1=80?= =?UTF-8?q?=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B8=20=D0=B4=D0=B0=D1=82=D1=8B?= =?UTF-8?q?=20=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD=D0=B8=D1=8F=20?= =?UTF-8?q?=D0=B8=20=D0=B4=D0=B0=D1=82=D1=8B=20=D1=81=D0=BE=D0=B7=D0=B4?= =?UTF-8?q?=D0=B0=D0=BD=D0=B8=D1=8F.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/file-object.os | 28 ++++++++++++++++++++++++++++ tests/testrunner.os | 7 +++++++ 2 files changed, 35 insertions(+) diff --git a/tests/file-object.os b/tests/file-object.os index 54d43f296..8b25254a0 100644 --- a/tests/file-object.os +++ b/tests/file-object.os @@ -26,6 +26,7 @@ ВсеТесты.Добавить("ТестДолжен_ПроверитьПолучениеКаталогаВПолномПути"); ВсеТесты.Добавить("ТестДолжен_ПроверитьПолучениеКаталогаВКорневомПути"); ВсеТесты.Добавить("ТестДолжен_ПроверитьСвойстваОбъектаИнициированногоПустойСтрокой"); + ВсеТесты.Добавить("ТестДолжен_ПроверитьПолучениеДатСозданияИИзменения"); Возврат ВсеТесты; КонецФункции @@ -234,3 +235,30 @@ юТест.ПроверитьЛожь(Ф.Существует(), "Файл существует"); КонецПроцедуры + +Процедура ТестДолжен_ПроверитьПолучениеДатСозданияИИзменения() Экспорт + ТекущаяДата = ТекущаяДата(); + ВремФайл = ПолучитьИмяВременногоФайла("os"); + ЗаписьТекста = Новый ЗаписьТекста(ВремФайл); + ЗаписьТекста.ЗаписатьСтроку("---"); + ЗаписьТекста.Закрыть(); + Файл = Новый Файл(ВремФайл); + ВремяСоздания = Файл.ПолучитьВремяСоздания(); + + юТест.ПроверитьРавенствоДатСТочностью2Секунды(ТекущаяДата, ВремяСоздания); + + Приостановить(3000); + + ТекущаяДата = ТекущаяДата(); + ЗаписьТекста.Открыть(ВремФайл); + ЗаписьТекста.ЗаписатьСтроку("---"); + ЗаписьТекста.Закрыть(); + Файл = Новый Файл(ВремФайл); + ВремяСоздания = Файл.ПолучитьВремяСоздания(); + ВремяИзменения = Файл.ПолучитьВремяИзменения(); + + юТест.ПроверитьРавенствоДатСТочностью2Секунды(ТекущаяДата, ВремяИзменения); + юТест.ПроверитьНеРавенство(ВремяСоздания, ВремяИзменения); + + УдалитьФайлы(ВремФайл); +КонецПроцедуры diff --git a/tests/testrunner.os b/tests/testrunner.os index 9bc663f40..25f5e89d1 100644 --- a/tests/testrunner.os +++ b/tests/testrunner.os @@ -55,6 +55,13 @@ КонецЕсли; КонецПроцедуры +Процедура ПроверитьРавенствоДатСТочностью2Секунды(_Дата, _Дата2, ДопСообщениеОшибки = "") Экспорт + Если _Дата < _Дата2-2 или _Дата > _Дата2+2 Тогда + СообщениеОшибки = "Переданная дата ("+Формат(_Дата, "ДФ='dd.MM.yyyy HH:mm:ss'")+") не равна дате ("+Формат(_Дата2, "ДФ='dd.MM.yyyy HH:mm:ss'")+") с точностью до 2-х секунд, а хотели, чтобы они равнялись." + ФорматДСО(ДопСообщениеОшибки); + ВызватьИсключение(СообщениеОшибки); + КонецЕсли; +КонецПроцедуры + Процедура ПроверитьДату(_Дата, _Период, ДопСообщениеОшибки = "") Экспорт Если _Дата < _Период.ДатаНачала или _Дата > _Период.ДатаОкончания Тогда представление = ПредставлениеПериода(_Период.ДатаНачала, _Период.ДатаОкончания, "ФП = Истина"); From 5e87289644d5c933b7252c9aec7adc921b3c0f6b Mon Sep 17 00:00:00 2001 From: Dmitriy Kartashev Date: Tue, 8 Aug 2017 12:54:13 +0300 Subject: [PATCH 085/230] =?UTF-8?q?fixes=20#479=20=D0=9D=D0=B5=20=D1=85?= =?UTF-8?q?=D0=B2=D0=B0=D1=82=D0=B0=D0=BB=D0=BE=20=D0=B0=D0=BD=D0=B3=D0=BB?= =?UTF-8?q?=D0=B8=D0=B9=D1=81=D0=BA=D0=B8=D1=85=20=D1=81=D0=B8=D0=BD=D0=BE?= =?UTF-8?q?=D0=BD=D0=B8=D0=BC=D0=BE=D0=B2=20=D0=B2=20=D1=80=D0=B0=D0=B7?= =?UTF-8?q?=D0=BD=D1=8B=D1=85=20=D0=BC=D0=B5=D1=81=D1=82=D0=B0=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Library/SymbolsContext.cs | 12 ++++++------ .../TypeDescription/BinaryDataQualifiers.cs | 4 ++-- .../Library/TypeDescription/DateQualifiers.cs | 2 +- .../Library/TypeDescription/NumberQualifiers.cs | 6 +++--- .../Library/TypeDescription/StringQualifiers.cs | 4 ++-- .../Library/TypeDescription/TypeDescription.cs | 14 +++++++------- 6 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/ScriptEngine.HostedScript/Library/SymbolsContext.cs b/src/ScriptEngine.HostedScript/Library/SymbolsContext.cs index 936fa48d9..55cd80ef6 100644 --- a/src/ScriptEngine.HostedScript/Library/SymbolsContext.cs +++ b/src/ScriptEngine.HostedScript/Library/SymbolsContext.cs @@ -16,7 +16,7 @@ public sealed class SymbolsContext : AutoContext /// Символ перевода строки. /// /// Символ перевода строки. - [ContextProperty("ПС")] + [ContextProperty("ПС", "LF")] public string LF { get @@ -29,7 +29,7 @@ public string LF /// Символ возврата каретки. /// /// Символ возврата каретки. - [ContextProperty("ВК")] + [ContextProperty("ВК", "CR")] public string CR { get @@ -42,7 +42,7 @@ public string CR /// Символ вертикальной табуляции. /// /// Символ вертикальной табуляции. - [ContextProperty("ВТаб")] + [ContextProperty("ВТаб", "VTab")] public string VTab { get @@ -55,7 +55,7 @@ public string VTab /// Символ табуляции. /// /// Символ горизонтальной табуляции. - [ContextProperty("Таб")] + [ContextProperty("Таб", "Tab")] public string Tab { get @@ -68,7 +68,7 @@ public string Tab /// Символ промотки. /// /// Символ промотки. - [ContextProperty("ПФ")] + [ContextProperty("ПФ", "FF")] public string FF { get @@ -81,7 +81,7 @@ public string FF /// Символ неразрывного пробела. /// /// Символ неразрывного пробела. - [ContextProperty("НПП")] + [ContextProperty("НПП", "Nbsp")] public string Nbsp { get diff --git a/src/ScriptEngine.HostedScript/Library/TypeDescription/BinaryDataQualifiers.cs b/src/ScriptEngine.HostedScript/Library/TypeDescription/BinaryDataQualifiers.cs index 43f47c113..cb3b09964 100644 --- a/src/ScriptEngine.HostedScript/Library/TypeDescription/BinaryDataQualifiers.cs +++ b/src/ScriptEngine.HostedScript/Library/TypeDescription/BinaryDataQualifiers.cs @@ -20,10 +20,10 @@ public BinaryDataQualifiers(int length = 0, AllowedLength = allowedLength; } - [ContextProperty("Длина")] + [ContextProperty("Длина", "Length")] public int Length { get; } - [ContextProperty("ДопустимаяДлина")] + [ContextProperty("ДопустимаяДлина", "AllowedLength")] public AllowedLengthEnum AllowedLength { get; } public override bool Equals(object obj) diff --git a/src/ScriptEngine.HostedScript/Library/TypeDescription/DateQualifiers.cs b/src/ScriptEngine.HostedScript/Library/TypeDescription/DateQualifiers.cs index 73d45db17..17b37c2cc 100644 --- a/src/ScriptEngine.HostedScript/Library/TypeDescription/DateQualifiers.cs +++ b/src/ScriptEngine.HostedScript/Library/TypeDescription/DateQualifiers.cs @@ -18,7 +18,7 @@ public DateQualifiers(DateFractionsEnum dateFractions = DateFractionsEnum.Date) DateFractions = dateFractions; } - [ContextProperty("ЧастиДаты")] + [ContextProperty("ЧастиДаты", "DateFractions")] public DateFractionsEnum DateFractions { get; } public override bool Equals(object obj) diff --git a/src/ScriptEngine.HostedScript/Library/TypeDescription/NumberQualifiers.cs b/src/ScriptEngine.HostedScript/Library/TypeDescription/NumberQualifiers.cs index 84493f2cd..c59900c0a 100644 --- a/src/ScriptEngine.HostedScript/Library/TypeDescription/NumberQualifiers.cs +++ b/src/ScriptEngine.HostedScript/Library/TypeDescription/NumberQualifiers.cs @@ -22,13 +22,13 @@ public NumberQualifiers(int digits = 0, AllowedSign = allowedSign; } - [ContextProperty("ДопустимыйЗнак")] + [ContextProperty("ДопустимыйЗнак", "AllowedSign")] public AllowedSignEnum AllowedSign { get; } - [ContextProperty("Разрядность")] + [ContextProperty("Разрядность", "Digits")] public int Digits { get; } - [ContextProperty("РазрядностьДробнойЧасти")] + [ContextProperty("РазрядностьДробнойЧасти", "FractionDigits")] public int FractionDigits { get; } public override bool Equals(object obj) diff --git a/src/ScriptEngine.HostedScript/Library/TypeDescription/StringQualifiers.cs b/src/ScriptEngine.HostedScript/Library/TypeDescription/StringQualifiers.cs index 52681837c..080eb9b47 100644 --- a/src/ScriptEngine.HostedScript/Library/TypeDescription/StringQualifiers.cs +++ b/src/ScriptEngine.HostedScript/Library/TypeDescription/StringQualifiers.cs @@ -20,10 +20,10 @@ public StringQualifiers(int length = 0, AllowedLength = allowedLength; } - [ContextProperty("Длина")] + [ContextProperty("Длина", "Length")] public int Length { get; } - [ContextProperty("ДопустимаяДлина")] + [ContextProperty("ДопустимаяДлина", "AllowedLength")] public AllowedLengthEnum AllowedLength { get; } public override bool Equals(object obj) diff --git a/src/ScriptEngine.HostedScript/Library/TypeDescription/TypeDescription.cs b/src/ScriptEngine.HostedScript/Library/TypeDescription/TypeDescription.cs index 24f17b010..6c3c6b8c3 100644 --- a/src/ScriptEngine.HostedScript/Library/TypeDescription/TypeDescription.cs +++ b/src/ScriptEngine.HostedScript/Library/TypeDescription/TypeDescription.cs @@ -32,19 +32,19 @@ public TypeDescription(IEnumerable types = null, BinaryDataQualifiers = binaryDataQualifiers ?? new BinaryDataQualifiers(); } - [ContextProperty("КвалификаторыЧисла")] + [ContextProperty("КвалификаторыЧисла", "NumberQualifiers")] public NumberQualifiers NumberQualifiers { get; } - [ContextProperty("КвалификаторыСтроки")] + [ContextProperty("КвалификаторыСтроки", "StringQualifiers")] public StringQualifiers StringQualifiers { get; } - [ContextProperty("КвалификаторыДаты")] + [ContextProperty("КвалификаторыДаты", "DateQualifiers")] public DateQualifiers DateQualifiers { get; } - [ContextProperty("КвалификаторыДвоичныхДанных")] + [ContextProperty("КвалификаторыДвоичныхДанных", "BinaryDataQualifiers")] public BinaryDataQualifiers BinaryDataQualifiers { get; } - [ContextMethod("Типы")] + [ContextMethod("Типы", "Types")] public ArrayImpl Types() { var result = ArrayImpl.Constructor() as ArrayImpl; @@ -57,7 +57,7 @@ public ArrayImpl Types() return result; } - [ContextMethod("СодержитТип")] + [ContextMethod("СодержитТип", "ContainsType")] public bool ContainsType(IValue type) { if (type is TypeTypeValue) @@ -82,7 +82,7 @@ IValueAdjuster GetAdjusterForType(TypeTypeValue type) return null; } - [ContextMethod("ПривестиЗначение")] + [ContextMethod("ПривестиЗначение", "AdjustValue")] public IValue AdjustValue(IValue value = null) { From d21d3bde4e8fbd59062aa1c423a1acc45dcd1de0 Mon Sep 17 00:00:00 2001 From: Dmitriy Kartashev Date: Tue, 8 Aug 2017 13:43:53 +0300 Subject: [PATCH 086/230] =?UTF-8?q?Revert=20"fixes=20#479=20=D0=9D=D0=B5?= =?UTF-8?q?=20=D1=85=D0=B2=D0=B0=D1=82=D0=B0=D0=BB=D0=BE=20=D0=B0=D0=BD?= =?UTF-8?q?=D0=B3=D0=BB=D0=B8=D0=B9=D1=81=D0=BA=D0=B8=D1=85=20=D1=81=D0=B8?= =?UTF-8?q?=D0=BD=D0=BE=D0=BD=D0=B8=D0=BC=D0=BE=D0=B2=20=D0=B2=20=D1=80?= =?UTF-8?q?=D0=B0=D0=B7=D0=BD=D1=8B=D1=85=20=D0=BC=D0=B5=D1=81=D1=82=D0=B0?= =?UTF-8?q?=D1=85"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 5e87289644d5c933b7252c9aec7adc921b3c0f6b. --- .../Library/SymbolsContext.cs | 12 ++++++------ .../TypeDescription/BinaryDataQualifiers.cs | 4 ++-- .../Library/TypeDescription/DateQualifiers.cs | 2 +- .../Library/TypeDescription/NumberQualifiers.cs | 6 +++--- .../Library/TypeDescription/StringQualifiers.cs | 4 ++-- .../Library/TypeDescription/TypeDescription.cs | 14 +++++++------- 6 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/ScriptEngine.HostedScript/Library/SymbolsContext.cs b/src/ScriptEngine.HostedScript/Library/SymbolsContext.cs index 55cd80ef6..936fa48d9 100644 --- a/src/ScriptEngine.HostedScript/Library/SymbolsContext.cs +++ b/src/ScriptEngine.HostedScript/Library/SymbolsContext.cs @@ -16,7 +16,7 @@ public sealed class SymbolsContext : AutoContext /// Символ перевода строки. /// /// Символ перевода строки. - [ContextProperty("ПС", "LF")] + [ContextProperty("ПС")] public string LF { get @@ -29,7 +29,7 @@ public string LF /// Символ возврата каретки. /// /// Символ возврата каретки. - [ContextProperty("ВК", "CR")] + [ContextProperty("ВК")] public string CR { get @@ -42,7 +42,7 @@ public string CR /// Символ вертикальной табуляции. /// /// Символ вертикальной табуляции. - [ContextProperty("ВТаб", "VTab")] + [ContextProperty("ВТаб")] public string VTab { get @@ -55,7 +55,7 @@ public string VTab /// Символ табуляции. /// /// Символ горизонтальной табуляции. - [ContextProperty("Таб", "Tab")] + [ContextProperty("Таб")] public string Tab { get @@ -68,7 +68,7 @@ public string Tab /// Символ промотки. /// /// Символ промотки. - [ContextProperty("ПФ", "FF")] + [ContextProperty("ПФ")] public string FF { get @@ -81,7 +81,7 @@ public string FF /// Символ неразрывного пробела. /// /// Символ неразрывного пробела. - [ContextProperty("НПП", "Nbsp")] + [ContextProperty("НПП")] public string Nbsp { get diff --git a/src/ScriptEngine.HostedScript/Library/TypeDescription/BinaryDataQualifiers.cs b/src/ScriptEngine.HostedScript/Library/TypeDescription/BinaryDataQualifiers.cs index cb3b09964..43f47c113 100644 --- a/src/ScriptEngine.HostedScript/Library/TypeDescription/BinaryDataQualifiers.cs +++ b/src/ScriptEngine.HostedScript/Library/TypeDescription/BinaryDataQualifiers.cs @@ -20,10 +20,10 @@ public BinaryDataQualifiers(int length = 0, AllowedLength = allowedLength; } - [ContextProperty("Длина", "Length")] + [ContextProperty("Длина")] public int Length { get; } - [ContextProperty("ДопустимаяДлина", "AllowedLength")] + [ContextProperty("ДопустимаяДлина")] public AllowedLengthEnum AllowedLength { get; } public override bool Equals(object obj) diff --git a/src/ScriptEngine.HostedScript/Library/TypeDescription/DateQualifiers.cs b/src/ScriptEngine.HostedScript/Library/TypeDescription/DateQualifiers.cs index 17b37c2cc..73d45db17 100644 --- a/src/ScriptEngine.HostedScript/Library/TypeDescription/DateQualifiers.cs +++ b/src/ScriptEngine.HostedScript/Library/TypeDescription/DateQualifiers.cs @@ -18,7 +18,7 @@ public DateQualifiers(DateFractionsEnum dateFractions = DateFractionsEnum.Date) DateFractions = dateFractions; } - [ContextProperty("ЧастиДаты", "DateFractions")] + [ContextProperty("ЧастиДаты")] public DateFractionsEnum DateFractions { get; } public override bool Equals(object obj) diff --git a/src/ScriptEngine.HostedScript/Library/TypeDescription/NumberQualifiers.cs b/src/ScriptEngine.HostedScript/Library/TypeDescription/NumberQualifiers.cs index c59900c0a..84493f2cd 100644 --- a/src/ScriptEngine.HostedScript/Library/TypeDescription/NumberQualifiers.cs +++ b/src/ScriptEngine.HostedScript/Library/TypeDescription/NumberQualifiers.cs @@ -22,13 +22,13 @@ public NumberQualifiers(int digits = 0, AllowedSign = allowedSign; } - [ContextProperty("ДопустимыйЗнак", "AllowedSign")] + [ContextProperty("ДопустимыйЗнак")] public AllowedSignEnum AllowedSign { get; } - [ContextProperty("Разрядность", "Digits")] + [ContextProperty("Разрядность")] public int Digits { get; } - [ContextProperty("РазрядностьДробнойЧасти", "FractionDigits")] + [ContextProperty("РазрядностьДробнойЧасти")] public int FractionDigits { get; } public override bool Equals(object obj) diff --git a/src/ScriptEngine.HostedScript/Library/TypeDescription/StringQualifiers.cs b/src/ScriptEngine.HostedScript/Library/TypeDescription/StringQualifiers.cs index 080eb9b47..52681837c 100644 --- a/src/ScriptEngine.HostedScript/Library/TypeDescription/StringQualifiers.cs +++ b/src/ScriptEngine.HostedScript/Library/TypeDescription/StringQualifiers.cs @@ -20,10 +20,10 @@ public StringQualifiers(int length = 0, AllowedLength = allowedLength; } - [ContextProperty("Длина", "Length")] + [ContextProperty("Длина")] public int Length { get; } - [ContextProperty("ДопустимаяДлина", "AllowedLength")] + [ContextProperty("ДопустимаяДлина")] public AllowedLengthEnum AllowedLength { get; } public override bool Equals(object obj) diff --git a/src/ScriptEngine.HostedScript/Library/TypeDescription/TypeDescription.cs b/src/ScriptEngine.HostedScript/Library/TypeDescription/TypeDescription.cs index 6c3c6b8c3..24f17b010 100644 --- a/src/ScriptEngine.HostedScript/Library/TypeDescription/TypeDescription.cs +++ b/src/ScriptEngine.HostedScript/Library/TypeDescription/TypeDescription.cs @@ -32,19 +32,19 @@ public TypeDescription(IEnumerable types = null, BinaryDataQualifiers = binaryDataQualifiers ?? new BinaryDataQualifiers(); } - [ContextProperty("КвалификаторыЧисла", "NumberQualifiers")] + [ContextProperty("КвалификаторыЧисла")] public NumberQualifiers NumberQualifiers { get; } - [ContextProperty("КвалификаторыСтроки", "StringQualifiers")] + [ContextProperty("КвалификаторыСтроки")] public StringQualifiers StringQualifiers { get; } - [ContextProperty("КвалификаторыДаты", "DateQualifiers")] + [ContextProperty("КвалификаторыДаты")] public DateQualifiers DateQualifiers { get; } - [ContextProperty("КвалификаторыДвоичныхДанных", "BinaryDataQualifiers")] + [ContextProperty("КвалификаторыДвоичныхДанных")] public BinaryDataQualifiers BinaryDataQualifiers { get; } - [ContextMethod("Типы", "Types")] + [ContextMethod("Типы")] public ArrayImpl Types() { var result = ArrayImpl.Constructor() as ArrayImpl; @@ -57,7 +57,7 @@ public ArrayImpl Types() return result; } - [ContextMethod("СодержитТип", "ContainsType")] + [ContextMethod("СодержитТип")] public bool ContainsType(IValue type) { if (type is TypeTypeValue) @@ -82,7 +82,7 @@ IValueAdjuster GetAdjusterForType(TypeTypeValue type) return null; } - [ContextMethod("ПривестиЗначение", "AdjustValue")] + [ContextMethod("ПривестиЗначение")] public IValue AdjustValue(IValue value = null) { From 904c890dbb58a02f30226fc38ea64d4983c7eb96 Mon Sep 17 00:00:00 2001 From: Sergey Batanov Date: Tue, 8 Aug 2017 13:45:01 +0300 Subject: [PATCH 087/230] =?UTF-8?q?CLR-=D0=BE=D0=B1=D1=8A=D0=B5=D0=BA?= =?UTF-8?q?=D1=82=D1=8B=20=D0=B2=20=D0=BF=D0=B5=D1=80=D0=B2=D0=BE=D0=BC=20?= =?UTF-8?q?=D0=BF=D1=80=D0=B8=D0=B1=D0=BB=D0=B8=D0=B6=D0=B5=D0=BD=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Machine/ComReflectionNameToIdMapper.cs | 45 ++++++++++++++++--- .../Machine/Contexts/COMWrapperContext.cs | 29 ++++++++++-- .../Contexts/ManagedCOMWrapperContext.cs | 8 ++-- 3 files changed, 67 insertions(+), 15 deletions(-) diff --git a/src/ScriptEngine/Machine/ComReflectionNameToIdMapper.cs b/src/ScriptEngine/Machine/ComReflectionNameToIdMapper.cs index c7c5d8051..07f1f0094 100644 --- a/src/ScriptEngine/Machine/ComReflectionNameToIdMapper.cs +++ b/src/ScriptEngine/Machine/ComReflectionNameToIdMapper.cs @@ -22,7 +22,7 @@ class ComReflectionNameToIdMapper readonly List _propertyCache; - readonly List _methodsCache; + readonly List> _methodsCache; public ComReflectionNameToIdMapper(Type type) { @@ -30,7 +30,7 @@ public ComReflectionNameToIdMapper(Type type) _propertyNames = new IndexedNamesCollection(); _methodNames = new IndexedNamesCollection(); _propertyCache = new List(); - _methodsCache = new List(); + _methodsCache = new List>(); } public int FindProperty(string name) @@ -53,20 +53,51 @@ public int FindProperty(string name) return id; } - public int FindMethod(string name) + private System.Reflection.MethodInfo[] GetMethods(string name) + { + return _reflectedType.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase) + .Where((x) => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)).ToArray(); + } + + private static System.Reflection.MethodInfo ChooseBestMatchingMethod(System.Reflection.MethodInfo[] methods, IValue[] callParams) + { + // TODO: анализ типов, анализ параметров по-умолчанию + foreach (var mi in methods) + { + if (mi.GetParameters().Length == callParams.Length) + { + return mi; + } + } + return methods[0]; + } + + private static object InvokeMethod(object instance, System.Reflection.MethodInfo[] methods, IValue[] callParams) + { + var mi = ChooseBestMatchingMethod(methods, callParams); + object[] castedParams = Contexts.COMWrapperContext.MarshalArgumentsStrict(mi, callParams); + return mi.Invoke(instance, castedParams); + } + + public delegate object InvokationDelegate(IValue[] callParams); + + public int FindMethod(object instance, string name) { int id; var hasMethod = _methodNames.TryGetIdOfName(name, out id); if (!hasMethod) { - var methodInfo = _reflectedType.GetMethod(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); - if(methodInfo == null) + var allMethodsInfo = GetMethods(name); + if (allMethodsInfo.Length == 0) throw RuntimeException.MethodNotFoundException(name); + var methodInfo = allMethodsInfo[0]; + Func< IValue[], object > invoker = (IValue[] callParams) => { return InvokeMethod(instance, allMethodsInfo, callParams); }; + id = _methodNames.RegisterName(name); System.Diagnostics.Debug.Assert(_methodsCache.Count == id); - _methodsCache.Add(methodInfo); + _methodsCache.Add(invoker); } return id; @@ -77,7 +108,7 @@ public PropertyInfo GetProperty(int id) return _propertyCache[id]; } - public System.Reflection.MethodInfo GetMethod(int id) + public Func GetMethod(int id) { return _methodsCache[id]; } diff --git a/src/ScriptEngine/Machine/Contexts/COMWrapperContext.cs b/src/ScriptEngine/Machine/Contexts/COMWrapperContext.cs index 79d0840e0..67048dabe 100644 --- a/src/ScriptEngine/Machine/Contexts/COMWrapperContext.cs +++ b/src/ScriptEngine/Machine/Contexts/COMWrapperContext.cs @@ -26,7 +26,23 @@ public COMWrapperContext() public static COMWrapperContext Create(string progId, IValue[] arguments) { - var type = Type.GetTypeFromProgID(progId, true); + var type = Type.GetType(progId, throwOnError: false, ignoreCase: true); + if (type == null) + { + type = Type.GetTypeFromProgID(progId, throwOnError: true); + } + + if (type.IsGenericType) + { + // В первом приближении мы заполняем параметры шаблона классом Object + // TODO: Продумать параметры шаблонного класса + var genericTypes = new List(); + foreach (var ga in type.GetGenericArguments()) + { + genericTypes.Add(typeof(object)); + } + type = type.MakeGenericType(genericTypes.ToArray()); + } object instance = Activator.CreateInstance(type, MarshalArguments(arguments)); @@ -44,7 +60,7 @@ private static COMWrapperContext InitByInstance(Type type, object instance) { return new UnmanagedRCWComContext(instance); } - else if (IsObjectType(type)) + else if (IsObjectType(type) || IsAStruct(type)) { return new ManagedCOMWrapperContext(instance); } @@ -57,6 +73,11 @@ private static bool IsObjectType(Type type) return !type.IsPrimitive && !type.IsValueType; } + private static bool IsAStruct(Type type) + { + return !type.IsPrimitive && type.IsValueType; + } + private static bool TypeIsRuntimeCallableWrapper(Type type) { return type.FullName == "System.__ComObject"; // string, cause it's hidden type @@ -105,7 +126,7 @@ protected static object[] MarshalArgumentsStrict(IValue[] arguments, Type[] argu return marshalledArgs; } - protected static object[] MarshalArgumentsStrict(System.Reflection.MethodInfo method, IValue[] arguments) + public static object[] MarshalArgumentsStrict(System.Reflection.MethodInfo method, IValue[] arguments) { var parameters = method.GetParameters(); @@ -179,7 +200,7 @@ public static IValue CreateIValue(object objParam) { return new SafeArrayWrapper(objParam); } - else if (IsObjectType(type)) + else if (IsObjectType(type) || IsAStruct(type)) { COMWrapperContext ctx; try diff --git a/src/ScriptEngine/Machine/Contexts/ManagedCOMWrapperContext.cs b/src/ScriptEngine/Machine/Contexts/ManagedCOMWrapperContext.cs index c6ad18987..07f88741e 100644 --- a/src/ScriptEngine/Machine/Contexts/ManagedCOMWrapperContext.cs +++ b/src/ScriptEngine/Machine/Contexts/ManagedCOMWrapperContext.cs @@ -134,25 +134,25 @@ public override void SetIndexedValue(IValue index, IValue value) public override int FindMethod(string name) { - return _nameMapper.FindMethod(name); + return _nameMapper.FindMethod(_instance, name); } public override MethodInfo GetMethodInfo(int methodNumber) { var methodInfo = _nameMapper.GetMethod(methodNumber); - return GetReflectableMethod(methodInfo); + return GetReflectableMethod(methodInfo.Method); } public override void CallAsProcedure(int methodNumber, IValue[] arguments) { var method = _nameMapper.GetMethod(methodNumber); - method.Invoke(_instance, MarshalArgumentsStrict(method, arguments)); + method.Invoke(arguments); } public override void CallAsFunction(int methodNumber, IValue[] arguments, out IValue retValue) { var method = _nameMapper.GetMethod(methodNumber); - var result = method.Invoke(_instance, MarshalArgumentsStrict(method, arguments)); + var result = method.Invoke(arguments); retValue = CreateIValue(result); } From f39a606432960966e1a55d3b4dec0c52bf616118 Mon Sep 17 00:00:00 2001 From: Sergey Batanov Date: Tue, 8 Aug 2017 13:45:17 +0300 Subject: [PATCH 088/230] =?UTF-8?q?=D0=A2=D0=B5=D1=81=D1=82=20=D0=BD=D0=B0?= =?UTF-8?q?=20CLR-=D0=BE=D0=B1=D1=8A=D0=B5=D0=BA=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/managed-com.os | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/tests/managed-com.os b/tests/managed-com.os index cb3f24989..c3463c35c 100644 --- a/tests/managed-com.os +++ b/tests/managed-com.os @@ -16,6 +16,10 @@ ВсеТесты.Добавить("ТестДолжен_ПроверитьВызовСОпциональнымиПараметрами"); КонецЕсли; + ВсеТесты.Добавить("ТестДолжен_ПроверитьСозданиеClrОбъекта"); + ВсеТесты.Добавить("ТестДолжен_ПроверитьСозданиеClrКоллекции"); + ВсеТесты.Добавить("ТестДолжен_ПроверитьСозданиеClrКоллекцииШаблона"); + Возврат ВсеТесты; КонецФункции @@ -45,3 +49,41 @@ КонецПопытки; КонецПроцедуры + +Процедура ТестДолжен_ПроверитьСозданиеClrОбъекта() Экспорт + + РоднойОбъект = Новый COMОбъект("System.Random"); + РоднойОбъект.Next(); + РоднойОбъект.Next(10); + РоднойОбъект.Next(10, 20); + РоднойОбъект.NextDouble(); + +КонецПроцедуры + +Процедура ТестДолжен_ПроверитьСозданиеClrКоллекции() Экспорт + + РоднаяКоллекцияНеШаблон = Новый COMОбъект("System.Collections.ArrayList"); + РоднаяКоллекцияНеШаблон.Add(1); + РоднаяКоллекцияНеШаблон.Add("string"); + РоднаяКоллекцияНеШаблон.Add('20170808'); + + юТест.ПроверитьРавенство(РоднаяКоллекцияНеШаблон.Count, 3); + юТест.ПроверитьРавенство(РоднаяКоллекцияНеШаблон[0], 1); + юТест.ПроверитьРавенство(РоднаяКоллекцияНеШаблон[1], "string"); + юТест.ПроверитьРавенство(РоднаяКоллекцияНеШаблон[2], '20170808'); + +КонецПроцедуры + +Процедура ТестДолжен_ПроверитьСозданиеClrКоллекцииШаблона() Экспорт + + РоднаяКоллекцияШаблон = Новый COMОбъект("System.Collections.Generic.List`1"); + РоднаяКоллекцияШаблон.Add(1); + РоднаяКоллекцияШаблон.Add("string"); + РоднаяКоллекцияШаблон.Add('20170808'); + + юТест.ПроверитьРавенство(РоднаяКоллекцияШаблон.Count, 3); + юТест.ПроверитьРавенство(РоднаяКоллекцияШаблон[0], 1); + юТест.ПроверитьРавенство(РоднаяКоллекцияШаблон[1], "string"); + юТест.ПроверитьРавенство(РоднаяКоллекцияШаблон[2], '20170808'); + +КонецПроцедуры From c3a271aa417c79feaaf3705ee86d3be2025bf31a Mon Sep 17 00:00:00 2001 From: Dmitriy Kartashev Date: Tue, 8 Aug 2017 14:31:19 +0300 Subject: [PATCH 089/230] =?UTF-8?q?=D0=9F=D0=BE=20=D1=80=D0=B5=D0=B7=D1=83?= =?UTF-8?q?=D0=BB=D1=8C=D1=82=D0=B0=D1=82=D0=B0=D0=BC=20=D1=80=D0=B5=D0=B2?= =?UTF-8?q?=D1=8C=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/file-object.os | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/file-object.os b/tests/file-object.os index 8b25254a0..d633be3bc 100644 --- a/tests/file-object.os +++ b/tests/file-object.os @@ -258,7 +258,7 @@ ВремяИзменения = Файл.ПолучитьВремяИзменения(); юТест.ПроверитьРавенствоДатСТочностью2Секунды(ТекущаяДата, ВремяИзменения); - юТест.ПроверитьНеРавенство(ВремяСоздания, ВремяИзменения); + юТест.ПроверитьМеньше(ВремяСоздания, ВремяИзменения); УдалитьФайлы(ВремФайл); КонецПроцедуры From 8abebf81c9a5218e0d644b6f481e679164b9e9dd Mon Sep 17 00:00:00 2001 From: Dmitriy Kartashev Date: Tue, 8 Aug 2017 12:54:13 +0300 Subject: [PATCH 090/230] =?UTF-8?q?fixes=20#479=20=D0=9D=D0=B5=20=D1=85?= =?UTF-8?q?=D0=B2=D0=B0=D1=82=D0=B0=D0=BB=D0=BE=20=D0=B0=D0=BD=D0=B3=D0=BB?= =?UTF-8?q?=D0=B8=D0=B9=D1=81=D0=BA=D0=B8=D1=85=20=D1=81=D0=B8=D0=BD=D0=BE?= =?UTF-8?q?=D0=BD=D0=B8=D0=BC=D0=BE=D0=B2=20=D0=B2=20=D1=80=D0=B0=D0=B7?= =?UTF-8?q?=D0=BD=D1=8B=D1=85=20=D0=BC=D0=B5=D1=81=D1=82=D0=B0=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Library/SymbolsContext.cs | 12 ++++++------ .../TypeDescription/BinaryDataQualifiers.cs | 4 ++-- .../Library/TypeDescription/DateQualifiers.cs | 2 +- .../Library/TypeDescription/NumberQualifiers.cs | 6 +++--- .../Library/TypeDescription/StringQualifiers.cs | 4 ++-- .../Library/TypeDescription/TypeDescription.cs | 14 +++++++------- 6 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/ScriptEngine.HostedScript/Library/SymbolsContext.cs b/src/ScriptEngine.HostedScript/Library/SymbolsContext.cs index 936fa48d9..55cd80ef6 100644 --- a/src/ScriptEngine.HostedScript/Library/SymbolsContext.cs +++ b/src/ScriptEngine.HostedScript/Library/SymbolsContext.cs @@ -16,7 +16,7 @@ public sealed class SymbolsContext : AutoContext /// Символ перевода строки. /// /// Символ перевода строки. - [ContextProperty("ПС")] + [ContextProperty("ПС", "LF")] public string LF { get @@ -29,7 +29,7 @@ public string LF /// Символ возврата каретки. /// /// Символ возврата каретки. - [ContextProperty("ВК")] + [ContextProperty("ВК", "CR")] public string CR { get @@ -42,7 +42,7 @@ public string CR /// Символ вертикальной табуляции. /// /// Символ вертикальной табуляции. - [ContextProperty("ВТаб")] + [ContextProperty("ВТаб", "VTab")] public string VTab { get @@ -55,7 +55,7 @@ public string VTab /// Символ табуляции. /// /// Символ горизонтальной табуляции. - [ContextProperty("Таб")] + [ContextProperty("Таб", "Tab")] public string Tab { get @@ -68,7 +68,7 @@ public string Tab /// Символ промотки. /// /// Символ промотки. - [ContextProperty("ПФ")] + [ContextProperty("ПФ", "FF")] public string FF { get @@ -81,7 +81,7 @@ public string FF /// Символ неразрывного пробела. /// /// Символ неразрывного пробела. - [ContextProperty("НПП")] + [ContextProperty("НПП", "Nbsp")] public string Nbsp { get diff --git a/src/ScriptEngine.HostedScript/Library/TypeDescription/BinaryDataQualifiers.cs b/src/ScriptEngine.HostedScript/Library/TypeDescription/BinaryDataQualifiers.cs index 43f47c113..cb3b09964 100644 --- a/src/ScriptEngine.HostedScript/Library/TypeDescription/BinaryDataQualifiers.cs +++ b/src/ScriptEngine.HostedScript/Library/TypeDescription/BinaryDataQualifiers.cs @@ -20,10 +20,10 @@ public BinaryDataQualifiers(int length = 0, AllowedLength = allowedLength; } - [ContextProperty("Длина")] + [ContextProperty("Длина", "Length")] public int Length { get; } - [ContextProperty("ДопустимаяДлина")] + [ContextProperty("ДопустимаяДлина", "AllowedLength")] public AllowedLengthEnum AllowedLength { get; } public override bool Equals(object obj) diff --git a/src/ScriptEngine.HostedScript/Library/TypeDescription/DateQualifiers.cs b/src/ScriptEngine.HostedScript/Library/TypeDescription/DateQualifiers.cs index 73d45db17..17b37c2cc 100644 --- a/src/ScriptEngine.HostedScript/Library/TypeDescription/DateQualifiers.cs +++ b/src/ScriptEngine.HostedScript/Library/TypeDescription/DateQualifiers.cs @@ -18,7 +18,7 @@ public DateQualifiers(DateFractionsEnum dateFractions = DateFractionsEnum.Date) DateFractions = dateFractions; } - [ContextProperty("ЧастиДаты")] + [ContextProperty("ЧастиДаты", "DateFractions")] public DateFractionsEnum DateFractions { get; } public override bool Equals(object obj) diff --git a/src/ScriptEngine.HostedScript/Library/TypeDescription/NumberQualifiers.cs b/src/ScriptEngine.HostedScript/Library/TypeDescription/NumberQualifiers.cs index 84493f2cd..c59900c0a 100644 --- a/src/ScriptEngine.HostedScript/Library/TypeDescription/NumberQualifiers.cs +++ b/src/ScriptEngine.HostedScript/Library/TypeDescription/NumberQualifiers.cs @@ -22,13 +22,13 @@ public NumberQualifiers(int digits = 0, AllowedSign = allowedSign; } - [ContextProperty("ДопустимыйЗнак")] + [ContextProperty("ДопустимыйЗнак", "AllowedSign")] public AllowedSignEnum AllowedSign { get; } - [ContextProperty("Разрядность")] + [ContextProperty("Разрядность", "Digits")] public int Digits { get; } - [ContextProperty("РазрядностьДробнойЧасти")] + [ContextProperty("РазрядностьДробнойЧасти", "FractionDigits")] public int FractionDigits { get; } public override bool Equals(object obj) diff --git a/src/ScriptEngine.HostedScript/Library/TypeDescription/StringQualifiers.cs b/src/ScriptEngine.HostedScript/Library/TypeDescription/StringQualifiers.cs index 52681837c..080eb9b47 100644 --- a/src/ScriptEngine.HostedScript/Library/TypeDescription/StringQualifiers.cs +++ b/src/ScriptEngine.HostedScript/Library/TypeDescription/StringQualifiers.cs @@ -20,10 +20,10 @@ public StringQualifiers(int length = 0, AllowedLength = allowedLength; } - [ContextProperty("Длина")] + [ContextProperty("Длина", "Length")] public int Length { get; } - [ContextProperty("ДопустимаяДлина")] + [ContextProperty("ДопустимаяДлина", "AllowedLength")] public AllowedLengthEnum AllowedLength { get; } public override bool Equals(object obj) diff --git a/src/ScriptEngine.HostedScript/Library/TypeDescription/TypeDescription.cs b/src/ScriptEngine.HostedScript/Library/TypeDescription/TypeDescription.cs index 24f17b010..6c3c6b8c3 100644 --- a/src/ScriptEngine.HostedScript/Library/TypeDescription/TypeDescription.cs +++ b/src/ScriptEngine.HostedScript/Library/TypeDescription/TypeDescription.cs @@ -32,19 +32,19 @@ public TypeDescription(IEnumerable types = null, BinaryDataQualifiers = binaryDataQualifiers ?? new BinaryDataQualifiers(); } - [ContextProperty("КвалификаторыЧисла")] + [ContextProperty("КвалификаторыЧисла", "NumberQualifiers")] public NumberQualifiers NumberQualifiers { get; } - [ContextProperty("КвалификаторыСтроки")] + [ContextProperty("КвалификаторыСтроки", "StringQualifiers")] public StringQualifiers StringQualifiers { get; } - [ContextProperty("КвалификаторыДаты")] + [ContextProperty("КвалификаторыДаты", "DateQualifiers")] public DateQualifiers DateQualifiers { get; } - [ContextProperty("КвалификаторыДвоичныхДанных")] + [ContextProperty("КвалификаторыДвоичныхДанных", "BinaryDataQualifiers")] public BinaryDataQualifiers BinaryDataQualifiers { get; } - [ContextMethod("Типы")] + [ContextMethod("Типы", "Types")] public ArrayImpl Types() { var result = ArrayImpl.Constructor() as ArrayImpl; @@ -57,7 +57,7 @@ public ArrayImpl Types() return result; } - [ContextMethod("СодержитТип")] + [ContextMethod("СодержитТип", "ContainsType")] public bool ContainsType(IValue type) { if (type is TypeTypeValue) @@ -82,7 +82,7 @@ IValueAdjuster GetAdjusterForType(TypeTypeValue type) return null; } - [ContextMethod("ПривестиЗначение")] + [ContextMethod("ПривестиЗначение", "AdjustValue")] public IValue AdjustValue(IValue value = null) { From 206994d1de7154dd6f5f48fb8109de84261e6532 Mon Sep 17 00:00:00 2001 From: Dmitriy Kartashev Date: Tue, 8 Aug 2017 13:34:39 +0300 Subject: [PATCH 091/230] =?UTF-8?q?#479=20=D0=A2=D0=B5=D1=81=D1=82=20?= =?UTF-8?q?=D0=B4=D0=BB=D1=8F=20=D0=BF=D0=BE=D0=B4=D1=82=D0=B2=D0=B5=D1=80?= =?UTF-8?q?=D0=B6=D0=B4=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=B1=D0=B0=D0=B3=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/symbols.os | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 tests/symbols.os diff --git a/tests/symbols.os b/tests/symbols.os new file mode 100644 index 000000000..fe034f1de --- /dev/null +++ b/tests/symbols.os @@ -0,0 +1,47 @@ +Перем юТест; + +Функция ПолучитьСписокТестов(ЮнитТестирование) Экспорт + + юТест = ЮнитТестирование; + + ВсеТесты = Новый Массив; + ВсеТесты.Добавить("ТестДолжен_ПроверитьЧтоСимволыПСНеПадает"); + ВсеТесты.Добавить("ТестДолжен_ПроверитьЧтоСимволыLFНеПадает"); + ВсеТесты.Добавить("ТестДолжен_ПроверитьЧтоCharsLFНеПадает"); + ВсеТесты.Добавить("ТестДолжен_ПроверитьЧтоCharsПСНеПадает"); + + Возврат ВсеТесты; + +КонецФункции + +Процедура ТестДолжен_ПроверитьЧтоСимволыLFНеПадает() Экспорт + Попытка + Строка = Символы.LF; + Исключение + юТест.ТестПровален("Не работает Символы.LF"); + КонецПопытки; +КонецПроцедуры + +Процедура ТестДолжен_ПроверитьЧтоСимволыПСНеПадает() Экспорт + Попытка + Строка = Символы.ПС; + Исключение + юТест.ТестПровален("Не работает Символы.ПС"); + КонецПопытки; +КонецПроцедуры + +Процедура ТестДолжен_ПроверитьЧтоCharsLFНеПадает() Экспорт + Попытка + Строка = Chars.LF; + Исключение + юТест.ТестПровален("Не работает Chars.LF"); + КонецПопытки; +КонецПроцедуры + +Процедура ТестДолжен_ПроверитьЧтоCharsПСНеПадает() Экспорт + Попытка + Строка = Chars.ПС; + Исключение + юТест.ТестПровален("Не работает Chars.ПС"); + КонецПопытки; +КонецПроцедуры \ No newline at end of file From 016fff2477b16941b2934a21ff5853851d19a566 Mon Sep 17 00:00:00 2001 From: Sergey Batanov Date: Wed, 9 Aug 2017 10:05:37 +0300 Subject: [PATCH 092/230] =?UTF-8?q?=D0=9F=D0=BE=D0=B4=D0=B4=D0=B5=D1=80?= =?UTF-8?q?=D0=B6=D0=BA=D0=B0=20=D1=82=D0=B8=D0=BF=D0=BE=D0=B2=20.Net-?= =?UTF-8?q?=D0=BE=D0=B1=D1=8A=D0=B5=D0=BA=D1=82=D0=BE=D0=B2.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Поддержка .Net-объектов в функциях Тип и ТипЗнч. --- .../Machine/Contexts/COMWrapperContext.cs | 16 ++++++++++++++++ .../Machine/Contexts/ManagedCOMWrapperContext.cs | 2 ++ src/ScriptEngine/Machine/TypeManager.cs | 16 ++++++++-------- tests/managed-com.os | 15 +++++++++++++++ 4 files changed, 41 insertions(+), 8 deletions(-) diff --git a/src/ScriptEngine/Machine/Contexts/COMWrapperContext.cs b/src/ScriptEngine/Machine/Contexts/COMWrapperContext.cs index 67048dabe..bfc718bd1 100644 --- a/src/ScriptEngine/Machine/Contexts/COMWrapperContext.cs +++ b/src/ScriptEngine/Machine/Contexts/COMWrapperContext.cs @@ -23,6 +23,20 @@ public COMWrapperContext() { } + + public static void RegisterClrTypeSupport(Type clrType, string typeName) + { + if (!TypeManager.IsKnownType(typeName)) + { + TypeManager.RegisterType(typeName, clrType); + } + } + + public static void RegisterClrTypeSupport(Type clrType) + { + // clrType.FullName выдаёт значение вместе со сборкой, несмотря на описание + RegisterClrTypeSupport(clrType, string.Format("{0}.{1}", clrType.Namespace, clrType.Name)); + } public static COMWrapperContext Create(string progId, IValue[] arguments) { @@ -44,6 +58,8 @@ public static COMWrapperContext Create(string progId, IValue[] arguments) type = type.MakeGenericType(genericTypes.ToArray()); } + RegisterClrTypeSupport(type, progId); + object instance = Activator.CreateInstance(type, MarshalArguments(arguments)); return InitByInstance(type, instance); diff --git a/src/ScriptEngine/Machine/Contexts/ManagedCOMWrapperContext.cs b/src/ScriptEngine/Machine/Contexts/ManagedCOMWrapperContext.cs index 07f88741e..bb466ec96 100644 --- a/src/ScriptEngine/Machine/Contexts/ManagedCOMWrapperContext.cs +++ b/src/ScriptEngine/Machine/Contexts/ManagedCOMWrapperContext.cs @@ -26,6 +26,8 @@ public ManagedCOMWrapperContext(object instance) _instanceType = instance.GetType(); _instance = instance; _nameMapper = new ComReflectionNameToIdMapper(_instanceType); + RegisterClrTypeSupport(_instanceType); + DefineType(TypeManager.GetTypeByFrameworkType(_instanceType)); } public override bool IsIndexed diff --git a/src/ScriptEngine/Machine/TypeManager.cs b/src/ScriptEngine/Machine/TypeManager.cs index b9a05bb5a..b4b635b82 100644 --- a/src/ScriptEngine/Machine/TypeManager.cs +++ b/src/ScriptEngine/Machine/TypeManager.cs @@ -94,17 +94,17 @@ public Type GetImplementingClass(int typeId) public TypeDescriptor GetTypeByName(string name) { - int ktIndex; - try + if (_knownTypesIndexes.ContainsKey(name)) { - ktIndex = _knownTypesIndexes[name]; + return _knownTypes[_knownTypesIndexes[name]].Descriptor; } - catch (KeyNotFoundException) + var clrType = Type.GetType(name, throwOnError: false, ignoreCase: true); + if (clrType != null) { - throw new RuntimeException(String.Format("Тип не зарегистрирован ({0})", name)); - } - - return _knownTypes[ktIndex].Descriptor; + var td = RegisterType(name, typeof(COMWrapperContext)); + return td; + } + throw new RuntimeException(String.Format("Тип не зарегистрирован ({0})", name)); } public TypeDescriptor GetTypeById(int id) diff --git a/tests/managed-com.os b/tests/managed-com.os index c3463c35c..a96b9b27a 100644 --- a/tests/managed-com.os +++ b/tests/managed-com.os @@ -19,6 +19,7 @@ ВсеТесты.Добавить("ТестДолжен_ПроверитьСозданиеClrОбъекта"); ВсеТесты.Добавить("ТестДолжен_ПроверитьСозданиеClrКоллекции"); ВсеТесты.Добавить("ТестДолжен_ПроверитьСозданиеClrКоллекцииШаблона"); + ВсеТесты.Добавить("ТестДолжен_ПроверитьТипыClrОбъектов"); Возврат ВсеТесты; КонецФункции @@ -87,3 +88,17 @@ юТест.ПроверитьРавенство(РоднаяКоллекцияШаблон[2], '20170808'); КонецПроцедуры + +Процедура ТестДолжен_ПроверитьТипыClrОбъектов() Экспорт + + РодноеСоответствие = Новый ComОбъект("System.Collections.Generic.Dictionary`2"); + РодноеСоответствие.Add("str", 123); + + юТест.ПроверитьРавенство (ТипЗнч(РодноеСоответствие), Тип("System.Collections.Generic.Dictionary`2"), "Равенство одинаковых CLR-типов"); + юТест.ПроверитьНеРавенство(ТипЗнч(РодноеСоответствие), Тип("System.Random"), "Неравенство разных CLR-типов"); + + Для Каждого мКлючЗначение Из РодноеСоответствие Цикл + юТест.ПроверитьРавенство(ТипЗнч(мКлючЗначение), Тип("System.Collections.Generic.KeyValuePair`2"), "Автоматическая регистрация незаявленных CLR-типов"); + КонецЦикла; + +КонецПроцедуры From 7dfd3b1f12c20bc42342363f040255d64e29a2b9 Mon Sep 17 00:00:00 2001 From: Faithfinder Date: Wed, 9 Aug 2017 12:34:32 +0300 Subject: [PATCH 093/230] =?UTF-8?q?=D0=9F=D1=80=D0=B5=D0=B4=D0=BF=D0=BE?= =?UTF-8?q?=D0=BB=D0=BE=D0=B6=D0=B8=D1=82=D0=B5=D0=BB=D1=8C=D0=BD=D0=BE?= =?UTF-8?q?=D0=B5=20=D1=80=D0=B5=D1=88=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BF?= =?UTF-8?q?=D1=80=D0=B8=D1=87=D0=B8=D0=BD=D1=8B=20#479?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine/Machine/Contexts/ContextMethodMapper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ScriptEngine/Machine/Contexts/ContextMethodMapper.cs b/src/ScriptEngine/Machine/Contexts/ContextMethodMapper.cs index 764570339..43773604e 100644 --- a/src/ScriptEngine/Machine/Contexts/ContextMethodMapper.cs +++ b/src/ScriptEngine/Machine/Contexts/ContextMethodMapper.cs @@ -148,7 +148,7 @@ private void MapType(Type type) scriptMethInfo.IsFunction = isFunc; scriptMethInfo.Name = item.Binding.GetName().ToLower(); scriptMethInfo.Alias = string.IsNullOrEmpty(item.Binding.GetAlias()) ? - item.Method.Name.ToLower() + scriptMethInfo.Name :item.Binding.GetAlias().ToLower(); scriptMethInfo.Params = paramDefs; From 145b59244abc971ec878acfee45c2b6f0f138c62 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Wed, 9 Aug 2017 22:28:27 +0300 Subject: [PATCH 094/230] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B4=D0=B5?= =?UTF-8?q?=D0=BB=D0=BA=D0=B0=20=D1=81=D1=82=D0=BE=D0=BF-=D0=BC=D0=B5?= =?UTF-8?q?=D0=BD=D0=B5=D0=B4=D0=B6=D0=B5=D1=80=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine/Machine/MachineInstance.cs | 10 +++---- .../Machine/MachineStopManager.cs | 26 ++++++++++++++----- .../DebugServer/OscriptDebugController.cs | 2 +- 3 files changed, 24 insertions(+), 14 deletions(-) diff --git a/src/ScriptEngine/Machine/MachineInstance.cs b/src/ScriptEngine/Machine/MachineInstance.cs index a02e6cb6d..9d84458e3 100644 --- a/src/ScriptEngine/Machine/MachineInstance.cs +++ b/src/ScriptEngine/Machine/MachineInstance.cs @@ -132,19 +132,17 @@ public bool SetBreakpoint(string source, int line, out int id) if (_stopManager == null) throw new InvalidOperationException("Machine is not in debug mode"); - throw new NotImplementedException(); - //id = _stopManager.AddSourceLineStop(source, line); + id = _stopManager.SetBreakpoint(source, line); return true; } - public void StopAtNextLine() + public void StepOver() { if (_stopManager == null) throw new InvalidOperationException("Machine is not in debug mode"); - throw new NotImplementedException(); - //_stopManager.AddNextLineStop(_currentFrame); + //_stopManager.StepOver(_currentFrame); } public void StepIn() @@ -1487,7 +1485,7 @@ private void LineNum(int arg) CodeStat_LineReached(); } - if(MachineStopped != null && _stopManager != null /*&& _stopManager.ShouldStopAtThisLine(_module.ModuleInfo.Origin, _currentFrame)*/) + if(MachineStopped != null && _stopManager != null && _stopManager.ShouldStopAtThisLine(_module.ModuleInfo.Origin, _currentFrame)) { CreateFullCallstack(); MachineStopped?.Invoke(this, new MachineStoppedEventArgs(MachineStopReason.Breakpoint)); diff --git a/src/ScriptEngine/Machine/MachineStopManager.cs b/src/ScriptEngine/Machine/MachineStopManager.cs index 3d3b921cd..974d8687a 100644 --- a/src/ScriptEngine/Machine/MachineStopManager.cs +++ b/src/ScriptEngine/Machine/MachineStopManager.cs @@ -19,7 +19,7 @@ internal enum DebugState internal class Breakpoint { public string Module; - public ExecutionFrame HitFrame; + //public ExecutionFrame HitFrame; public int LineNumber; public Breakpoint(int id) @@ -33,18 +33,23 @@ public Breakpoint(int id) internal class MachineStopManager { - private DebugState _currentState; - private List _breakpoints; + private DebugState _currentState = DebugState.Running; + private List _breakpoints = new List(); + + private ExecutionFrame _stopFrame; private int _bpIdsGenerator; public int SetBreakpoint(string module, int line) { - return (new Breakpoint(_bpIdsGenerator++) + var bp = new Breakpoint(_bpIdsGenerator++) { LineNumber = line, Module = module - }).BreakpointId; + }; + + _breakpoints.Add(bp); + return bp.BreakpointId; } public void RemoveBreakpoint(int bpId) @@ -54,12 +59,12 @@ public void RemoveBreakpoint(int bpId) _breakpoints.RemoveAt(index); } - public bool LineHit(string module, ExecutionFrame currentFrame) + public bool ShouldStopAtThisLine(string module, ExecutionFrame currentFrame) { switch (_currentState) { case DebugState.Running: - throw new NotImplementedException(); + return HitBreakpointOnLine(module, currentFrame); case DebugState.SteppingIn: throw new NotImplementedException(); case DebugState.SteppingOut: @@ -70,5 +75,12 @@ public bool LineHit(string module, ExecutionFrame currentFrame) throw new NotImplementedException(); } + + private bool HitBreakpointOnLine(string module, ExecutionFrame currentFrame) + { + var found = _breakpoints.Find(x => x.Module.Equals(module) && x.LineNumber == currentFrame.LineNumber); + return found != null; + } + } } diff --git a/src/oscript/DebugServer/OscriptDebugController.cs b/src/oscript/DebugServer/OscriptDebugController.cs index 250c11462..1ad0d3268 100644 --- a/src/oscript/DebugServer/OscriptDebugController.cs +++ b/src/oscript/DebugServer/OscriptDebugController.cs @@ -186,7 +186,7 @@ public Variable Evaluate(int contextFrame, string expression) public void Next() { - _machine.StopAtNextLine(); + _machine.StepOver(); _debugCommandEvent.Set(); } From 4b68379ca691c26445f1b5506763264430ca5eed Mon Sep 17 00:00:00 2001 From: Sergey Batanov Date: Wed, 9 Aug 2017 13:54:10 +0300 Subject: [PATCH 095/230] =?UTF-8?q?Fix=20#501:=20=D0=A1=D0=BE=D0=B7=D0=B4?= =?UTF-8?q?=D0=B0=D0=BD=D0=B8=D0=B5=20=D1=81=D1=82=D1=80=D1=83=D0=BA=D1=82?= =?UTF-8?q?=D1=83=D1=80=D1=8B=20=D0=BF=D0=BE=20=D1=81=D1=82=D1=80=D1=83?= =?UTF-8?q?=D0=BA=D1=82=D1=83=D1=80=D0=B5.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Добавлен конструктор, создающий структуру по данным другой структуры. --- .../Library/StructureImpl.cs | 12 ++++++++++++ tests/fixed-structure.os | 13 +++++++++++++ 2 files changed, 25 insertions(+) diff --git a/src/ScriptEngine.HostedScript/Library/StructureImpl.cs b/src/ScriptEngine.HostedScript/Library/StructureImpl.cs index aa676dbf7..04aafb89b 100644 --- a/src/ScriptEngine.HostedScript/Library/StructureImpl.cs +++ b/src/ScriptEngine.HostedScript/Library/StructureImpl.cs @@ -40,6 +40,14 @@ public StructureImpl(string strProperties, params IValue[] values) } } + public StructureImpl(IEnumerable structure) + { + foreach (KeyAndValueImpl keyValue in structure) + { + Insert(keyValue.Key.AsString(), keyValue.Value); + } + } + [ContextMethod("Вставить")] public void Insert(string name, IValue val = null) { @@ -206,6 +214,10 @@ public static IRuntimeContextInstance Constructor() [ScriptConstructor(Name="На основании свойств и значений")] public static IRuntimeContextInstance Constructor(IValue strProperties, IValue[] args) { + if (strProperties is IEnumerable) + { + return new StructureImpl(strProperties as IEnumerable); + } return new StructureImpl(strProperties.AsString(), args); } diff --git a/tests/fixed-structure.os b/tests/fixed-structure.os index 4c8207a03..9350438ad 100644 --- a/tests/fixed-structure.os +++ b/tests/fixed-structure.os @@ -21,6 +21,7 @@ ВсеТесты.Добавить("ТестДолжен_ПроверитьЧтоНельзяПоменятьЗначениеПриОбращенииЧерезКлюч"); ВсеТесты.Добавить("ТестДолжен_ПроверитьМетодСвойство"); ВсеТесты.Добавить("ТестДолжен_ПроверитьОтсутствиеМетодаВставить"); + ВсеТесты.Добавить("ТестДолжен_СоздатьСтруктуруПоФиксированнойСтруктуре"); Возврат ВсеТесты; КонецФункции @@ -108,3 +109,15 @@ ВызватьИсключение "Ожидали, что у класса ""ФиксированнаяСтруктура"" нельзя менять значение через обращение по ключу, а получили, что меняется"; КонецПроцедуры + +Процедура ТестДолжен_СоздатьСтруктуруПоФиксированнойСтруктуре() Экспорт + + ФиксированнаяСтруктура = Новый ФиксированнаяСтруктура("Ключ1, Ключ2", "Значение1", "Значение2"); + Структура = Новый Структура(ФиксированнаяСтруктура); + + Ожидаем.Что(ТипЗнч(Структура)).Равно(Тип("Структура")); + Ожидаем.Что(Структура.Количество(), "количество элементов исходной и полученной структуры совпадут").Равно(ФиксированнаяСтруктура.Количество()); + Ожидаем.Что(Структура.Ключ1, "значения элементов совпадут").Равно(ФиксированнаяСтруктура.Ключ1); + Ожидаем.Что(Структура.Ключ2, "значения элементов совпадут").Равно(ФиксированнаяСтруктура.Ключ2); + +КонецПроцедуры From 54ec3ab2d70af302924eec761a4e355129f19083 Mon Sep 17 00:00:00 2001 From: Sergey Batanov Date: Fri, 11 Aug 2017 10:03:16 +0300 Subject: [PATCH 096/230] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=20RawValue?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine.HostedScript/Library/StructureImpl.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/ScriptEngine.HostedScript/Library/StructureImpl.cs b/src/ScriptEngine.HostedScript/Library/StructureImpl.cs index 04aafb89b..0f5b0cdf2 100644 --- a/src/ScriptEngine.HostedScript/Library/StructureImpl.cs +++ b/src/ScriptEngine.HostedScript/Library/StructureImpl.cs @@ -214,11 +214,12 @@ public static IRuntimeContextInstance Constructor() [ScriptConstructor(Name="На основании свойств и значений")] public static IRuntimeContextInstance Constructor(IValue strProperties, IValue[] args) { - if (strProperties is IEnumerable) + var rawArgument = strProperties.GetRawValue(); + if (rawArgument is IEnumerable) { - return new StructureImpl(strProperties as IEnumerable); + return new StructureImpl(rawArgument as IEnumerable); } - return new StructureImpl(strProperties.AsString(), args); + return new StructureImpl(rawArgument.AsString(), args); } } From 1388cab7019796fe677e420a36e7cc0da9a3d0d5 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sun, 13 Aug 2017 22:11:41 +0300 Subject: [PATCH 097/230] =?UTF-8?q?=D0=92=D1=8B=D0=BD=D0=B5=D1=81=20=D1=83?= =?UTF-8?q?=D0=BF=D1=80=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D1=82?= =?UTF-8?q?=D0=BE=D1=87=D0=BA=D0=B0=D0=BC=D0=B8=20=D0=BE=D1=81=D1=82=D0=B0?= =?UTF-8?q?=D0=BD=D0=BE=D0=B2=D0=B0=20=D0=BE=D1=82=D0=B4=D0=B5=D0=BB=D1=8C?= =?UTF-8?q?=D0=BD=D0=BE=20=D0=BE=D1=82=20=D1=81=D1=82=D0=BE=D0=BF-=D0=BC?= =?UTF-8?q?=D0=B5=D0=BD=D0=B5=D0=B4=D0=B6=D0=B5=D1=80=D0=B0.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine/Machine/Breakpoints.cs | 52 +++++++++++++++++++ .../Machine/MachineStopManager.cs | 43 +++------------ src/ScriptEngine/ScriptEngine.csproj | 1 + 3 files changed, 59 insertions(+), 37 deletions(-) create mode 100644 src/ScriptEngine/Machine/Breakpoints.cs diff --git a/src/ScriptEngine/Machine/Breakpoints.cs b/src/ScriptEngine/Machine/Breakpoints.cs new file mode 100644 index 000000000..be2cc38c1 --- /dev/null +++ b/src/ScriptEngine/Machine/Breakpoints.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace ScriptEngine.Machine +{ + internal class Breakpoint + { + public string Module; + //public ExecutionFrame HitFrame; + public int LineNumber; + + public Breakpoint(int id) + { + BreakpointId = id; + } + + public int BreakpointId { get; } + } + + class Breakpoints + { + private readonly List _breakpoints = new List(); + private int idsGenerator = 0; + + public int SetBreakpoint(string module, int line) + { + var bp = new Breakpoint(idsGenerator++) + { + LineNumber = line, + Module = module + }; + + _breakpoints.Add(bp); + return bp.BreakpointId; + } + + public void RemoveBreakpoint(int bpId) + { + int index = _breakpoints.FindIndex(x => x.BreakpointId == bpId); + if (index >= 0) + _breakpoints.RemoveAt(index); + } + + public bool Find(string module, int line) + { + var found = _breakpoints.Find(x => x.Module.Equals(module) && x.LineNumber == line); + return found != null; + } + } +} diff --git a/src/ScriptEngine/Machine/MachineStopManager.cs b/src/ScriptEngine/Machine/MachineStopManager.cs index 974d8687a..588f383aa 100644 --- a/src/ScriptEngine/Machine/MachineStopManager.cs +++ b/src/ScriptEngine/Machine/MachineStopManager.cs @@ -16,49 +16,19 @@ internal enum DebugState SteppingOut } - internal class Breakpoint - { - public string Module; - //public ExecutionFrame HitFrame; - public int LineNumber; - - public Breakpoint(int id) - { - BreakpointId = id; - } - - public int BreakpointId { get; } - } - + internal class MachineStopManager { private DebugState _currentState = DebugState.Running; - private List _breakpoints = new List(); - + private Breakpoints _breakpoints = new Breakpoints(); private ExecutionFrame _stopFrame; - - private int _bpIdsGenerator; - + public int SetBreakpoint(string module, int line) { - var bp = new Breakpoint(_bpIdsGenerator++) - { - LineNumber = line, - Module = module - }; - - _breakpoints.Add(bp); - return bp.BreakpointId; - } - - public void RemoveBreakpoint(int bpId) - { - int index = _breakpoints.FindIndex(x => x.BreakpointId == bpId); - if(index >= 0) - _breakpoints.RemoveAt(index); + return _breakpoints.SetBreakpoint(module, line); } - + public bool ShouldStopAtThisLine(string module, ExecutionFrame currentFrame) { switch (_currentState) @@ -78,8 +48,7 @@ public bool ShouldStopAtThisLine(string module, ExecutionFrame currentFrame) private bool HitBreakpointOnLine(string module, ExecutionFrame currentFrame) { - var found = _breakpoints.Find(x => x.Module.Equals(module) && x.LineNumber == currentFrame.LineNumber); - return found != null; + return _breakpoints.Find(module, currentFrame.LineNumber); } } diff --git a/src/ScriptEngine/ScriptEngine.csproj b/src/ScriptEngine/ScriptEngine.csproj index a1b2a80cd..c845978d5 100644 --- a/src/ScriptEngine/ScriptEngine.csproj +++ b/src/ScriptEngine/ScriptEngine.csproj @@ -111,6 +111,7 @@ + From cefb39c276240588046e78e9c625fdfa5befad87 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sun, 13 Aug 2017 22:25:25 +0300 Subject: [PATCH 098/230] =?UTF-8?q?=D0=A3=D1=81=D1=82=D0=B0=D1=80=D0=B5?= =?UTF-8?q?=D0=B2=D1=88=D0=B8=D0=B9=20=D0=BD=D0=B5=D0=BD=D1=83=D0=B6=D0=BD?= =?UTF-8?q?=D1=8B=D0=B9=20partial?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine/Compiler/Compiler.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ScriptEngine/Compiler/Compiler.cs b/src/ScriptEngine/Compiler/Compiler.cs index 0e4abf3fa..49185456a 100644 --- a/src/ScriptEngine/Compiler/Compiler.cs +++ b/src/ScriptEngine/Compiler/Compiler.cs @@ -12,7 +12,7 @@ This Source Code Form is subject to the terms of the namespace ScriptEngine.Compiler { - partial class Compiler + class Compiler { private static readonly Dictionary _tokenToOpCode; From 7d989f4391f5d6e63c03ad4b40ea6f4d1b44d286 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sun, 13 Aug 2017 22:25:41 +0300 Subject: [PATCH 099/230] =?UTF-8?q?=D0=9E=D0=BA=D0=BE=D0=BD=D1=87=D0=B0?= =?UTF-8?q?=D0=BD=D0=B8=D1=8F=20=D1=81=D1=82=D1=80=D0=BE=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine/Compiler/Compiler.cs | 72 +++++++++++++-------------- 1 file changed, 36 insertions(+), 36 deletions(-) diff --git a/src/ScriptEngine/Compiler/Compiler.cs b/src/ScriptEngine/Compiler/Compiler.cs index 49185456a..74e7fb8e9 100644 --- a/src/ScriptEngine/Compiler/Compiler.cs +++ b/src/ScriptEngine/Compiler/Compiler.cs @@ -752,9 +752,9 @@ private void BuildForEachStatement() SetTryBlockFlag(savedTryFlag); PopStructureToken(); - if (_lastExtractedLexem.Token == Token.EndLoop) - { - AddCommand(OperationCode.LineNum, _lastExtractedLexem.LineNumber, isExtraCode: true); + if (_lastExtractedLexem.Token == Token.EndLoop) + { + AddCommand(OperationCode.LineNum, _lastExtractedLexem.LineNumber, isExtraCode: true); } AddCommand(OperationCode.Jmp, loopBegin); @@ -817,15 +817,15 @@ private void BuildCountableForStatement() SetTryBlockFlag(savedTryFlag); PopStructureToken(); - if (_lastExtractedLexem.Token == Token.EndLoop) - { - AddCommand(OperationCode.LineNum, _lastExtractedLexem.LineNumber, isExtraCode: true); + if (_lastExtractedLexem.Token == Token.EndLoop) + { + AddCommand(OperationCode.LineNum, _lastExtractedLexem.LineNumber, isExtraCode: true); } // jmp to start AddCommand(OperationCode.Jmp, indexLoopBegin); var indexLoopEnd = AddCommand(OperationCode.PopTmp, 1); - + var cmd = _module.Code[conditionIndex]; cmd.Argument = indexLoopEnd; _module.Code[conditionIndex] = cmd; @@ -833,32 +833,32 @@ private void BuildCountableForStatement() CorrectBreakStatements(_nestedLoops.Pop(), indexLoopEnd); NextToken(); - } - - private void BuildWhileStatement() - { - NextToken(); - var conditionIndex = _module.Code.Count; - var loopRecord = NestedLoopInfo.New(); - loopRecord.startPoint = conditionIndex; - _nestedLoops.Push(loopRecord); - BuildExpression(Token.Loop); - PushStructureToken(Token.EndLoop); - - var jumpFalseIndex = AddCommand(OperationCode.JmpFalse, 0); - NextToken(); - bool savedTryFlag = SetTryBlockFlag(false); - BuildCodeBatch(); - SetTryBlockFlag(savedTryFlag); - PopStructureToken(); - - if (_lastExtractedLexem.Token == Token.EndLoop) - { - AddCommand(OperationCode.LineNum, _lastExtractedLexem.LineNumber, isExtraCode: true); - } - - AddCommand(OperationCode.Jmp, conditionIndex); - + } + + private void BuildWhileStatement() + { + NextToken(); + var conditionIndex = _module.Code.Count; + var loopRecord = NestedLoopInfo.New(); + loopRecord.startPoint = conditionIndex; + _nestedLoops.Push(loopRecord); + BuildExpression(Token.Loop); + PushStructureToken(Token.EndLoop); + + var jumpFalseIndex = AddCommand(OperationCode.JmpFalse, 0); + NextToken(); + bool savedTryFlag = SetTryBlockFlag(false); + BuildCodeBatch(); + SetTryBlockFlag(savedTryFlag); + PopStructureToken(); + + if (_lastExtractedLexem.Token == Token.EndLoop) + { + AddCommand(OperationCode.LineNum, _lastExtractedLexem.LineNumber, isExtraCode: true); + } + + AddCommand(OperationCode.Jmp, conditionIndex); + var endLoop = AddCommand(OperationCode.Nop, 0); _module.Code[jumpFalseIndex] = new Command() { Code = OperationCode.JmpFalse, @@ -1798,9 +1798,9 @@ private Token[] PopStructureToken() private int AddCommand(OperationCode code, int arg, bool isExtraCode = false) { - var addr = _module.Code.Count; - if (!isExtraCode || ProduceExtraCode) - { + var addr = _module.Code.Count; + if (!isExtraCode || ProduceExtraCode) + { _module.Code.Add(new Command() { Code = code, Argument = arg }); } return addr; From e482282af278f0e732c40d2700f3a7300cf4e2cf Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Sun, 13 Aug 2017 22:34:26 +0300 Subject: [PATCH 100/230] =?UTF-8?q?fixed=20#496.=20=D0=9D=D0=B5=20=D0=BA?= =?UTF-8?q?=D0=BE=D0=BC=D0=BF=D0=B8=D0=BB=D0=B8=D1=80=D1=83=D1=8E=D1=82?= =?UTF-8?q?=D1=81=D1=8F=20=D0=B1=D1=83=D0=BB=D0=B5=D0=B2=D1=8B=20=D0=BE?= =?UTF-8?q?=D0=BF=D0=B5=D1=80=D0=B0=D1=82=D0=BE=D1=80=D1=8B=20=D0=B2=20?= =?UTF-8?q?=D0=BA=D0=B0=D1=87=D0=B5=D1=81=D1=82=D0=B2=D0=B5=20=D1=81=D0=B2?= =?UTF-8?q?=D0=BE=D0=B9=D1=81=D1=82=D0=B2.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine/Compiler/Compiler.cs | 5 ++++- tests/engine-behaviors.os | 7 +++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/ScriptEngine/Compiler/Compiler.cs b/src/ScriptEngine/Compiler/Compiler.cs index 74e7fb8e9..e4d28ccf4 100644 --- a/src/ScriptEngine/Compiler/Compiler.cs +++ b/src/ScriptEngine/Compiler/Compiler.cs @@ -1392,7 +1392,10 @@ private bool IsValidPropertyName(ref Lexem lex) return LanguageDef.IsIdentifier(ref lex) || lex.Type == LexemType.BooleanLiteral || lex.Type == LexemType.NullLiteral - || lex.Type == LexemType.UndefinedLiteral; + || lex.Type == LexemType.UndefinedLiteral + || lex.Token == Token.And + || lex.Token == Token.Or + || lex.Token == Token.Not; } private void ResolveProperty(string identifier) diff --git a/tests/engine-behaviors.os b/tests/engine-behaviors.os index 244668787..17b1ddffd 100644 --- a/tests/engine-behaviors.os +++ b/tests/engine-behaviors.os @@ -41,6 +41,7 @@ ВсеТесты.Добавить("ТестДолжен_ПроверитьПередачуПеречисленийЧерезПараметры"); ВсеТесты.Добавить("ТестДолжен_ПроверитьКомпиляциюКлючевыхСловВСвойствахСтруктуры"); ВсеТесты.Добавить("ТестДолжен_ПроверитьЧтоАргументыКоманднойСтрокиЭтоФиксированныйМассив"); + Возврат ВсеТесты; @@ -384,11 +385,17 @@ Структура.Вставить("Неопределено", Неопределено); Структура.Вставить("Истина", Истина); Структура.Вставить("Ложь", Ложь); + Структура.Вставить("И", 1); + Структура.Вставить("ИЛИ", 2); + Структура.Вставить("НЕ", 3); юТест.ПроверитьРавенство(Истина, Структура.Истина, "Истина"); юТест.ПроверитьРавенство(Ложь, Структура.Ложь, "Ложь"); юТест.ПроверитьРавенство(Неопределено, Структура.Неопределено, "Неопределено"); юТест.ПроверитьРавенство(Null, Структура.Null, "Null"); + юТест.ПроверитьРавенство(1, Структура.И, "И"); + юТест.ПроверитьРавенство(2, Структура.ИЛИ, "ИЛИ"); + юТест.ПроверитьРавенство(3, Структура.НЕ, "НЕ"); КонецПроцедуры From dca04be488962e2a17211637a2ca4e182fb1445d Mon Sep 17 00:00:00 2001 From: Faithfinder Date: Thu, 17 Aug 2017 17:02:54 +0300 Subject: [PATCH 101/230] =?UTF-8?q?=D0=97=D0=B0=D0=BC=D0=B5=D0=BD=D0=B5?= =?UTF-8?q?=D0=BD=20=D1=83=D1=81=D1=82=D0=B0=D1=80=D0=B5=D0=B2=D1=88=D0=B8?= =?UTF-8?q?=D0=B9=20=D0=BC=D0=B5=D1=82=D0=BE=D0=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/TestApp/Controls/CodeControl.xaml.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/TestApp/Controls/CodeControl.xaml.cs b/src/TestApp/Controls/CodeControl.xaml.cs index dfeca7710..55d0c23d5 100644 --- a/src/TestApp/Controls/CodeControl.xaml.cs +++ b/src/TestApp/Controls/CodeControl.xaml.cs @@ -51,7 +51,7 @@ public CodeControl() InitializeComponent(); - editor.TextArea.DefaultInputHandler.NestedInputHandlers.Add(new SearchInputHandler(editor.TextArea)); + SearchPanel.Install(editor.TextArea); editor.ShowLineNumbers = true; foldingManager = FoldingManager.Install(editor.TextArea); From afea15940a355126d8e8fcf5a002918d3d539629 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Tue, 22 Aug 2017 12:17:37 +0300 Subject: [PATCH 102/230] =?UTF-8?q?=D0=92=20standalonerunner=20=D0=BD?= =?UTF-8?q?=D0=B5=20=D0=B1=D1=8B=D0=BB=20=D0=B2=D0=BA=D0=BB=D1=8E=D1=87?= =?UTF-8?q?=D0=B5=D0=BD=20=D1=80=D0=B5=D1=81=D1=83=D1=80=D1=81=20json.dll?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/StandaloneRunner/StandaloneRunner.csproj | 10 ++++++++++ src/StandaloneRunner/packages.config | 4 ++++ 2 files changed, 14 insertions(+) create mode 100644 src/StandaloneRunner/packages.config diff --git a/src/StandaloneRunner/StandaloneRunner.csproj b/src/StandaloneRunner/StandaloneRunner.csproj index 46d3f1631..e33e57987 100644 --- a/src/StandaloneRunner/StandaloneRunner.csproj +++ b/src/StandaloneRunner/StandaloneRunner.csproj @@ -71,6 +71,10 @@ MinimumRecommendedRules.ruleset + + ..\packages\Newtonsoft.Json.10.0.3\lib\net40\Newtonsoft.Json.dll + True + @@ -112,6 +116,12 @@ + + + + + + diff --git a/src/StandaloneRunner/packages.config b/src/StandaloneRunner/packages.config new file mode 100644 index 000000000..03c709252 --- /dev/null +++ b/src/StandaloneRunner/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file From 3c50a88e802a246a082f764dd1ae16f49d35d06f Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Tue, 22 Aug 2017 15:07:54 +0300 Subject: [PATCH 103/230] =?UTF-8?q?=D0=BD=D0=B5=D0=B1=D0=BE=D0=BB=D1=8C?= =?UTF-8?q?=D1=88=D0=B0=D1=8F=20=D0=BE=D0=BF=D1=82=D0=B8=D0=BC=D0=B8=D0=B7?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D1=8F=20=D0=B4=D0=BB=D1=8F=20=D1=87=D0=B0?= =?UTF-8?q?=D1=81=D1=82=D0=BE=20=D0=B8=D1=81=D0=BF=D0=BE=D0=BB=D1=8C=D0=B7?= =?UTF-8?q?=D1=83=D0=B5=D0=BC=D1=8B=D1=85=20=D1=87=D0=B8=D1=81=D0=BB=D0=BE?= =?UTF-8?q?=D0=B2=D1=8B=D1=85=20=D0=BA=D0=BE=D0=BD=D1=81=D1=82=D0=B0=D0=BD?= =?UTF-8?q?=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine/Machine/GenericValue.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/ScriptEngine/Machine/GenericValue.cs b/src/ScriptEngine/Machine/GenericValue.cs index acdd7daf5..48f0dce2d 100644 --- a/src/ScriptEngine/Machine/GenericValue.cs +++ b/src/ScriptEngine/Machine/GenericValue.cs @@ -142,6 +142,8 @@ public override string ToString() private static readonly SimpleConstantValue _staticUndef = new SimpleConstantValue(); private static readonly SimpleConstantValue _staticBoolTrue = BooleanInternal(true); private static readonly SimpleConstantValue _staticBoolFalse = BooleanInternal(false); + private static readonly SimpleConstantValue _staticIntZero = new SimpleConstantValue() {_decimalPart = 0, _type = DataType.Number}; + private static readonly SimpleConstantValue _staticIntOne = new SimpleConstantValue() {_decimalPart = 1, _type = DataType.Number}; public static SimpleConstantValue Undefined() { @@ -164,6 +166,12 @@ private static SimpleConstantValue BooleanInternal(bool value) public static SimpleConstantValue Number(decimal value) { + if (value == 0) + return _staticIntZero; + + if (value == 1) + return _staticIntOne; + var val = new SimpleConstantValue(); val._type = DataType.Number; val._decimalPart = value; From c43a7764da4b0478f246a1752890f09a4ed37134 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Tue, 22 Aug 2017 15:09:43 +0300 Subject: [PATCH 104/230] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D1=80=D0=B0?= =?UTF-8?q?=D0=B1=D0=BE=D1=82=D0=B0=D0=BD=20=D0=BF=D0=BE=D0=B4=D1=85=D0=BE?= =?UTF-8?q?=D0=B4=20=D0=BA=20=D1=81=D1=82=D0=B5=D0=BA=D1=83=20=D0=B2=D1=8B?= =?UTF-8?q?=D0=B7=D0=BE=D0=B2=D0=BE=D0=B2.=20=D0=A0=D0=B5=D0=B0=D0=BB?= =?UTF-8?q?=D0=B8=D0=B7=D0=BE=D0=B2=D0=B0=D0=BD=20=D0=B5=D0=B4=D0=B8=D0=BD?= =?UTF-8?q?=D1=8B=D0=B9=20=D1=81=D0=BA=D0=B2=D0=BE=D0=B7=D0=BD=D0=BE=D0=B9?= =?UTF-8?q?=20=D1=81=D1=82=D0=B5=D0=BA=20=D0=B2=D1=8B=D0=B7=D0=BE=D0=B2?= =?UTF-8?q?=D0=BE=D0=B2=20=D0=B4=D0=BB=D1=8F=20=D0=B2=D1=81=D0=B5=D0=B9=20?= =?UTF-8?q?=D0=BC=D0=B0=D1=88=D0=B8=D0=BD=D1=8B.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ScriptEngine/Machine/MachineInstance.cs | 65 ++++++--------------- 1 file changed, 19 insertions(+), 46 deletions(-) diff --git a/src/ScriptEngine/Machine/MachineInstance.cs b/src/ScriptEngine/Machine/MachineInstance.cs index 9d84458e3..1320f029c 100644 --- a/src/ScriptEngine/Machine/MachineInstance.cs +++ b/src/ScriptEngine/Machine/MachineInstance.cs @@ -26,8 +26,8 @@ public class MachineInstance private Stack _exceptionsStack; private Stack _states; private LoadedModule _module; - private ICodeStatCollector _codeStatCollector = null; - private MachineStopManager _stopManager = null; + private ICodeStatCollector _codeStatCollector; + private MachineStopManager _stopManager; // для отладчика. // актуален в момент останова машины @@ -50,12 +50,9 @@ private struct ExceptionJumpInfo private struct MachineState { public Scope topScope; - public ExecutionFrame currentFrame; public LoadedModule module; public bool hasScope; public IValue[] operationStack; - public ExecutionFrame[] callStack; - public ExceptionJumpInfo[] exceptionsStack; } public void AttachContext(IAttachableContext context, bool detachable) @@ -92,7 +89,8 @@ internal void ExecuteModuleBody() { if (_module.EntryMethodIndex >= 0) { - PrepareMethodExecution(_module.EntryMethodIndex); + var entryRef = _module.MethodRefs[_module.EntryMethodIndex]; + PrepareMethodExecutionDirect(entryRef.CodeIndex); ExecuteCode(); } } @@ -190,9 +188,9 @@ public IValue Evaluate(string expression, bool separate = false) try { if (!separate) - PushFrame(); + PushFrame(frame); - runner.SetFrame(frame); + //runner.SetFrame(frame); runner.SetModule(code); runner.MainCommandLoop(); } @@ -251,16 +249,11 @@ private void PushState() { var stateToSave = new MachineState(); stateToSave.hasScope = DetachTopScope(out stateToSave.topScope); - stateToSave.currentFrame = _currentFrame; stateToSave.module = _module; - StackToArray(ref stateToSave.callStack, _callStack); - StackToArray(ref stateToSave.exceptionsStack, _exceptionsStack); StackToArray(ref stateToSave.operationStack, _operationStack); _states.Push(stateToSave); - _callStack.Clear(); - _exceptionsStack.Clear(); _operationStack.Clear(); } @@ -311,32 +304,24 @@ private void PopState() _module = savedState.module; - RestoreStack(ref _callStack, savedState.callStack); RestoreStack(ref _operationStack, savedState.operationStack); - RestoreStack(ref _exceptionsStack, savedState.exceptionsStack); - SetFrame(savedState.currentFrame); } - private void PushFrame() + private void PushFrame(ExecutionFrame frame) { - if(_currentFrame != null) - _callStack.Push(_currentFrame); - CodeStat_StopFrameStatistics(); + _callStack.Push(frame); + _currentFrame = frame; } private void PopFrame() { - _currentFrame = _callStack.Pop(); + _callStack.Pop(); + _currentFrame = _callStack.Peek(); CodeStat_ResumeFrameStatistics(); } - private void SetFrame(ExecutionFrame frame) - { - _currentFrame = frame; - } - private bool DetachTopScope(out Scope topScope) { if (_scopes.Count > 0) @@ -384,13 +369,7 @@ private void Reset() _module = null; _currentFrame = null; } - - private void PrepareMethodExecution(int methodIndex) - { - var entryRef = _module.MethodRefs[methodIndex]; - PrepareMethodExecutionDirect(entryRef.CodeIndex); - } - + private void PrepareMethodExecutionDirect(int methodIndex) { var methDescr = _module.Methods[methodIndex]; @@ -403,7 +382,7 @@ private void PrepareMethodExecutionDirect(int methodIndex) } frame.InstructionPointer = methDescr.EntryPoint; - SetFrame(frame); + PushFrame(frame); } private void PrepareCodeStatisticsData() @@ -469,7 +448,7 @@ private void ExecuteCode() PopFrame(); } - SetFrame(handler.handlerFrame); + //SetFrame(handler.handlerFrame); _currentFrame.InstructionPointer = handler.handlerAddress; _currentFrame.LastException = exc; @@ -965,8 +944,7 @@ private bool MethodCallImpl(int arg, bool asFunc) } frame.InstructionPointer = methDescr.EntryPoint; - PushFrame(); - SetFrame(frame); + PushFrame(frame); if (_stopManager != null) { //_stopManager.OnFrameEntered(frame); @@ -1225,13 +1203,8 @@ private void Return(int arg) _exceptionsStack.Pop(); } - if (_callStack.Count != 0) - { - PopFrame(); - NextInstruction(); - } - else - _currentFrame.InstructionPointer = -1; + PopFrame(); + NextInstruction(); } @@ -1497,7 +1470,7 @@ private void LineNum(int arg) private void CreateFullCallstack() { var result = new List(); - var callstack = _callStack.ToArray(); + /*var callstack = _callStack.ToArray(); result.Add(FrameInfo(_module, _currentFrame)); @@ -1513,7 +1486,7 @@ private void CreateFullCallstack() result.Add(FrameInfo(state.module, frame)); } } - + */ _fullCallstackCache = result; } From 8298190150256a02b2c10b9864cb884d08bf1b05 Mon Sep 17 00:00:00 2001 From: Faithfinder Date: Tue, 22 Aug 2017 15:10:33 +0300 Subject: [PATCH 105/230] fixes #486 --- src/oscript/MakeAppBehavior.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/oscript/MakeAppBehavior.cs b/src/oscript/MakeAppBehavior.cs index 6762983c0..43bdadfb3 100644 --- a/src/oscript/MakeAppBehavior.cs +++ b/src/oscript/MakeAppBehavior.cs @@ -43,6 +43,7 @@ public override int Execute() ScriptFileHelper.OnBeforeScriptRead(engine); var source = engine.Loader.FromFile(_codePath); var compiler = engine.GetCompilerService(); + engine.SetGlobalEnvironment(new DoNothingHost(), source); var entry = compiler.CreateModule(source); var embeddedContext = engine.GetUserAddedScripts(); @@ -78,5 +79,4 @@ public override int Execute() return 0; } } - } From 8e5cf21df76e1306bf55a7eea4eb3d91aff44e0d Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Tue, 22 Aug 2017 18:22:22 +0300 Subject: [PATCH 106/230] =?UTF-8?q?=D0=9D=D0=B0=D1=87=D0=B0=D0=BB=D0=BE=20?= =?UTF-8?q?=D0=B3=D0=BB=D1=83=D0=B1=D0=BE=D0=BA=D0=BE=D0=B9=20=D0=BF=D0=B5?= =?UTF-8?q?=D1=80=D0=B5=D0=B4=D0=B5=D0=BB=D0=BA=D0=B8=20Machine?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Machine/Contexts/ScriptDrivenObject.cs | 52 ++----- src/ScriptEngine/Machine/ExecutionFrame.cs | 8 + .../Machine/IAttachableContext.cs | 10 +- src/ScriptEngine/Machine/MachineInstance.cs | 137 ++++++------------ src/ScriptEngine/ScriptingEngine.cs | 1 + 5 files changed, 74 insertions(+), 134 deletions(-) diff --git a/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs b/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs index e5df9c884..1756cd279 100644 --- a/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs +++ b/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs @@ -12,7 +12,7 @@ This Source Code Form is subject to the terms of the namespace ScriptEngine.Machine.Contexts { - public abstract class ScriptDrivenObject : PropertyNameIndexAccessor, IAttachableContext + public abstract class ScriptDrivenObject : PropertyNameIndexAccessor, IRunnable { private readonly LoadedModule _module; private MachineInstance _machine; @@ -27,14 +27,6 @@ public abstract class ScriptDrivenObject : PropertyNameIndexAccessor, IAttachabl public IValue[] ConstructorParams { get { return constructorParams; } set { constructorParams = value; } } - //~ScriptDrivenObject() - //{ - // var methId = GetScriptMethod("деструктор", "destructor"); - // if (methId > -1) - // { - // CallAsProcedure(methId, new IValue[0]); - // } - public ScriptDrivenObject(LoadedModuleHandle module) : this(module.Module) { @@ -44,6 +36,11 @@ public ScriptDrivenObject(LoadedModuleHandle module, bool deffered) : this(modul { } + public LoadedModuleHandle Module => new LoadedModuleHandle() + { + Module = _module + }; + internal ScriptDrivenObject(LoadedModule module, bool deffered) : base(TypeManager.GetTypeByName("Object")) { @@ -112,13 +109,8 @@ internal int GetMethodDescriptorIndex(int indexInContext) public void Initialize(MachineInstance runner) { _machine = runner; - _machine.StateConsistentOperation(() => - { - _machine.SetModule(_module); - _machine.AttachContext(this, true); - _machine.ExecuteModuleBody(); - }); - + _machine.ExecuteModuleBody(this); + var methId = GetScriptMethod("ПриСозданииОбъекта", "OnObjectCreate"); int constructorParamsCount = ConstructorParams.Count(); @@ -182,14 +174,7 @@ protected int GetScriptMethod(string methodName, string alias = null) protected IValue CallScriptMethod(int methodIndex, IValue[] parameters) { - IValue returnValue = null; - - _machine.StateConsistentOperation(() => - { - _machine.SetModule(_module); - _machine.AttachContext(this, true); - returnValue = _machine.ExecuteMethod(methodIndex, parameters); - }); + var returnValue = _machine.ExecuteMethod(this, methodIndex, parameters); return returnValue; } @@ -390,12 +375,7 @@ public override void CallAsProcedure(int methodNumber, IValue[] arguments) { if (MethodDefinedInScript(methodNumber)) { - _machine.StateConsistentOperation(() => - { - _machine.AttachContext(this, true); - _machine.SetModule(_module); - _machine.ExecuteMethod(methodNumber - METHOD_COUNT, arguments); - }); + _machine.ExecuteMethod(this, methodNumber - METHOD_COUNT, arguments); } else { @@ -407,15 +387,9 @@ public override void CallAsFunction(int methodNumber, IValue[] arguments, out IV { if (MethodDefinedInScript(methodNumber)) { - IValue returnClosure = null; - _machine.StateConsistentOperation(() => - { - _machine.AttachContext(this, true); - _machine.SetModule(_module); - returnClosure = _machine.ExecuteMethod(methodNumber, arguments); - }); - - retValue = returnClosure; + _machine.AttachContext(this, true); + _machine.SetModule(_module); + retValue = _machine.ExecuteMethod(this, methodNumber - METHOD_COUNT, arguments); } else { diff --git a/src/ScriptEngine/Machine/ExecutionFrame.cs b/src/ScriptEngine/Machine/ExecutionFrame.cs index 978f9bd6e..1aa35a1a2 100644 --- a/src/ScriptEngine/Machine/ExecutionFrame.cs +++ b/src/ScriptEngine/Machine/ExecutionFrame.cs @@ -19,8 +19,16 @@ class ExecutionFrame public bool DiscardReturnValue; public string MethodName; public RuntimeException LastException; + public LoadedModule Module; public Stack LocalFrameStack = new Stack(); + + public Scope ModuleScope { get; set; } + + public override string ToString() + { + return $"{MethodName}: {LineNumber} ({Module.ModuleInfo.ModuleName})"; + } } public struct ExecutionFrameInfo diff --git a/src/ScriptEngine/Machine/IAttachableContext.cs b/src/ScriptEngine/Machine/IAttachableContext.cs index 3d90d3439..b8cbfa411 100644 --- a/src/ScriptEngine/Machine/IAttachableContext.cs +++ b/src/ScriptEngine/Machine/IAttachableContext.cs @@ -9,13 +9,19 @@ This Source Code Form is subject to the terms of the using System.Linq; using System.Text; +using ScriptEngine.Environment; + namespace ScriptEngine.Machine { public interface IAttachableContext : IRuntimeContextInstance { void OnAttach(MachineInstance machine, - out IVariable[] variables, - out MethodInfo[] methods); + out IVariable[] variables, + out MethodInfo[] methods); + } + internal interface IRunnable : IAttachableContext + { + LoadedModuleHandle Module { get; } } } diff --git a/src/ScriptEngine/Machine/MachineInstance.cs b/src/ScriptEngine/Machine/MachineInstance.cs index 1320f029c..34c52d0d6 100644 --- a/src/ScriptEngine/Machine/MachineInstance.cs +++ b/src/ScriptEngine/Machine/MachineInstance.cs @@ -24,7 +24,7 @@ public class MachineInstance private ExecutionFrame _currentFrame; private Action[] _commands; private Stack _exceptionsStack; - private Stack _states; + private LoadedModule _module; private ICodeStatCollector _codeStatCollector; private MachineStopManager _stopManager; @@ -46,15 +46,7 @@ private struct ExceptionJumpInfo public int handlerAddress; public ExecutionFrame handlerFrame; } - - private struct MachineState - { - public Scope topScope; - public LoadedModule module; - public bool hasScope; - public IValue[] operationStack; - } - + public void AttachContext(IAttachableContext context, bool detachable) { IVariable[] vars; @@ -69,24 +61,33 @@ public void AttachContext(IAttachableContext context, bool detachable) }; _scopes.Add(scope); - } - internal void StateConsistentOperation(Action action) + private void AttachModuleContext(IAttachableContext context) { - PushState(); - try - { - action(); - } - finally + IVariable[] vars; + MethodInfo[] methods; + context.OnAttach(this, out vars, out methods); + var scope = new Scope() { - PopState(); - } + Variables = vars, + Methods = methods, + Instance = context + }; + + _scopes[_scopes.Count - 1] = scope; + } + + public void ContextsAttached() + { + // module scope + _scopes.Add(default(Scope)); } - internal void ExecuteModuleBody() + internal void ExecuteModuleBody(IRunnable sdo) { + SetModule(sdo.Module.Module); + AttachModuleContext(sdo); if (_module.EntryMethodIndex >= 0) { var entryRef = _module.MethodRefs[_module.EntryMethodIndex]; @@ -95,8 +96,10 @@ internal void ExecuteModuleBody() } } - internal IValue ExecuteMethod(int methodIndex, IValue[] arguments) + internal IValue ExecuteMethod(IRunnable sdo, int methodIndex, IValue[] arguments) { + SetModule(sdo.Module.Module); + AttachModuleContext(sdo); PrepareMethodExecutionDirect(methodIndex); var method = _module.Methods[methodIndex]; for (int i = 0; i < arguments.Length; i++) @@ -176,6 +179,7 @@ public IValue Evaluate(string expression, bool separate = false) frame.MethodName = code.ModuleInfo.ModuleName; frame.Locals = new IVariable[0]; frame.InstructionPointer = 0; + frame.Module = code; var curModule = _module; var mlocals = new Scope(); @@ -184,13 +188,13 @@ public IValue Evaluate(string expression, bool separate = false) mlocals.Methods = TopScope.Methods; mlocals.Variables = _currentFrame.Locals; runner._scopes.Add(mlocals); + frame.ModuleScope = mlocals; try { if (!separate) PushFrame(frame); - //runner.SetFrame(frame); runner.SetModule(code); runner.MainCommandLoop(); } @@ -244,84 +248,28 @@ internal void Cleanup() Reset(); GC.Collect(); } - - private void PushState() - { - var stateToSave = new MachineState(); - stateToSave.hasScope = DetachTopScope(out stateToSave.topScope); - stateToSave.module = _module; - StackToArray(ref stateToSave.operationStack, _operationStack); - - _states.Push(stateToSave); - - _operationStack.Clear(); - } - - private void StackToArray(ref T[] destination, Stack source) - { - if (source != null) - { - destination = new T[source.Count]; - source.CopyTo(destination, 0); - } - } - - private void RestoreStack(ref Stack destination, T[] source) - { - if (source != null) - { - destination = new Stack(); - for (int i = source.Length-1; i >=0 ; i--) - { - destination.Push(source[i]); - } - } - else - { - destination = null; - } - } - - private void PopState() - { - var savedState = _states.Pop(); - if (savedState.hasScope) - { - if (_scopes[_scopes.Count - 1].Detachable) - { - _scopes[_scopes.Count - 1] = savedState.topScope; - } - else - { - _scopes.Add(savedState.topScope); - } - } - else if (_scopes[_scopes.Count - 1].Detachable) - { - Scope s; - DetachTopScope(out s); - } - - _module = savedState.module; - - RestoreStack(ref _operationStack, savedState.operationStack); - - } - + private void PushFrame(ExecutionFrame frame) { CodeStat_StopFrameStatistics(); _callStack.Push(frame); - _currentFrame = frame; + SetFrame(frame); } private void PopFrame() { _callStack.Pop(); - _currentFrame = _callStack.Peek(); + SetFrame(_callStack.Peek()); CodeStat_ResumeFrameStatistics(); } + private void SetFrame(ExecutionFrame frame) + { + SetModule(frame.Module); + _scopes[_scopes.Count - 1] = frame.ModuleScope; + _currentFrame = frame; + } + private bool DetachTopScope(out Scope topScope) { if (_scopes.Count > 0) @@ -365,7 +313,6 @@ private void Reset() _operationStack = new Stack(); _callStack = new Stack(); _exceptionsStack = new Stack(); - _states = new Stack(); _module = null; _currentFrame = null; } @@ -376,6 +323,8 @@ private void PrepareMethodExecutionDirect(int methodIndex) var frame = new ExecutionFrame(); frame.MethodName = methDescr.Signature.Name; frame.Locals = new IVariable[methDescr.Variables.Count]; + frame.Module = _module; + frame.ModuleScope = TopScope; for (int i = 0; i < frame.Locals.Length; i++) { frame.Locals[i] = Variable.Create(ValueFactory.Create(), methDescr.Variables[i]); @@ -448,7 +397,6 @@ private void ExecuteCode() PopFrame(); } - //SetFrame(handler.handlerFrame); _currentFrame.InstructionPointer = handler.handlerAddress; _currentFrame.LastException = exc; @@ -900,8 +848,13 @@ private bool MethodCallImpl(int arg, bool asFunc) if (sdo.MethodDefinedInScript(methodRef.CodeIndex)) { + // заранее переведем указатель на адрес возврата. В опкоде Return инкремента нет. + NextInstruction(); + var methDescr = _module.Methods[sdo.GetMethodDescriptorIndex(methodRef.CodeIndex)]; var frame = new ExecutionFrame(); + frame.Module = _module; + frame.ModuleScope = TopScope; frame.MethodName = methInfo.Name; frame.Locals = new IVariable[methDescr.Variables.Count]; for (int i = 0; i < frame.Locals.Length; i++) @@ -1204,8 +1157,6 @@ private void Return(int arg) } PopFrame(); - NextInstruction(); - } private void JmpCounter(int arg) diff --git a/src/ScriptEngine/ScriptingEngine.cs b/src/ScriptEngine/ScriptingEngine.cs index 32aaa583d..1222a6590 100644 --- a/src/ScriptEngine/ScriptingEngine.cs +++ b/src/ScriptEngine/ScriptingEngine.cs @@ -63,6 +63,7 @@ public void UpdateContexts() { _machine.AttachContext(item, false); } + _machine.ContextsAttached(); } private void SetDefaultEnvironmentIfNeeded() From 7e67c01e18af66a55da6ae901dc2e93983319ce5 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Wed, 23 Aug 2017 14:14:18 +0300 Subject: [PATCH 107/230] =?UTF-8?q?=D0=A0=D0=B5=D1=84=D0=B0=D0=BA=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=B8=D0=BD=D0=B3=20=D0=B8=20=D0=B8=D1=81=D0=BF?= =?UTF-8?q?=D1=80=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BE=D1=88?= =?UTF-8?q?=D0=B8=D0=B1=D0=BE=D0=BA=20=D0=B2=20=D1=82=D0=BE=D1=87=D0=BA?= =?UTF-8?q?=D0=B5=20=D0=B2=D1=85=D0=BE=D0=B4=D0=B0=20=D0=B2=20=D0=BC=D0=B0?= =?UTF-8?q?=D1=88=D0=B8=D0=BD=D1=83.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Environment/ModuleInformation.cs | 5 ++++ src/ScriptEngine/Machine/MachineInstance.cs | 27 +++++++++---------- 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/src/ScriptEngine/Environment/ModuleInformation.cs b/src/ScriptEngine/Environment/ModuleInformation.cs index eae0d9264..baef6219f 100644 --- a/src/ScriptEngine/Environment/ModuleInformation.cs +++ b/src/ScriptEngine/Environment/ModuleInformation.cs @@ -17,5 +17,10 @@ class ModuleInformation public string ModuleName { get; set; } public ISourceCodeIndexer CodeIndexer { get; set; } public string Origin { get; set; } + + public override string ToString() + { + return ModuleName; + } } } diff --git a/src/ScriptEngine/Machine/MachineInstance.cs b/src/ScriptEngine/Machine/MachineInstance.cs index 34c52d0d6..fe8379ce1 100644 --- a/src/ScriptEngine/Machine/MachineInstance.cs +++ b/src/ScriptEngine/Machine/MachineInstance.cs @@ -63,7 +63,7 @@ public void AttachContext(IAttachableContext context, bool detachable) _scopes.Add(scope); } - private void AttachModuleContext(IAttachableContext context) + private Scope CreateModuleScope(IAttachableContext context) { IVariable[] vars; MethodInfo[] methods; @@ -74,8 +74,7 @@ private void AttachModuleContext(IAttachableContext context) Methods = methods, Instance = context }; - - _scopes[_scopes.Count - 1] = scope; + return scope; } public void ContextsAttached() @@ -86,21 +85,18 @@ public void ContextsAttached() internal void ExecuteModuleBody(IRunnable sdo) { - SetModule(sdo.Module.Module); - AttachModuleContext(sdo); - if (_module.EntryMethodIndex >= 0) + var module = sdo.Module.Module; + if (module.EntryMethodIndex >= 0) { - var entryRef = _module.MethodRefs[_module.EntryMethodIndex]; - PrepareMethodExecutionDirect(entryRef.CodeIndex); + var entryRef = module.MethodRefs[module.EntryMethodIndex]; + PrepareMethodExecutionDirect(sdo, entryRef.CodeIndex); ExecuteCode(); } } internal IValue ExecuteMethod(IRunnable sdo, int methodIndex, IValue[] arguments) { - SetModule(sdo.Module.Module); - AttachModuleContext(sdo); - PrepareMethodExecutionDirect(methodIndex); + PrepareMethodExecutionDirect(sdo, methodIndex); var method = _module.Methods[methodIndex]; for (int i = 0; i < arguments.Length; i++) { @@ -317,14 +313,15 @@ private void Reset() _currentFrame = null; } - private void PrepareMethodExecutionDirect(int methodIndex) + private void PrepareMethodExecutionDirect(IRunnable sdo, int methodIndex) { - var methDescr = _module.Methods[methodIndex]; + var module = sdo.Module.Module; + var methDescr = module.Methods[methodIndex]; var frame = new ExecutionFrame(); frame.MethodName = methDescr.Signature.Name; frame.Locals = new IVariable[methDescr.Variables.Count]; - frame.Module = _module; - frame.ModuleScope = TopScope; + frame.Module = module; + frame.ModuleScope = CreateModuleScope(sdo); for (int i = 0; i < frame.Locals.Length; i++) { frame.Locals[i] = Variable.Create(ValueFactory.Create(), methDescr.Variables[i]); From ed6e67e58c9f4bcd6c06379aed03372d1fabe3ae Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Wed, 23 Aug 2017 15:02:30 +0300 Subject: [PATCH 108/230] =?UTF-8?q?=D0=A0=D0=B5=D0=B0=D0=BB=D0=B8=D0=B7?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D1=8F=20=D0=BD=D0=BE=D0=B2=D0=BE=D0=B3=D0=BE?= =?UTF-8?q?=20=D1=81=D1=82=D0=B5=D0=BA=D0=B0=20=D0=B2=D1=8B=D0=B7=D0=BE?= =?UTF-8?q?=D0=B2=D0=BE=D0=B2.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Machine/Contexts/ScriptDrivenObject.cs | 2 -- src/ScriptEngine/Machine/ExecutionFrame.cs | 2 ++ src/ScriptEngine/Machine/MachineInstance.cs | 31 +++++++++++++------ 3 files changed, 24 insertions(+), 11 deletions(-) diff --git a/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs b/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs index 1756cd279..3bf3f1445 100644 --- a/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs +++ b/src/ScriptEngine/Machine/Contexts/ScriptDrivenObject.cs @@ -387,8 +387,6 @@ public override void CallAsFunction(int methodNumber, IValue[] arguments, out IV { if (MethodDefinedInScript(methodNumber)) { - _machine.AttachContext(this, true); - _machine.SetModule(_module); retValue = _machine.ExecuteMethod(this, methodNumber - METHOD_COUNT, arguments); } else diff --git a/src/ScriptEngine/Machine/ExecutionFrame.cs b/src/ScriptEngine/Machine/ExecutionFrame.cs index 1aa35a1a2..4fee1b2e6 100644 --- a/src/ScriptEngine/Machine/ExecutionFrame.cs +++ b/src/ScriptEngine/Machine/ExecutionFrame.cs @@ -20,9 +20,11 @@ class ExecutionFrame public string MethodName; public RuntimeException LastException; public LoadedModule Module; + public bool IsReentrantCall; public Stack LocalFrameStack = new Stack(); + public Scope ModuleScope { get; set; } public override string ToString() diff --git a/src/ScriptEngine/Machine/MachineInstance.cs b/src/ScriptEngine/Machine/MachineInstance.cs index fe8379ce1..ca35785ca 100644 --- a/src/ScriptEngine/Machine/MachineInstance.cs +++ b/src/ScriptEngine/Machine/MachineInstance.cs @@ -89,14 +89,14 @@ internal void ExecuteModuleBody(IRunnable sdo) if (module.EntryMethodIndex >= 0) { var entryRef = module.MethodRefs[module.EntryMethodIndex]; - PrepareMethodExecutionDirect(sdo, entryRef.CodeIndex); + PrepareReentrantMethodExecution(sdo, entryRef.CodeIndex); ExecuteCode(); } } internal IValue ExecuteMethod(IRunnable sdo, int methodIndex, IValue[] arguments) { - PrepareMethodExecutionDirect(sdo, methodIndex); + PrepareReentrantMethodExecution(sdo, methodIndex); var method = _module.Methods[methodIndex]; for (int i = 0; i < arguments.Length; i++) { @@ -109,14 +109,23 @@ internal IValue ExecuteMethod(IRunnable sdo, int methodIndex, IValue[] arguments } ExecuteCode(); + IValue methodResult = null; if (_module.Methods[methodIndex].Signature.IsFunction) { - return _operationStack.Pop(); + methodResult = _operationStack.Pop(); } - return null; - } + // Этот Pop связан с методом Return. + // Если идет возврат из вложенного вызова, то Pop делается здесь, а не в Return, + // т.к. мы должны выйти из MainCommandLoop и вернуться в предыдущий цикл машины + // + // P.S. it's fuckin spaghetti ( + if (_callStack.Count > 0) + PopFrame(); + return methodResult; + } + #region Debug protocol methods public void SetDebugMode(IDebugController debugContr) @@ -313,7 +322,7 @@ private void Reset() _currentFrame = null; } - private void PrepareMethodExecutionDirect(IRunnable sdo, int methodIndex) + private void PrepareReentrantMethodExecution(IRunnable sdo, int methodIndex) { var module = sdo.Module.Module; var methDescr = module.Methods[methodIndex]; @@ -322,6 +331,7 @@ private void PrepareMethodExecutionDirect(IRunnable sdo, int methodIndex) frame.Locals = new IVariable[methDescr.Variables.Count]; frame.Module = module; frame.ModuleScope = CreateModuleScope(sdo); + frame.IsReentrantCall = true; for (int i = 0; i < frame.Locals.Length; i++) { frame.Locals[i] = Variable.Create(ValueFactory.Create(), methDescr.Variables[i]); @@ -1152,10 +1162,13 @@ private void Return(int arg) { _exceptionsStack.Pop(); } - - PopFrame(); - } + if (_currentFrame.IsReentrantCall) + _currentFrame.InstructionPointer = -1; + else + PopFrame(); + } + private void JmpCounter(int arg) { var counter = _operationStack.Pop(); From c0a8249585c4aafa6a77786b34c11bc05c28cc93 Mon Sep 17 00:00:00 2001 From: EvilBeaver Date: Wed, 23 Aug 2017 15:44:26 +0300 Subject: [PATCH 109/230] =?UTF-8?q?=D0=9F=D0=BE=D1=81=D1=82-=D0=B1=D0=B8?= =?UTF-8?q?=D0=BB=D0=B4=20=D1=81=D0=BA=D1=80=D0=B8=D0=BF=D1=82=20=D0=B4?= =?UTF-8?q?=D0=BB=D1=8F=20=D0=BA=D0=BE=D0=BF=D0=B8=D1=80=D0=BE=D0=B2=D0=B0?= =?UTF-8?q?=D0=BD=D0=B8=D1=8F=20json?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ScriptEngine.HostedScript.csproj | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/ScriptEngine.HostedScript/ScriptEngine.HostedScript.csproj b/src/ScriptEngine.HostedScript/ScriptEngine.HostedScript.csproj index 9c54357f3..1eb159f8c 100644 --- a/src/ScriptEngine.HostedScript/ScriptEngine.HostedScript.csproj +++ b/src/ScriptEngine.HostedScript/ScriptEngine.HostedScript.csproj @@ -244,9 +244,15 @@ xcopy "$(TargetDir)ScriptEngine.HostedScript.dll" "$(SolutionDir)StandaloneRunner\" /Y /E /D -xcopy "$(TargetDir)Ionic.Zip.dll" "$(SolutionDir)StandaloneRunner\" /Y /E /D +xcopy "$(TargetDir)Ionic.Zip.dll" "$(SolutionDir)StandaloneRunner\" /Y /E /D +xcopy "$(TargetDir)Newtonsoft.Json.dll" "$(SolutionDir)StandaloneRunner\" /Y /E /D cp -f "$(TargetDir)ScriptEngine.HostedScript.dll" "$(SolutionDir)StandaloneRunner" -cp -f "$(TargetDir)Ionic.Zip.dll" "$(SolutionDir)StandaloneRunner" +cp -f "$(TargetDir)Ionic.Zip.dll" "$(SolutionDir)StandaloneRunner" +cp -f "$(TargetDir)Newtonsoft.Json.dll" "$(SolutionDir)StandaloneRunner" + + + xcopy "$(TargetDir)ScriptEngine.HostedScript.dll" "$(SolutionDir)StandaloneRunner\" /Y /E /D +xcopy "$(TargetDir)Ionic.Zip.dll" "$(SolutionDir)StandaloneRunner\" /Y /E /D + + + + + + + +