コード例 #1
0
        public async Task InvokeMethodInterpreterRecursivityStackoverflowAsync()
        {
            var parser = new BaZicParser();

            var inputCode =
                @"EXTERN FUNCTION Main(args[])
    FirstMethod(1000) # A Stackoverflow must never happen if FirstMethod is ASYNC.
END FUNCTION

ASYNC FUNCTION FirstMethod(num)
    IF num > 1 THEN
        RETURN FirstMethod(num - 1)
    END IF
    RETURN num
END FUNCTION";

            var interpreter = new BaZicInterpreter(parser.Parse(inputCode, false).Program);
            await interpreter.StartDebugAsync(true);

            var expected1 = "[Log] End of the execution of the method 'FirstMethod'. Returned value : 0 (System.Int32)";

            var result = interpreter.GetStateChangedHistoryString();

            Assert.IsTrue(result.Contains(expected1));
            Assert.AreEqual(null, interpreter.ProgramResult);

            await TestUtilities.TestAllRunningMode(null, inputCode);
        }
コード例 #2
0
        /// <inheritdoc/>
        internal override object Run()
        {
            var declarations = BaZicInterpreter.MethodDeclarations.Where(m => string.Compare(m.Name.Identifier, Expression.MethodName.Identifier, StringComparison.Ordinal) == 0);

            if (declarations.Count() == 0)
            {
                BaZicInterpreter.ChangeState(this, new MethodNotFoundException(Expression.MethodName.Identifier, L.BaZic.Runtime.Interpreters.Expressions.InvokeMethodInterpreter.FormattedMethodNotFound(Expression.MethodName)), Expression);
                return(null);
            }
            else if (declarations.Count() > 1)
            {
                BaZicInterpreter.ChangeState(this, new MethodNotFoundException(Expression.MethodName.Identifier, L.BaZic.Runtime.Interpreters.Expressions.InvokeMethodInterpreter.FormattedSeveralMethods(Expression.MethodName)), Expression);
                return(null);
            }

            // If the invocation is made manually by the user (outisde of the execution flow).
            if (_failIfNotExtern)
            {
                if (!declarations.Single().IsExtern)
                {
                    BaZicInterpreter.ChangeState(this, new MethodNotFoundException(Expression.MethodName.Identifier, L.BaZic.Runtime.Interpreters.Expressions.InvokeMethodInterpreter.FormattedMethodNotFound(Expression.MethodName)), Expression);
                    return(null);
                }

                if (!declarations.Single().IsAsync&& Expression.Await)
                {
                    Expression.Await = false;
                }
            }

            var methodInterpreter = new MethodInterpreter(BaZicInterpreter, ParentInterpreter, declarations.Single(), Expression, _executionFlowId);

            return(methodInterpreter.Invoke());
        }
コード例 #3
0
        public async Task BinaryOperatorInterpreterAddition()
        {
            var parser = new BaZicParser();

            var inputCode =
                @"EXTERN FUNCTION Main(args[])
    VARIABLE var1 = 2 + 3 # Should be 5
    VARIABLE var2 = ""2"" + 3 # Should be 23
    VARIABLE var3 = 2 + 3.0 # Should be 5
    VARIABLE var4 = ""Hello"" + true # Should be HelloTrue
END FUNCTION";
            var interpreter = new BaZicInterpreter(parser.Parse(inputCode, true).Program);
            await interpreter.StartDebugAsync(true);

            var result = interpreter.GetStateChangedHistoryString();

            Assert.IsNull(interpreter.Error);
            Assert.IsTrue(result.Contains("[Log] Variable 'var1' declared. Default value : 5 (System.Int32)"));
            Assert.IsTrue(result.Contains("[Log] Variable 'var2' declared. Default value : 23 (System.String)"));
            Assert.IsTrue(result.Contains("[Log] Variable 'var3' declared. Default value : 5 (System.Double)"));
            Assert.IsTrue(result.Contains("[Log] Variable 'var4' declared. Default value : HelloTrue (System.String)"));



            inputCode =
                @"EXTERN FUNCTION Main(args[])
    VARIABLE var4 = true + false # Should fail
END FUNCTION";
            interpreter = new BaZicInterpreter(parser.Parse(inputCode, true).Program);
            await interpreter.StartDebugAsync(true);

            result = interpreter.GetStateChangedHistoryString();

            Assert.IsTrue(result.Contains("[Error] Unexpected and unmanaged error has been detected : Operator '+' cannot be applied to operands of type 'bool' and 'bool'"));
        }
