예제 #1
0
파일: tryNode.cs 프로젝트: hstde/Calc2
        private ScriptException TryTryBlock(ScriptThread thread)
        {
            ScriptException ret          = null;
            var             currentScope = thread.CurrentScope;

            try
            {
                tryBlock.Evaluate(thread);
            }
            catch (ScriptException e)
            {
                ret = e;
            }
            catch (Exception e)
            {
                ret = new ScriptException("UnexpectedExceptionException", e);
            }
            finally
            {
                //reset scopes
                thread.CurrentScope = currentScope;
            }

            return(ret);
        }
예제 #2
0
        public void New_Exception_Shows_Negative_Line_And_Column()
        {
            var e = new ScriptException();

            Assert.True(e.LineNumber == -1);
            Assert.True(e.ColumnNumber == -1);
        }
예제 #3
0
        private void HandleException(Exception exp, string line, int l)
        {
            while (exp.InnerException != null)
            {
                exp = exp.InnerException;
            }

            ScriptException toThrow;

            if (exp is ScriptException)
            {
                toThrow = (ScriptException)exp;
            }
            else
            {
                toThrow = new ScriptException(exp.Message);
            }

            if (toThrow.LineNumber <= 0)
            {
                toThrow.Line       = line;
                toThrow.LineNumber = l + 1;
            }
            throw toThrow;
        }
예제 #4
0
파일: JSTests.cs 프로젝트: ikvm/DScript
        public void TestFile(string filename)
        {
            var file   = File.ReadAllText(filename);
            var engine = new ScriptEngine();
            var loader = new EngineFunctionLoader();

            loader.RegisterFunctions(engine);

            engine.Root.AddChild("result", new ScriptVar(0));

            ScriptException ex = null;

            try
            {
                engine.Execute(file);
            }
            catch (ScriptException e)
            {
                ex = e;
            }

            engine.Root.Trace(0, "root");

            var result       = engine.Root.GetParameter("result");
            var resultAsBool = result.Bool;

            Assert.IsTrue(resultAsBool, ex != null ? ex.Message : string.Empty);
        }
예제 #5
0
 private void ClearRuntimeInfo()
 {
     lnkShowErrLocation.Enabled = false;
     lnkShowErrStack.Enabled    = false;
     _runtimeError  = null;
     txtOutput.Text = string.Empty;
 }
예제 #6
0
    public void Errors()
    {
        var context  = Context.Create(_callbackFinalizer, _externalFinalizer);
        var testName = "Errors";

        var strs = new string[] { "new ....", "obj.someMethod()", "throw \"Hello\"" };

        foreach (var str in strs)
        {
            JSScriptException err;
            var res = Eval(context, testName, str, out err);
            Assert.AreNotEqual(default(JSScriptException), err);
            ScriptException.Release(context, err);
            Assert.AreEqual(default(JSValue), res);
        }

        {
            var throwingFun = AsFunction(Eval(context, testName, "(function() { throw \"Error\"; })"));
            JSScriptException err;
            Value.CallCreate(context, throwingFun, default(JSObject), null, 0, out err);
            Assert.AreNotEqual(default(JSScriptException), err);
            ScriptException.Release(context, err);
        }

        Context.Release(context);
    }
예제 #7
0
        public object DoEvalutate(ScriptThread thread, ScriptException se)
        {
            thread.CurrentNode = this;

            if (DependentScopeInfo == null)
            {
                DependentScopeInfo = new ScopeInfo(this, AsString);
            }

            thread.PushScope(DependentScopeInfo, null);

            if (exceptionVar != null)
            {
                var bind = thread.Bind(exceptionVar.Symbol, BindingRequestFlags.ExistingOrNew | BindingRequestFlags.Write);
                if (bind != null && !(bind is NullBinding) && bind.SetValueRef != null)
                {
                    bind.SetValueRef(thread, se.ToScriptObject(), TypeInfo.Table);
                }
            }

            block.Evaluate(thread);

            thread.CurrentNode = this.Parent;
            return(thread.Runtime.NullValue);
        }