コード例 #4
0
        public async Task ProgramInterpreterInvokeExternMethod3()
        {
            var parser = new BaZicParser();

            var inputCode =
                @"EXTERN FUNCTION Main(args[])
    AWAIT MethodAsync(345, 5.0)
END FUNCTION

EXTERN FUNCTION Method1(arg)
    RETURN arg
END FUNCTION

ASYNC FUNCTION MethodAsync(value, timeToWait)
    VARIABLE var1 = AWAIT System.Threading.Tasks.Task.Delay(System.TimeSpan.FromSeconds(timeToWait))
    RETURN value
END FUNCTION";

            using (var interpreter = new BaZicInterpreter(parser.Parse(inputCode, false).Program))
            {
                var t      = interpreter.StartDebugAsync(true);
                var result = await interpreter.InvokeMethod(true, "Method1", true, 123);

                Assert.AreEqual(123, result);

                // Idle is expected because InvokeMethod waits that the main
                // thread (used by Main()) is free before running. So the async
                // function is complete before reaching this assert.
                Assert.AreEqual(BaZicInterpreterState.Idle, interpreter.State);

                await interpreter.Stop();

                Assert.AreEqual(BaZicInterpreterState.Stopped, interpreter.State);
            }
        }
コード例 #5
0
ファイル: BaZicInterpreterUiTest.cs プロジェクト: veler/BaZic
        public async Task BaZicInterpreterWithUiProgramBadControlAccessorUse()
        {
            var parser = new BaZicParser();

            var inputCode =
                @"
EXTERN FUNCTION Main(args[])
    Button1.Content = ""Hello""
END FUNCTION";

            var xamlCode = @"
<Window xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" Name=""Window"">
    <Grid>
        <Button Name=""Button1""/>
    </Grid>
</Window>";

            var bazicProgram = (BaZicUiProgram)parser.Parse(inputCode, xamlCode, optimize: true).Program;

            var interpreter = new BaZicInterpreter(bazicProgram);
            await interpreter.StartDebugAsync(true);

            var exception = interpreter.Error.Exception;

            Assert.AreEqual("The variable 'Button1' does not exist or is not accessible.", exception.Message);
        }
コード例 #6
0
ファイル: ProgramInterpreter.cs プロジェクト: veler/BaZic
        private EntryPointMethod GetEntryPointMethod()
        {
            var entryPoints = _program.Methods.OfType <EntryPointMethod>().ToList();

            if (entryPoints.Count == 0)
            {
                BaZicInterpreter.ChangeState(this, new MissingEntryPointMethodException());
                return(null);
            }
            else if (entryPoints.Count > 1)
            {
                BaZicInterpreter.ChangeState(this, new SeveralEntryPointMethodException(), entryPoints.Last());
                return(null);
            }

            var entryPoint = entryPoints.Single();

            if (entryPoint.Arguments.Count != 1)
            {
                BaZicInterpreter.ChangeState(this, new BadArgumentException(L.BaZic.Parser.Statements.UniqueArgumentEntryPoint), entryPoint);
                return(null);
            }
            else if (!entryPoint.Arguments.Single().IsArray)
            {
                BaZicInterpreter.ChangeState(this, new BadArgumentException(L.BaZic.Parser.Statements.EntryPointArgumentArrayExpected), entryPoint.Arguments.Single());
                return(null);
            }

            return(entryPoint);
        }
コード例 #7
0
ファイル: Interpreter.cs プロジェクト: veler/BaZic
        /// <summary>
        /// Retrieves the parent interpreter of the current executed method.
        /// </summary>
        /// <param name="includeThis">(optional) Defines whether the search must include the current interpreter.</param>
        /// <param name="throwIfNotFound">(optional) Defines whether an error must be thrown if the parent interpreter is not found.</param>
        /// <returns>The parent <see cref="MethodInterpreter"/></returns>
        internal MethodInterpreter GetParentMethodInterpreter(bool includeThis = false, bool throwIfNotFound = true)
        {
            if (includeThis && this is MethodInterpreter thisMethodInterpreter)
            {
                return(thisMethodInterpreter);
            }

            var parentInterpreter = ParentInterpreter;

            while (parentInterpreter != null)
            {
                if (parentInterpreter is MethodInterpreter methodInterpreter)
                {
                    return(methodInterpreter);
                }

                parentInterpreter = parentInterpreter.ParentInterpreter;
            }

            if (throwIfNotFound)
            {
                BaZicInterpreter.ChangeState(this, new InternalException(L.BaZic.Runtime.Interpreters.Interpreter.ParentMethodNotFound));
            }
            return(null);
        }
コード例 #8
0
        public async Task ProgramInterpreterInvokeExternMethod4()
        {
            var parser = new BaZicParser();

            var inputCode =
                @"EXTERN FUNCTION Main(args[])
END FUNCTION

EXTERN FUNCTION Method1(arg)
    RETURN arg
END FUNCTION";

            using (var interpreter = new BaZicInterpreter(parser.Parse(inputCode, false).Program))
            {
                var tempFile = Path.Combine(Path.GetTempPath(), "BaZic_Bin", Path.GetFileNameWithoutExtension(Path.GetTempFileName()) + ".exe");
                var errors   = await interpreter.Build();

                Assert.IsNull(errors);

                var result = await interpreter.InvokeMethod(true, "Method1", true, 123);

                Assert.AreEqual(123, result);
                Assert.AreEqual(BaZicInterpreterState.Idle, interpreter.State);
            }
        }
コード例 #9
0
ファイル: AssignInterpreter.cs プロジェクト: veler/BaZic
        /// <summary>
        /// Assigns the specified value to a property.
        /// </summary>
        /// <param name="propertyReference">The reference to the property to set.</param>
        /// <param name="value">The value to assign.</param>
        private void AssignProperty(PropertyReferenceExpression propertyReference, object value)
        {
            if (string.IsNullOrWhiteSpace(propertyReference.PropertyName?.Identifier))
            {
                BaZicInterpreter.ChangeState(this, new NullValueException(L.BaZic.Runtime.Interpreters.Expressions.PropertyReferenceInterpreter.UndefinedName), propertyReference);
            }
            var targetObjectValue = ParentInterpreter.RunExpression(propertyReference.TargetObject);

            if (ParentInterpreter.IsAborted)
            {
                return;
            }

            if (targetObjectValue == null)
            {
                BaZicInterpreter.ChangeState(this, new NullValueException(L.BaZic.Runtime.Interpreters.Expressions.PropertyReferenceInterpreter.NullValue), propertyReference);
                return;
            }

            if (propertyReference.TargetObject is ClassReferenceExpression && targetObjectValue is Type)
            {
                BaZicInterpreter.Reflection.SetStaticProperty((Type)targetObjectValue, propertyReference.PropertyName.Identifier, value);
            }
            else if (targetObjectValue is FrameworkElement)
            {
                BaZicInterpreter.ProgramInterpreter.UIDispatcher.Invoke(() =>
                {
                    BaZicInterpreter.Reflection.SetProperty(targetObjectValue, propertyReference.PropertyName.Identifier, value);
                }, System.Windows.Threading.DispatcherPriority.Background);
            }
            else
            {
                BaZicInterpreter.Reflection.SetProperty(targetObjectValue, propertyReference.PropertyName.Identifier, value);
            }
        }
コード例 #10
0
        public async Task ProgramInterpreterTestEntryPointMethod()
        {
            var parser = new BaZicParser();

            var inputCode =
                @"FUNCTION Method1()
END FUNCTION";

            using (var interpreter = new BaZicInterpreter(parser.Parse(inputCode, false).Program))
            {
                await interpreter.StartDebugAsync(true);

                Assert.AreEqual(BaZicInterpreterState.Idle, interpreter.State);
            }

            inputCode =
                @"EXTERN FUNCTION Main(args[])
END FUNCTION

EXTERN FUNCTION Main(args[])
END FUNCTION";
            using (var interpreter = new BaZicInterpreter(parser.Parse(inputCode, true).Program))
            {
                await interpreter.StartDebugAsync(true);

                Assert.IsInstanceOfType(interpreter.Error.Exception, typeof(SeveralEntryPointMethodException));
            }
        }
コード例 #11
0
        public async Task ProgramInterpreterInvokeExternMethod5()
        {
            var parser = new BaZicParser();

            var inputCode =
                @"EXTERN FUNCTION Main(args[])
END FUNCTION

FUNCTION Method1(arg)
    RETURN arg
END FUNCTION";

            using (var interpreter = new BaZicInterpreter(parser.Parse(inputCode, false).Program))
            {
                var tempFile = Path.Combine(Path.GetTempPath(), "BaZic_Bin", Path.GetFileNameWithoutExtension(Path.GetTempFileName()) + ".exe");
                var errors   = await interpreter.Build();

                Assert.IsNull(errors);

                var result = await interpreter.InvokeMethod(true, "Method1", true, 123);

                Assert.AreEqual(null, result);
                Assert.AreEqual("Unexpected and unmanaged error has been detected : The method 'Method1' does not exist in the type 'BaZicProgramReleaseMode.Program'.", interpreter.Error.Exception.Message);
                Assert.AreEqual(BaZicInterpreterState.StoppedWithError, interpreter.State);
            }
        }