예제 #8
0
        /// <summary>
        /// Sends an error message to the console.
        /// </summary>
        /// <param name="sx">The error to be printed</param>
        private void ReportError(ScriptException sx)
        {
            Console.ForegroundColor            = ConsoleColor.Red;
            Console.WriteLine(lastErrorMessage = sx.Message);
            Console.ResetColor();

            if (!string.IsNullOrEmpty(sx.FileName))
            {
                Console.Write(Resources.File);
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write(sx.FileName);
                Console.ResetColor();
                Console.Write(Resources.Comma);
            }

            Console.Write(Resources.Line);
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.Write(sx.ScriptElement.Start.LineNumber + 1);
            Console.ResetColor();

            Console.WriteLine(Resources.PressAnyKeyToReturn);
            Console.ReadKey(true);

            if (sx.FileName != filePath)
            {
                return;
            }

            sciEditor.Caret.Goto(sx.ScriptElement.Start.Offset);
            sciEditor.Markers[0].AddInstanceTo(sciEditor.Caret.LineNumber);
            sciEditor.GetRange(sx.ScriptElement.Start.Offset, sx.ScriptElement.End.Offset).SetIndicator(0);
        }
예제 #9
0
        public void Invoke(Action action)
        {
            var timeout = 5000;
            var cts     = new CancellationTokenSource();

            try
            {
                cts.CancelAfter(timeout);
                var task = Task.Factory.StartNew(() =>
                {
                    Delegate del = action;
                    Invoke(del);
                },
                                                 cts.Token,
                                                 TaskCreationOptions.None,
                                                 _scheduler);
                //Wait
                task.GetAwaiter().GetResult();
                if (task.Exception != null)
                {
                    throw task.Exception;
                }
            }
            catch (OperationCanceledException)
            {
                //handle cancellation
                throw new Exception("ESAPIX Timeout!");
            }
            catch (Exception e)
            {
                var wrapped = new ScriptException(e);
                throw wrapped;
            }
        }
예제 #10
0
        public ExceptionInfoContext(ScriptException source)
        {
            if (source == null)
            {
                throw new ArgumentNullException();
            }

            _exc = source;
        }
예제 #11
0
        public void Test4()
        {
            DialogueScript script = new DialogueScript();

            ScriptException ex = Assert.Throws <ScriptException>(() => { script.Parse(script_4); });

            Assert.That(ex.Message, Is.EqualTo("Semantic Error: Undeclared ID: End at 5.31"));

            Assert.Pass();
        }
예제 #12
0
        public void ConditionTest_1()
        {
            BehaviourScript script = new BehaviourScript();

            ScriptException ex = Assert.Throws <ScriptException>(() => script.Parse(script_5));

            Assert.That(ex.Message, Is.EqualTo("Parsing Error: Unexpected Token: ELSEIF at 12.18"));

            Assert.Pass();
        }
예제 #13
0
 private static void ShowError(ScriptException sx)
 {
     Console.ForegroundColor = ConsoleColor.Red;
     Console.WriteLine(ERROR_MESSAGE_FORMAT,
                       sx.GetType().FullName,
                       sx.Message,
                       string.IsNullOrEmpty(sx.FileName) ? "(asis)" : sx.FileName,
                       sx.ScriptElement.Start.LineNumber + 1);
     Console.ResetColor();
 }
예제 #14
0
 private string FormatScriptExceptionMessage(ScriptException ex)
 {
     if (ex.Token != null)
     {
         return($"{ex.Message} (Regel: {ex.Token.Location.Row + 1}, Teken: {ex.Token.Location.Column + 1})");
     }
     else
     {
         return(ex.Message);
     }
 }
예제 #15
0
 static void CheckError(JSContext context, JSScriptException err)
 {
     if (err != default(JSScriptException))
     {
         try
         {
             throw new Exception("V8.Simple runtime error: " + ScriptException.GetMessage(err));
         }
         finally
         {
             ScriptException.Release(context, err);
         }
     }
 }
예제 #16
0
 public void Invoke(Action action)
 {
     try
     {
         _dispatcher.Invoke(action);
     }
     catch (Exception e)
     {
         var wrapped = new ScriptException(e);
         XContext.Instance.CurrentContext.Logger.Log(wrapped.Message);
         XContext.Instance.CurrentContext.Logger.Log(e.GetRootException().Message);
         throw wrapped;
     }
 }
예제 #17
0
        public async Task InvokeAsync(Action action)
        {
            var task = Task.Run(() =>
            {
                Invoke(action);
            });
            await task;

            if (task.Exception != null)
            {
                var wrapped = new ScriptException(task.Exception);
                throw wrapped;
            }
        }
예제 #18
0
    private void ShowRuntimeError(ScriptException error){
      _runtimeError = error;
      lnkShowErrLocation.Enabled = _runtimeError != null;
      lnkShowErrStack.Enabled = lnkShowErrLocation.Enabled;
      if (_runtimeError != null) {
        //the exception was caught and processed by Interpreter
        WriteOutput("Error: " + error.Message + " At " + _runtimeError.Location.ToUiString() + ".");
        ShowSourcePosition(_runtimeError.Location.Position, 1);
      } else {
        //the exception was not caught by interpreter/AST node. Show full exception info
        WriteOutput("Error: " + error.Message);
        fmShowException.ShowException(error);

      }
      tabBottom.SelectedTab = pageOutput;
    }
예제 #19
0
            int IActiveScriptSite.OnScriptError(IActiveScriptError scriptError)
            {
                string sourceLine = null;

                try
                {
                    scriptError.GetSourceLineText(out sourceLine);
                }
                catch
                {
                    // happens sometimes...
                }
                uint sourceContext;
                int  lineNumber;
                int  characterPosition;

                scriptError.GetSourcePosition(out sourceContext, out lineNumber, out characterPosition);
                lineNumber++;
                characterPosition++;
                System.Runtime.InteropServices.ComTypes.EXCEPINFO exceptionInfo;
                scriptError.GetExceptionInfo(out exceptionInfo);

                string message;

                if (!string.IsNullOrEmpty(sourceLine))
                {
                    message = "Script exception: {1}. Error number {0} (0x{0:X8}): {2} at line {3}, column {4}. Source line: '{5}'.";
                }
                else
                {
                    message = "Script exception: {1}. Error number {0} (0x{0:X8}): {2} at line {3}, column {4}.";
                }
                LastException        = new ScriptException(string.Format(message, exceptionInfo.scode, exceptionInfo.bstrSource, exceptionInfo.bstrDescription, lineNumber, characterPosition, sourceLine));
                LastException.Line   = lineNumber;
                LastException.Column = characterPosition;
                LastException.Number = exceptionInfo.scode;
                LastException.Text   = sourceLine;
                LastException.Desc   = exceptionInfo.bstrDescription;
                return(0);
            }
예제 #20
0
    public void CallbackExceptions()
    {
        var testName = "CallbackExceptions";
        var context  = Context.Create(_callbackFinalizer, _externalFinalizer);

        var cb = CreateCallback(context, (cxt, args) =>
        {
            throw new Exception(testName);
        });

        JSScriptException err;
        var res = Value.CallCreate(context, cb, default(JSObject), null, 0, out err);

        Assert.AreEqual(default(JSValue), res);
        Assert.AreNotEqual(default(JSScriptException), err);
        var exceptionString = AsString(context, ScriptException.GetException(err));

        Assert.AreEqual(testName, exceptionString);

        ScriptException.Release(context, err);
        Context.Release(context);
    }