コード例 #12
0
ファイル: BaZicInterpreterTest.cs プロジェクト: veler/BaZic
        public async Task BaZicCompile()
        {
            var inputCode =
                @"EXTERN FUNCTION Main(args[])
    VARIABLE var1 = 1
    VARIABLE Var1 = 2
    VARIABLE result = var1 + Var1
    System.Console.WriteLine(result.ToString())
    RETURN result
END FUNCTION";

            using (var interpreter = new BaZicInterpreter(inputCode, false))
            {
                var mscorlib      = AssemblyInfoHelper.GetAssemblyDetailsFromNameOrLocation(typeof(object).Assembly.FullName);
                var baZicCoreTest = AssemblyInfoHelper.GetAssemblyDetailsFromNameOrLocation(typeof(LogMock).Assembly.Location);
                interpreter.SetDependencies(mscorlib, baZicCoreTest);

                var tempFile = Path.Combine(Path.GetTempPath(), "BaZic_Bin", Path.GetFileNameWithoutExtension(Path.GetTempFileName()) + ".exe");
                var errors   = await interpreter.Build(Core.Enums.BaZicCompilerOutputType.ConsoleApp, tempFile);

                Assert.IsNull(errors);
                Assert.IsTrue(File.Exists(tempFile));
                Assert.IsTrue(File.Exists(tempFile.Replace(".exe", ".pdb")));
                Assert.IsTrue(File.Exists(Path.Combine(Path.GetTempPath(), "BaZic_Bin", "BaZic.Core.Tests.dll")));

                File.Delete(tempFile);
                File.Delete(tempFile.Replace(".exe", ".pdb"));
                File.Delete(Path.Combine(Path.GetTempPath(), "BaZic_Bin", "BaZic.Core.Tests.dll"));
                Directory.Delete(Path.Combine(Path.GetTempPath(), @"BaZic_Bin"), true);
            }
        }
コード例 #13
0
        public async Task ProgramInterpreterInvokeExternMethod7()
        {
            var parser = new BaZicParser();

            var inputCode =
                @"EXTERN FUNCTION Main(args[])
END FUNCTION

EXTERN ASYNC FUNCTION Method1(arg)
    VARIABLE var1 = AWAIT System.Threading.Tasks.Task.Delay(System.TimeSpan.FromSeconds(3.0))
    RETURN arg
END FUNCTION";

            using (var interpreter = new BaZicInterpreter(parser.Parse(inputCode, false).Program))
            {
                var errors = await interpreter.Build();

                Assert.IsNull(errors);

                var t      = interpreter.StartReleaseAsync(true);
                var result = (Task)interpreter.InvokeMethod(true, "Method1", true, 123);

                Assert.AreEqual(TaskStatus.WaitingForActivation, result.Status);

                await Task.Delay(5000);

                Assert.AreEqual(TaskStatus.RanToCompletion, result.Status);
                Assert.AreEqual(123, ((dynamic)result).Result);
                Assert.AreEqual(BaZicInterpreterState.Idle, interpreter.State);

                await interpreter.Stop();

                Assert.AreEqual(BaZicInterpreterState.Stopped, interpreter.State);
            }
        }
コード例 #14
0
ファイル: BlockInterpreter.cs プロジェクト: veler/BaZic
        /// <summary>
        /// Execute the statements of the block.
        /// </summary>
        internal void Run()
        {
            _executionCursor = 0;
            while (_executionCursor < _statements.Count)
            {
                RunStatement(_statements[_executionCursor]);

                BaZicInterpreter.AttemptPauseIfRequired(this);

                if (IsAborted || State.ExitMethod || State.ExitIteration || State.ExitBlockBecauseOfLabelJump)
                {
                    break;
                }

                _executionCursor++;
            }

            var parentMethodInterpreter = GetParentMethodInterpreter();

            foreach (var variable in Variables)
            {
                if (parentMethodInterpreter.DebugCallInfo.Variables.Remove(variable))
                {
                    variable.Dispose();
                }
            }
        }
コード例 #15
0
ファイル: Interpreter.cs プロジェクト: veler/BaZic
        /// <summary>
        /// Look for the specified variable currently in memory based on its unique ID.
        /// </summary>
        /// <param name="variableId">The unique ID that represents the variable.</param>
        /// <param name="variableName">The friendly name of the variable.</param>
        /// <param name="throwIfNotFound">(optional) Indicates whether an exception must be thrown if the variable is not found. By default, this argument is True.</param>
        /// <param name="searchInParents">Defines whether finding a variable can be performed in the parent interpreters.</param>
        /// <returns>Returns the variable if it has been found, otherwise, null or throws an exception.</returns>
        internal Variable GetVariable(Guid variableId, string variableName, bool throwIfNotFound = true, bool searchInParents = true)
        {
            var interpreter = this;

            do
            {
                var variable = interpreter.Variables.FirstOrDefault(v => v.Id == variableId);

                if (variable != null)
                {
                    return(variable);
                }

                if (searchInParents)
                {
                    interpreter = interpreter.ParentInterpreter;
                }
            } while (searchInParents && interpreter != null);

            if (throwIfNotFound)
            {
                BaZicInterpreter.ChangeState(this, new VariableNotFoundException(variableName));
            }

            return(null);
        }
コード例 #16
0
ファイル: Interpreter.cs プロジェクト: veler/BaZic
        /// <summary>
        /// Set the value of the specified variable currently in memory based on its unique ID.
        /// </summary>
        /// <param name="variableRef">The reference to the variable to set.</param>
        /// <param name="value">The value to give to the variable</param>
        internal void SetVariable(VariableReferenceExpression variableRef, object value)
        {
            var variable = GetVariable(variableRef.VariableDeclarationID, variableRef.Name.Identifier, true);

            if (IsAborted)
            {
                return;
            }

            var valueInfo = ValueInfo.GetValueInfo(value);

            if (!valueInfo.IsNull)
            {
                if (variable.IsArray && !valueInfo.IsArray)
                {
                    BaZicInterpreter.ChangeState(this, new NotAssignableException(L.BaZic.Runtime.Interpreters.Interpreter.FormattedArrayExpected(variableRef.Name)), variableRef);
                    return;
                }
                else if (!variable.IsArray && valueInfo.IsArray)
                {
                    BaZicInterpreter.ChangeState(this, new NotAssignableException(L.BaZic.Runtime.Interpreters.Interpreter.FormattedNotArrayExpected(variableRef.Name)), variableRef);
                    return;
                }
            }

            variable.SetValue(value, valueInfo);

            if (BaZicInterpreter.Verbose)
            {
                VerboseLog(L.BaZic.Runtime.Interpreters.Interpreter.FormattedVariableSetted(variable.Name, variable));
            }
        }
コード例 #17
0
        /// <inheritdoc/>
        internal override void Run()
        {
            if (!ParentInterpreter.State.IsInIteration)
            {
                BaZicInterpreter.ChangeState(this, new IncoherentStatementException(L.BaZic.Runtime.Interpreters.Statements.BreakInterpreter.Illegal), Statement);
            }

            ParentInterpreter.State.ExitIteration = true;
        }
コード例 #18
0
        public async Task PropertyReferenceInterpreter()
        {
            var parser = new BaZicParser();

            var inputCode =
                @"EXTERN FUNCTION Main(args[])
    VARIABLE var1 = ""Hello"".Length
END FUNCTION";
            var interpreter = new BaZicInterpreter(parser.Parse(inputCode, true).Program);
            await interpreter.StartDebugAsync(true);

            var expectedLogs = @"[State] Ready
[State] Preparing
[Log] Reference assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' loaded in the application domain.
[Log] Reference assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' loaded in the application domain.
[Log] Reference assembly 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' loaded in the application domain.
[Log] Reference assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' loaded in the application domain.
[Log] Reference assembly 'Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' loaded in the application domain.
[Log] Reference assembly 'PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' loaded in the application domain.
[Log] Reference assembly 'PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' loaded in the application domain.
[Log] Reference assembly 'WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' loaded in the application domain.
[Log] Declaring global variables.
[Log] Program's entry point detected.
[State] Running
[Log] Preparing to invoke the method 'Main'.
[Log] Executing the argument values of the method.
[Log] Executing an expression of type 'ArrayCreationExpression'.
[Log] The expression returned the value 'BaZicProgramReleaseMode.ObservableDictionary' (BaZicProgramReleaseMode.ObservableDictionary (length: 0)).
[Log] Invoking the synchronous method 'Main'.
[Log] Variable 'args' declared. Default value : {Null}
[Log] Variable 'args' value set to : BaZicProgramReleaseMode.ObservableDictionary (BaZicProgramReleaseMode.ObservableDictionary (length: 0))
[Log] Registering labels.
[Log] Executing a statement of type 'VariableDeclaration'.
[Log] Executing an expression of type 'PropertyReferenceExpression'.
[Log] Getting the property ''Hello' (type:System.String).Length'.
[Log] Executing an expression of type 'PrimitiveExpression'.
[Log] The expression returned the value 'Hello' (System.String).
[Log] The expression returned the value '5' (System.Int32).
[Log] Variable 'var1' declared. Default value : 5 (System.Int32)
[Log] End of the execution of the method 'Main'. Returned value :  ({Null})
[State] Idle
";

            Assert.AreEqual(expectedLogs, interpreter.GetStateChangedHistoryString());



            inputCode =
                @"EXTERN FUNCTION Main(args[])
    VARIABLE var1 = ""Hello"".length
END FUNCTION";
            interpreter = new BaZicInterpreter(parser.Parse(inputCode, true).Program);
            await interpreter.StartDebugAsync(true);

            Assert.AreEqual("Unable to access to the property 'length' of the type 'System.String'.", interpreter.StateChangedHistory.Last().Error.Exception.InnerException.Message);
        }