예제 #21
0
        private void GotResponse()
        {
            TimeElapsed = IDate.Now.getTime() - _timestart;

            Worker.Stop();



            if (IsVerbose)
            {
                Console.Log(" <= [" + this.Descriptor.Description + "] " + TimeElapsed + " ms, " + this.ResponseText.Length + " bytes");
                Console.Log("json: " + this.ResponseText);
            }

            Descriptor = null;


            try
            {
                Descriptor = Expando.FromJSONProtocolString(ResponseText).To <MyTransportDescriptor <TType> >();
            }
            catch (ScriptException exc)
            {
                LastException = exc;

                //if (IsVerbose)
                //{
                //    Console.LogError("unable to spawn from json, " + exc.Message);
                //    Console.LogError("stream -> " + ResponseText);
                //}
            }

            Helper.Invoke(Complete, this);

            //if (Complete != null)
            //    Complete(this);
        }
예제 #22
0
        public void Send()
        {
            _timestart  = IDate.Now.getTime();
            TimeElapsed = 0;

            LastException = null;

            if (BeforeSend != null)
            {
                BeforeSend(this);
            }

            if (Descriptor.Description == null)
            {
                string err = "header not set";

                Console.LogError(err);

                if (DemandHeader)
                {
                    throw new ScriptException(err);
                }
            }


            string json = ToJSON();

            if (IsVerbose)
            {
                Console.Log(" => [" + Descriptor.Description + "] " + json.Length + " bytes");
            }

            Worker.StartInterval();



            if (IsVerbose)
            {
                Console.WriteLine("var data = " + json + ";");
                Console.Log(json.Length + " bytes sent");
            }

            if (Form == null)
            {
                Request.open(HTTPMethodEnum.POST, Url);
                Request.send(json);
                Request.InvokeOnComplete(
                    delegate
                {
                    ResponseText = Request.responseText;

                    GotResponse();
                });
            }
            else
            {
                IHTMLInput z = new IHTMLInput(HTMLInputTypeEnum.hidden);

                z.name  = Helper.FormTemplateJSONField;
                z.value = Convert.ToBase64String(json);

                Form.appendChild(z);
                Form.target = Descriptor.Callback;
                Form.submit();

                z.Dispose();
            }
        }
예제 #23
0
 private void ClearRuntimeInfo() {
   lnkShowErrLocation.Enabled = false;
   lnkShowErrStack.Enabled = false;
   _runtimeError = null;
   txtOutput.Text = string.Empty;
 }
예제 #24
0
    private void ShowRuntimeError(ScriptException error){
      _runtimeError = error;
      lnkShowErrLocation.Enabled = _runtimeError != null;
      lnkShowErrStack.Enabled = lnkShowErrLocation.Enabled;
      if (_runtimeError != null) {
        //the exception was caught and processed by Interpreter
        WriteOutput("Error: " + error.Message + " At " + _runtimeError.Location.ToUiString() + ".");
        ShowSourcePosition(_runtimeError.Location.Position, 1);
      } else {
        //the exception was not caught by interpreter/AST node. Show full exception info
        WriteOutput("Error: " + error.Message);
        fmShowException.ShowException(error);

      }
      tabBottom.SelectedTab = pageOutput;
    }
예제 #25
0
            int IActiveScriptSite.OnScriptError(IActiveScriptError scriptError)
            {
                string sourceLine = null;
                try
                {
                    scriptError.GetSourceLineText(out sourceLine);
                }
                catch
                {
                    // happens sometimes... 
                }
                uint sourceContext;
                int lineNumber;
                int characterPosition;
                scriptError.GetSourcePosition(out sourceContext, out lineNumber, out characterPosition);
                lineNumber++;
                characterPosition++;
                System.Runtime.InteropServices.ComTypes.EXCEPINFO exceptionInfo;
                scriptError.GetExceptionInfo(out exceptionInfo);

                string message;
                if (!string.IsNullOrEmpty(sourceLine))
                {
                    message = "Script exception: {1}. Error number {0} (0x{0:X8}): {2} at line {3}, column {4}. Source line: '{5}'.";
                }
                else
                {
                    message = "Script exception: {1}. Error number {0} (0x{0:X8}): {2} at line {3}, column {4}.";
                }
                LastException = new ScriptException(string.Format(message, exceptionInfo.scode, exceptionInfo.bstrSource, exceptionInfo.bstrDescription, lineNumber, characterPosition, sourceLine));
                LastException.Line = lineNumber;
                LastException.Column = characterPosition;
                LastException.Number = exceptionInfo.scode;
                LastException.Text = sourceLine;
                LastException.Desc = exceptionInfo.bstrDescription;
                return 0;
            }
예제 #26
0
 private void ExceptionHandler(ScriptException error)
 {
     Assert.Fail();
 }
예제 #27
0
 void IActiveScriptSite.OnEnterScript()
 {
     //Trace.WriteLine("OnEnterScript");
     _lastException = null;
 }
예제 #28
0
 int IActiveScriptSite.OnEnterScript()
 {
     LastException = null;
     return 0;
 }
예제 #29
0
        static void Main(string[] args)
        {
            if (args.Length > 1)
            {
                Console.WriteLine("ERROR: Too many arguments, maybe put quotes around it?");
                return;
            }

            string specificTest = null;

            if (args.Length == 1)
            {
                specificTest = args[0];
            }

            string solutionDir    = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName;
            string testScriptsDir = Path.Combine(solutionDir, "scripttests");

            var testfilePaths =
                specificTest == null
                ? new List <string>(Directory.GetFiles(testScriptsDir, "*.*", SearchOption.AllDirectories))
                : new List <string>()
            {
                Path.Combine(testScriptsDir, specificTest + ".txt")
            };

            testfilePaths.Sort();

            int errorCount = 0;

#if !DEBUG
            try
#endif
            {
                foreach (string filePath in testfilePaths)
                {
                    string testName = Path.GetFileNameWithoutExtension(filePath);
                    Console.WriteLine("-- " + testName);

                    string fileText = File.ReadAllText(filePath);

                    int separatorIdx = fileText.IndexOf("===");
                    if (separatorIdx <= 0)
                    {
                        Console.WriteLine("ERROR: Test lacks == divider");
                        return;
                    }

                    string script   = fileText.Substring(0, separatorIdx).Trim();
                    string expected = fileText.Substring(separatorIdx + "===".Length).Trim().Replace("\r\n", "\n");

                    string output;
                    {
                        var symbols = new SymbolTable();
                        var stream  = new MemoryStream();
                        using (var proc = new ScriptProcessor(script, symbols, stream, "testScript", "execute", null, sm_scriptCtxtFunctions))
                            proc.ProcessAsync().Wait();
                        output = Encoding.UTF8.GetString(stream.ToArray()).Trim().Replace("\r\n", "\n");
                    }

                    if (expected != output)
                    {
                        ++errorCount;
                        Console.WriteLine("ERROR: Test '{0}' fails!", testName);
                        Console.WriteLine($" - Output:\n{output}");
                        Console.WriteLine($" - Expected:\n{expected}");
                        return;
                    }
                }
            }
#if !DEBUG
            catch (Exception exp)
            {
                if (exp is AggregateException)
                {
                    while (exp.InnerException != null)
                    {
                        exp = exp.InnerException;
                    }
                }

                if (exp is ScriptException)
                {
                    ScriptException scriptExp = (ScriptException)exp;
                    Console.WriteLine("SCRIPT ERROR:");
                    Console.WriteLine(scriptExp.Message);
                    Console.WriteLine(scriptExp.LineNumber + ": " + scriptExp.Line);
                }
                else
                {
                    Console.WriteLine("EXCEPTION:");
                    Console.WriteLine($"{exp.GetType().FullName}: {exp.Message}");
                }

                return;
            }
#endif
            Console.WriteLine("\nAll done.  Errors: {0}", errorCount);
        }
예제 #30
0
 int IActiveScriptSite.OnEnterScript()
 {
     LastException = null;
     return(0);
 }