コード例 #19
0
        public async Task ProgramInterpreterInvokeExternMethodUI12()
        {
            var parser = new BaZicParser();

            var inputCode =
                @"
VARIABLE globVar = 1

EXTERN FUNCTION Main(args[])
END FUNCTION

EXTERN FUNCTION Method1()
    DO WHILE TRUE
    LOOP
END FUNCTION";

            var xamlCode = @"
<Window xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" Name=""Window1"">
    <StackPanel>
        <Button Name=""Button1"" Content=""Hello""/>
    </StackPanel>
</Window>";

            using (var interpreter = new BaZicInterpreter(inputCode, xamlCode))
            {
                var t = interpreter.StartDebugAsync(true);
                t = interpreter.InvokeMethod(true, "Method1", true);

                await Task.Delay(3000);

                Assert.AreEqual(BaZicInterpreterState.Running, interpreter.State);

                await interpreter.Stop();

                Assert.AreEqual(BaZicInterpreterState.Stopped, interpreter.State);
            }

            using (var interpreter = new BaZicInterpreter(inputCode, xamlCode))
            {
                var errors = await interpreter.Build();

                Assert.IsNull(errors);

                var t = interpreter.StartReleaseAsync(true);
                t = interpreter.InvokeMethod(true, "Method1", true);

                await Task.Delay(10000);

                Assert.AreEqual(BaZicInterpreterState.Running, interpreter.State);

                await interpreter.Stop();

                Assert.AreEqual(BaZicInterpreterState.Stopped, interpreter.State);
            }
        }
コード例 #20
0
        public async Task VariableReferenceInterpreter()
        {
            var parser = new BaZicParser();

            var inputCode =
                @"EXTERN FUNCTION Main(args[])
    VARIABLE var1 = 1
    VARIABLE var2 = var1
    RETURN var2
END FUNCTION";
            var interpreter = new BaZicInterpreter(parser.Parse(inputCode, true).Program);
            await interpreter.StartDebugAsync(true);

            var expectedLogs = @"[State] Ready
[State] Preparing
[Log] Reference assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' loaded in the application domain.
[Log] Reference assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' loaded in the application domain.
[Log] Reference assembly 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' loaded in the application domain.
[Log] Reference assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' loaded in the application domain.
[Log] Reference assembly 'Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' loaded in the application domain.
[Log] Reference assembly 'PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' loaded in the application domain.
[Log] Reference assembly 'PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' loaded in the application domain.
[Log] Reference assembly 'WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' loaded in the application domain.
[Log] Declaring global variables.
[Log] Program's entry point detected.
[State] Running
[Log] Preparing to invoke the method 'Main'.
[Log] Executing the argument values of the method.
[Log] Executing an expression of type 'ArrayCreationExpression'.
[Log] The expression returned the value 'BaZicProgramReleaseMode.ObservableDictionary' (BaZicProgramReleaseMode.ObservableDictionary (length: 0)).
[Log] Invoking the synchronous method 'Main'.
[Log] Variable 'args' declared. Default value : {Null}
[Log] Variable 'args' value set to : BaZicProgramReleaseMode.ObservableDictionary (BaZicProgramReleaseMode.ObservableDictionary (length: 0))
[Log] Registering labels.
[Log] Executing a statement of type 'VariableDeclaration'.
[Log] Executing an expression of type 'PrimitiveExpression'.
[Log] The expression returned the value '1' (System.Int32).
[Log] Variable 'var1' declared. Default value : 1 (System.Int32)
[Log] Executing a statement of type 'VariableDeclaration'.
[Log] Executing an expression of type 'VariableReferenceExpression'.
[Log] The expression returned the value '1' (System.Int32).
[Log] Variable 'var2' declared. Default value : 1 (System.Int32)
[Log] Executing a statement of type 'ReturnStatement'.
[Log] Executing an expression of type 'VariableReferenceExpression'.
[Log] The expression returned the value '1' (System.Int32).
[Log] Return : 1 (System.Int32)
[Log] A Return statement or Break statement or Exception has been detected or thrown. Exiting the current block of statements.
[Log] End of the execution of the method 'Main'. Returned value : 1 (System.Int32)
[State] Idle
";

            Assert.AreEqual(expectedLogs, interpreter.GetStateChangedHistoryString());
            await TestUtilities.TestAllRunningMode("1", inputCode);
        }
コード例 #21
0
ファイル: ProgramInterpreter.cs プロジェクト: veler/BaZic
        /// <summary>
        /// Invoke a public method accessible from outside of the interpreter (EXTERN FUNCTION).
        /// </summary>
        /// <param name="executionFlowId">A GUID that defines in which callstack is linked.</param>
        /// <param name="methodName">The name of the method.</param>
        /// <param name="awaitIfAsync">Await if the method is maked as asynchronous.</param>
        /// <param name="args">The arguments to pass to the method.</param>
        /// <returns>Returns the result of the invocation (a <see cref="Task"/> in the case of a not awaited asynchronous method, or the value returned by the method).</returns>
        internal object InvokeMethod(Guid executionFlowId, string methodName, bool awaitIfAsync, Code.AbstractSyntaxTree.Expression[] args)
        {
            InitializeGlobalState();

            BaZicInterpreter.CheckState(BaZicInterpreterState.Idle, BaZicInterpreterState.Stopped, BaZicInterpreterState.StoppedWithError);

            var invokeExpression = new InvokeMethodExpression(methodName, awaitIfAsync).WithParameters(args);

            BaZicInterpreter.ChangeState(this, new BaZicInterpreterStateChangeEventArgs(BaZicInterpreterState.Running));

            return(new InvokeMethodInterpreter(BaZicInterpreter, this, invokeExpression, executionFlowId, true).Run());
        }
コード例 #22
0
ファイル: MethodInterpreterTest.cs プロジェクト: veler/BaZic
        public async Task MethodInterpreterAwait()
        {
            var parser = new BaZicParser();

            var inputCode =
                @"EXTERN FUNCTION Main(args[])
    AWAIT Main(NEW [1, 2, 3])
END FUNCTION";
            var interpreter = new BaZicInterpreter(parser.Parse(inputCode, true).Program);
            await interpreter.StartDebugAsync(true);

            Assert.AreEqual("Unable to await the method 'Main' because it is not marked as asynchronous.", interpreter.Error.Exception.Message);
        }
コード例 #23
0
        public async Task InvokeCoreMethodInterpreter3()
        {
            var parser = new BaZicParser();

            var inputCode =
                @"EXTERN FUNCTION Main(args[])
    VARIABLE var1 = 123.toString()
END FUNCTION";
            var interpreter = new BaZicInterpreter(parser.Parse(inputCode, true).Program);
            await interpreter.StartDebugAsync(true);

            Assert.AreEqual("The method 'toString' does not exist in the type 'System.Int32'.", interpreter.StateChangedHistory.Last().Error.Exception.InnerException.Message);
        }
コード例 #24
0
ファイル: BaZicInterpreterTest.cs プロジェクト: veler/BaZic
        public async Task BaZicInterpreterAssembliesLoad()
        {
            var program = new BaZicProgram();

            program.WithAssemblies("FakeAssembly, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

            var interpreter = new BaZicInterpreter(program);
            await interpreter.StartDebugAsync(true);

            var exception = (LoadAssemblyException)interpreter.Error.Exception;

            Assert.AreEqual("FakeAssembly, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", exception.AssemblyPath);
            Assert.AreEqual("Could not load file or assembly 'FakeAssembly, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified.", exception.InnerException.Message);
        }
コード例 #25
0
ファイル: ThrowInterpreter.cs プロジェクト: veler/BaZic
        /// <inheritdoc/>
        internal override void Run()
        {
            var expression = ParentInterpreter.RunExpression(Statement.Expression);

            var exception = expression as Exception;

            if (exception == null)
            {
                BaZicInterpreter.ChangeState(this, new BadTypeException(L.BaZic.Runtime.Interpreters.Statements.ThrowInterpreter.FormattedExceptionExpected(typeof(Exception).FullName)));
                return;
            }

            throw exception;
        }
コード例 #26
0
ファイル: BaZicInterpreterTest.cs プロジェクト: veler/BaZic
        public async Task BaZicInterpreterDebugInformation()
        {
            var parser = new BaZicParser();

            var inputCode =
                @"
VARIABLE globVar = ""Hello""

EXTERN FUNCTION Main(args[])
    RETURN SimpleRecursivity(5)
END FUNCTION

FUNCTION SimpleRecursivity(num)
    IF num < 1 THEN
        BREAKPOINT
        RETURN num
    ELSE
        RETURN SimpleRecursivity(num - 1)
    END IF
END FUNCTION";
            var interpreter = new BaZicInterpreter(parser.Parse(inputCode, true).Program);
            var t           = interpreter.StartDebugAsync(true);

            await Task.Delay(2000);

            var debugInfo = interpreter.DebugInfos;

            Assert.IsNull(debugInfo);
            Assert.AreEqual(BaZicInterpreterState.Pause, interpreter.State);


            interpreter = new BaZicInterpreter(parser.Parse(inputCode, false).Program);
            t           = interpreter.StartDebugAsync(true);

            Assert.IsNull(interpreter.DebugInfos);

            await Task.Delay(2000);

            debugInfo = interpreter.DebugInfos;

            Assert.IsNotNull(debugInfo);
            Assert.AreEqual(BaZicInterpreterState.Pause, interpreter.State);
            Assert.AreEqual(7, debugInfo.CallStack.Count);
            Assert.AreEqual(1, debugInfo.GlobalVariables.Count);
            Assert.AreEqual("SimpleRecursivity", debugInfo.CallStack.First().InvokeMethodExpression.MethodName.Identifier);
            Assert.AreEqual("num", debugInfo.CallStack.First().Variables.Single().Name);
            Assert.AreEqual(0, debugInfo.CallStack.First().Variables.Single().Value);
            Assert.AreEqual(5, debugInfo.CallStack[5].Variables.Single().Value);
        }
コード例 #27
0
ファイル: TestUtilities.cs プロジェクト: veler/BaZic
        internal static async Task RunDebugOptimizedVerbose(List <string> resultReceiver, string inputBaZicCode, string xamlCode, params object[] args)
        {
            using (var interpreter = new BaZicInterpreter(inputBaZicCode, xamlCode, optimize: true))
            {
                interpreter.SetDependencies("PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
                await interpreter.StartDebugAsync(true, args);

                if (interpreter.Error != null)
                {
                    throw interpreter.Error.Exception;
                }

                resultReceiver.Add(interpreter.ProgramResult?.ToString());
            }
        }
コード例 #28
0
        public async Task BinaryOperatorInterpreterDivision()
        {
            var parser = new BaZicParser();

            var inputCode =
                @"EXTERN FUNCTION Main(args[])
    VARIABLE var1 = 2 / 0 # Should fail
END FUNCTION";
            var interpreter = new BaZicInterpreter(parser.Parse(inputCode, true).Program);
            await interpreter.StartDebugAsync(true);

            var result = interpreter.GetStateChangedHistoryString();

            Assert.IsTrue(result.Contains("[Error] Attempted to divide by zero."));
        }
コード例 #29
0
        /// <inheritdoc/>
        internal override object Run()
        {
            var parentBlockInterpreter = ParentInterpreter as BlockInterpreter;

            if (parentBlockInterpreter == null)
            {
                BaZicInterpreter.ChangeState(this, new InternalException(L.BaZic.Runtime.Interpreters.Expressions.ExceptionInterpreter.BlockExpected), Expression);
            }

            if (parentBlockInterpreter.CaughtException == null)
            {
                BaZicInterpreter.ChangeState(this, new IncoherentStatementException(L.BaZic.Runtime.Interpreters.Expressions.ExceptionInterpreter.TryCatchExpected), Expression);
            }

            return(parentBlockInterpreter.CaughtException);
        }
コード例 #30
0
        public async Task ProgramInterpreterInvokeExternMethod11()
        {
            var parser = new BaZicParser();

            var inputCode =
                @"
VARIABLE globVar = 1

EXTERN FUNCTION Main(args[])
    DO WHILE TRUE
    LOOP
END FUNCTION

EXTERN FUNCTION Method1()
    RETURN TRUE
END FUNCTION";


            using (var interpreter = new BaZicInterpreter(parser.Parse(inputCode, false).Program))
            {
                var t = interpreter.StartDebugAsync(true);
                t = interpreter.InvokeMethod(true, "Method1", true);

                await Task.Delay(3000);

                Assert.AreEqual(BaZicInterpreterState.Running, interpreter.State);

                await interpreter.Stop();

                Assert.AreEqual(BaZicInterpreterState.Stopped, interpreter.State);
            }

            using (var interpreter = new BaZicInterpreter(parser.Parse(inputCode, false).Program))
            {
                var t = interpreter.StartReleaseAsync(true);
                t = interpreter.InvokeMethod(true, "Method1", true);

                await Task.Delay(10000);

                Assert.AreEqual(BaZicInterpreterState.Running, interpreter.State);

                await interpreter.Stop();

                Assert.AreEqual(BaZicInterpreterState.Stopped, interpreter.State);
            }
        }