Ejemplo n.º 1
0
Archivo: Io.cs Proyecto: macias/Skila
        public IInterpreter FileExists()
        {
            var interpreter = new Interpreter.Interpreter();

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Environment.Create(new Options()
                {
                    DebugThrowOnError = true, AllowInvalidMainResult = true
                }
                                             .SetMutability(mutability));
                var root_ns = env.Root;

                var main_func = root_ns.AddBuilder(FunctionBuilder.Create(
                                                       "main",
                                                       ExpressionReadMode.OptionalUse,
                                                       NameFactory.Int64NameReference(),
                                                       Block.CreateStatement(
                                                           VariableDeclaration.CreateStatement("e", null, FunctionCall.Create(NameReference.Create(NameFactory.FileNameReference(),
                                                                                                                                                   NameFactory.FileExists), StringLiteral.Create(randomTextFilePath))),
                                                           IfBranch.CreateIf(NameReference.Create("e"), new[] { Return.Create(Int64Literal.Create("2")) },
                                                                             IfBranch.CreateElse(new[] { Return.Create(Int64Literal.Create("-5")) }))
                                                           )));

                ExecValue result = interpreter.TestRun(env);

                Assert.AreEqual(2L, result.RetValue.PlainValue);
            }

            return(interpreter);
        }
Ejemplo n.º 2
0
        public IErrorReporter ReadingIfAsExpression()
        {
            NameResolver resolver = null;

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Environment.Create(new Options()
                {
                    GlobalVariables = true,
                    RelaxedMode     = true
                }.SetMutability(mutability));
                var root_ns = env.Root;

                var if_ctrl = IfBranch.CreateIf(BoolLiteral.CreateTrue(),
                                                new IExpression[] { Int64Literal.Create("5") },
                                                IfBranch.CreateElse(new[] { Int64Literal.Create("7") }));

                root_ns.AddNode(VariableDeclaration.CreateStatement("x", NameFactory.Int64NameReference(), if_ctrl, EntityModifier.Public));

                resolver = NameResolver.Create(env);

                Assert.AreEqual(0, resolver.ErrorManager.Errors.Count);
            }

            return(resolver);
        }
Ejemplo n.º 3
0
        public IInterpreter DereferenceOnIfCondition()
        {
            var interpreter = new Interpreter.Interpreter();

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Language.Environment.Create(new Options()
                {
                    DebugThrowOnError      = true,
                    AllowInvalidMainResult = true
                }.SetMutability(mutability));
                var root_ns = env.Root;

                var main_func = root_ns.AddBuilder(FunctionBuilder.Create(
                                                       "main",
                                                       ExpressionReadMode.OptionalUse,
                                                       NameFactory.Int64NameReference(),
                                                       Block.CreateStatement(new IExpression[] {
                    VariableDeclaration.CreateStatement("ptr", NameFactory.PointerNameReference(NameFactory.BoolNameReference()),
                                                        ExpressionFactory.HeapConstructor(NameFactory.BoolNameReference(), FunctionArgument.Create(BoolLiteral.CreateTrue()))),
                    Return.Create(IfBranch.CreateIf(NameReference.Create("ptr"), new[] { Int64Literal.Create("2") },
                                                    IfBranch.CreateElse(new[] { Int64Literal.Create("5") }))),
                })));


                ExecValue result = interpreter.TestRun(env);

                Assert.AreEqual(2L, result.RetValue.PlainValue);
            }

            return(interpreter);
        }
Ejemplo n.º 4
0
Archivo: Flow.cs Proyecto: macias/Skila
        public IInterpreter IfBranches()
        {
            var interpreter = new Interpreter.Interpreter();

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Language.Environment.Create(new Options()
                {
                    AllowInvalidMainResult = true
                }.SetMutability(mutability));
                var root_ns = env.Root;

                var main_func = root_ns.AddBuilder(FunctionBuilder.Create(
                                                       "main",
                                                       ExpressionReadMode.OptionalUse,
                                                       NameFactory.Int64NameReference(),
                                                       Block.CreateStatement(new IExpression[] {
                    IfBranch.CreateIf(BoolLiteral.CreateFalse(), new[] { Return.Create(Int64Literal.Create("5")) },
                                      IfBranch.CreateElse(new[] { Return.Create(Int64Literal.Create("2")) }))
                })));

                ExecValue result = interpreter.TestRun(env);

                Assert.AreEqual(2L, result.RetValue.PlainValue);
            }

            return(interpreter);
        }
        public override void Compile(CompileContext context)
        {
            if (context.Options.Optimize && !ElseBranch.IsUsed)
            {
                IfBranch.Compile(context);
                return;
            }
            else if (context.Options.Optimize && !IfBranch.IsUsed)
            {
                ElseBranch.Compile(context);
                return;
            }
            Label elseStart = context.ILGenerator.DefineLabel();
            Label elseEnd   = context.ILGenerator.DefineLabel();

            context.MarkSequencePoint(Expression.LexicalInfo);
            this.Expression.Compile(context);
            context.ILGenerator.Emit(OpCodes.Brfalse, elseStart);
            IfBranch.Compile(context);
            context.ILGenerator.Emit(OpCodes.Br, elseEnd);
            context.ILGenerator.MarkLabel(elseStart);
            ElseBranch.Compile(context);
            context.ILGenerator.MarkLabel(elseEnd);
            if (context.Options.Debug && ElseBranch.LexicalInfo.EndLine != 0)
            {
                LexicalInfo l = ElseBranch.LexicalInfo;
                context.ILGenerator.MarkSequencePoint(context.DebugWriter, l.EndLine, l.EndColumn + 1, l.EndLine, l.EndColumn + 1);
            }
        }
Ejemplo n.º 6
0
        /// <summary cref="IBackendCodeGenerator.GenerateCode(IfBranch)"/>
        public void GenerateCode(IfBranch branch)
        {
            // TODO: refactor if-block generation into a separate emitter
            // See also EmitImplicitKernelIndex

            var condition = Load(branch.Condition);

            if (condition is ConstantVariable constantVariable)
            {
                if (constantVariable.Value.RawValue != 0)
                {
                    GotoStatement(branch.TrueTarget);
                }
                else
                {
                    GotoStatement(branch.FalseTarget);
                }
            }
            else
            {
                AppendIndent();
                Builder.Append("if (");
                Builder.Append(condition.ToString());
                Builder.AppendLine(")");
                PushIndent();
                GotoStatement(branch.TrueTarget);
                PopIndent();
                GotoStatement(branch.FalseTarget);
            }
        }
Ejemplo n.º 7
0
        public IInterpreter Indexer()
        {
            var interpreter = new Interpreter.Interpreter();

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Language.Environment.Create(new Options()
                {
                    AllowInvalidMainResult = true,
                    DebugThrowOnError      = true
                }.SetMutability(mutability));
                var root_ns = env.Root;

                IEnumerable <FunctionParameter> property_parameters = new[] { FunctionParameter.Create("idx", NameFactory.Int64NameReference()) };
                NameReference property_typename = NameFactory.Int64NameReference();

                var point_type = root_ns.AddBuilder(TypeBuilder.Create("Point")
                                                    .SetModifier(EntityModifier.Mutable)
                                                    .With(Property.CreateIndexer(env.Options, property_typename,
                                                                                 new[] { VariableDeclaration.CreateStatement("x", NameFactory.Int64NameReference(), Int64Literal.Create("1"),
                                                                                                                             env.Options.ReassignableModifier()) },
                                                                                 new[] { Property.CreateIndexerGetter(property_typename, property_parameters,
                                                                                                                      Block.CreateStatement(IfBranch.CreateIf(ExpressionFactory.IsEqual(NameReference.Create("idx"), Int64Literal.Create("17")), new[] {
                        Return.Create(NameReference.CreateThised("x"))
                    }, IfBranch.CreateElse(new[] {
                        Return.Create(Int64Literal.Create("300"))
                    })))) },
                                                                                 new[] { Property.CreateIndexerSetter(property_typename, property_parameters,
                                                                                                                      Block.CreateStatement(IfBranch.CreateIf(ExpressionFactory.IsEqual(NameReference.Create("idx"), Int64Literal.Create("17")), new[] {
                        Assignment.CreateStatement(NameReference.CreateThised("x"),
                                                   NameReference.Create(NameFactory.PropertySetterValueParameter))
                    }))) }
                                                                                 )));

                var main_func = root_ns.AddBuilder(FunctionBuilder.Create(
                                                       "main",
                                                       ExpressionReadMode.OptionalUse,
                                                       NameFactory.Int64NameReference(),
                                                       Block.CreateStatement(new IExpression[] {
                    // p = Point() // p.x is initialized with 1
                    VariableDeclaration.CreateStatement("p", null, ExpressionFactory.StackConstructor(NameReference.Create("Point"))),
                    // p[17] = 1+p[17]
                    Assignment.CreateStatement(FunctionCall.Indexer(NameReference.Create("p"),
                                                                    FunctionArgument.Create(Int64Literal.Create("17"))),
                                               FunctionCall.Create(NameReference.Create(Int64Literal.Create("1"), NameFactory.AddOperator),
                                                                   FunctionArgument.Create(FunctionCall.Indexer(NameReference.Create("p"),
                                                                                                                FunctionArgument.Create(Int64Literal.Create("17")))))),
                    // return p[17]
                    Return.Create(FunctionCall.Indexer(NameReference.Create("p"),
                                                       FunctionArgument.Create(Int64Literal.Create("17"))))
                })));

                ExecValue result = interpreter.TestRun(env);

                Assert.AreEqual(2L, result.RetValue.PlainValue);
            }

            return(interpreter);
        }
Ejemplo n.º 8
0
        /// <summary>
        ///     Called when the mocked method is called.
        ///     This implementation will select the alternative branch if the condition evaluates to <c>true</c>.
        /// </summary>
        /// <param name="mockInfo">Information about the mock through which the method is called.</param>
        /// <param name="param">The parameters used.</param>
        /// <returns>The returned result.</returns>
        public override TResult Call(IMockInfo mockInfo, ValueTuple param)
        {
            if (_condition?.Invoke(mockInfo.MockInstance) ?? false)
            {
                return(IfBranch.Call(mockInfo, param));
            }

            return(base.Call(mockInfo, param));
        }
Ejemplo n.º 9
0
        /// <summary>
        ///     Called when a value is read from the property.
        ///     This implementation will select the alternative branch if the get condition evaluates to <c>true</c>.
        /// </summary>
        /// <param name="mockInfo">Information about the mock through which the value is read.</param>
        /// <returns>The value being read.</returns>
        public override TValue Get(IMockInfo mockInfo)
        {
            if (_getCondition?.Invoke() ?? false)
            {
                return(IfBranch.Get(mockInfo));
            }

            return(base.Get(mockInfo));
        }
Ejemplo n.º 10
0
        /// <summary>
        ///     Called when a value is read from the indexer.
        ///     This implementation will select the alternative branch if the get condition evaluates to <c>true</c>.
        /// </summary>
        /// <param name="mockInfo">Information about the mock through which the value is read.</param>
        /// <param name="key">The indexer key used.</param>
        /// <returns>The value being read.</returns>
        public override TValue Get(IMockInfo mockInfo, TKey key)
        {
            if (_getCondition?.Invoke(mockInfo.MockInstance, key) ?? false)
            {
                return(IfBranch.Get(mockInfo, key));
            }

            return(base.Get(mockInfo, key));
        }
Ejemplo n.º 11
0
        public override string ToString()
        {
            string s = string.Format("if {0} then\n{1}", Expression, Indent(IfBranch.ToString()));

            if (ElseBranch != null)
            {
                s += string.Format("\nelse\n{0}", Indent(ElseBranch.ToString()));
            }
            s += "\nfi";
            return(s);
        }
Ejemplo n.º 12
0
 /// <summary>
 ///     Called when a value is written to the indexer.
 ///     This implementation will select the alternative branch if the set condition evaluates to <c>true</c>.
 /// </summary>
 /// <param name="mockInfo">Information about the mock through which the value is written.</param>
 /// <param name="key">The indexer key used.</param>
 /// <param name="value">The value being written.</param>
 public override void Set(IMockInfo mockInfo, TKey key, TValue value)
 {
     if (_setCondition?.Invoke(mockInfo.MockInstance, key, value) ?? false)
     {
         IfBranch.Set(mockInfo, key, value);
     }
     else
     {
         base.Set(mockInfo, key, value);
     }
 }
Ejemplo n.º 13
0
 /// <summary>
 ///     Called when an event handler is being removed from the mocked event.
 ///     This implementation will select the alternative branch if the remove condition evaluates to <c>true</c>.
 /// </summary>
 /// <param name="mockInfo">Information about the mock through which the event handler is being removed.</param>
 /// <param name="value">The event handler that is being removed.</param>
 public override void Remove(IMockInfo mockInfo, THandler?value)
 {
     if (_removeCondition?.Invoke(value) ?? false)
     {
         IfBranch.Remove(mockInfo, value);
     }
     else
     {
         base.Remove(mockInfo, value);
     }
 }
Ejemplo n.º 14
0
 /// <summary>
 ///     Called when an event handler is being added to the mocked event.
 ///     This implementation will select the alternative branch if the add condition evaluates to <c>true</c>.
 /// </summary>
 /// <param name="mockInfo">Information about the mock through which the event handler is being added.</param>
 /// <param name="value">The event handler that is being added.</param>
 public override void Add(IMockInfo mockInfo, THandler?value)
 {
     if (_addCondition?.Invoke(value) ?? false)
     {
         IfBranch.Add(mockInfo, value);
     }
     else
     {
         base.Add(mockInfo, value);
     }
 }
Ejemplo n.º 15
0
Archivo: Flow.cs Proyecto: macias/Skila
        public IInterpreter InitializationWithOptionalAssignment()
        {
            var interpreter = new Interpreter.Interpreter();

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Language.Environment.Create(new Options()
                {
                    DebugThrowOnError = true,
                    DiscardingAnyExpressionDuringTests = true,
                }.SetMutability(mutability));
                var root_ns = env.Root;

                // this test is a bit tougher than regular opt.assignment, because variables will be
                // initialized for the first time with this assigment
                root_ns.AddBuilder(FunctionBuilder.Create("main",
                                                          ExpressionReadMode.OptionalUse,
                                                          NameFactory.Nat8NameReference(),
                                                          Block.CreateStatement(
                                                              VariableDeclaration.CreateStatement("acc", null, Nat8Literal.Create("0"), env.Options.ReassignableModifier()),


                                                              VariableDeclaration.CreateStatement("x", null,
                                                                                                  ExpressionFactory.OptionOf(NameFactory.Nat8NameReference(), Nat8Literal.Create("3"))),
                                                              VariableDeclaration.CreateStatement("z", null,
                                                                                                  ExpressionFactory.OptionOf(NameFactory.Nat8NameReference(), Nat8Literal.Create("5"))),

                                                              VariableDeclaration.CreateStatement("a", NameFactory.Nat8NameReference(), null, env.Options.ReassignableModifier()),
                                                              VariableDeclaration.CreateStatement("b", NameFactory.Nat8NameReference(), null, env.Options.ReassignableModifier()),

                                                              IfBranch.CreateIf(ExpressionFactory.OptionalAssignment(
                                                                                    new[] { NameReference.Create("a"), NameReference.Create("b") },
                                                                                    new[] { NameReference.Create("x"), NameReference.Create("z") }),
                                                                                new[] {
                    // assign tracker should recognize the variable is initialized
                    ExpressionFactory.IncBy("acc", NameReference.Create("a")),
                },
                                                                                // making else branch a dead one
                                                                                IfBranch.CreateElse(ExpressionFactory.GenericThrow())),

                                                              // assign tracker should recognize the variable is initialized (because `else` branch of above `if` is dead)
                                                              ExpressionFactory.IncBy("acc", NameReference.Create("b")),

                                                              Return.Create(NameReference.Create("acc"))
                                                              )));

                ExecValue result = interpreter.TestRun(env);

                Assert.AreEqual((byte)8, result.RetValue.PlainValue);
            }

            return(interpreter);
        }
Ejemplo n.º 16
0
        public static IExpression DownCast(IExpression lhs, INameReference rhsTypeName)
        {
            // if the expression is not of the given type we get null
            // if it is the runtime type IS PRESERVED
            // say you have statically types object
            // x *Object
            // and in runtime x is Orange
            // if you cast it to Vehicle you will get null, when you cast it to Fruit you will get Orange (sic!)
            IExpression condition = IsType.Create(lhs, rhsTypeName);
            IExpression success   = ExpressionFactory.StackConstructor(NameFactory.OptionNameReference(rhsTypeName),
                                                                       FunctionArgument.Create(ReinterpretType.Create(lhs, rhsTypeName)));
            IExpression failure = ExpressionFactory.StackConstructor(NameFactory.OptionNameReference(rhsTypeName));

            return(IfBranch.CreateIf(condition, new[] { success }, IfBranch.CreateElse(new[] { failure })));
        }
Ejemplo n.º 17
0
        /// <summary cref="IBackendCodeGenerator.GenerateCode(IfBranch)"/>
        public void GenerateCode(IfBranch branch)
        {
            var primitiveCondition = LoadPrimitive(branch.Condition);
            var condition          = EnsureHardwareRegister(primitiveCondition);

            // Use the actual branch targets from the schedule
            var(trueTarget, falseTarget) = branch.NotInvertedBranchTargets;

            // Determine the branch operation to be used
            var branchOperation = Uniforms.IsUniform(branch)
                ? PTXInstructions.UniformBranchOperation
                : PTXInstructions.BranchOperation;

            // The current schedule has inverted all if conditions with implicit branch
            // targets to simplify the work of the PTX assembler
            if (Schedule.IsImplicitSuccessor(branch.BasicBlock, trueTarget))
            {
                // Jump to false target in the else case
                using var command = BeginCommand(
                          branchOperation,
                          new PredicateConfiguration(
                              condition,
                              isTrue: branch.IsInverted));
                var targetLabel = blockLookup[falseTarget];
                command.AppendLabel(targetLabel);
            }
            else
            {
                if (branch.IsInverted)
                {
                    Utilities.Swap(ref trueTarget, ref falseTarget);
                }
                using (var command = BeginCommand(
                           branchOperation,
                           new PredicateConfiguration(condition, isTrue: true)))
                {
                    var targetLabel = blockLookup[trueTarget];
                    command.AppendLabel(targetLabel);
                }

                // Jump to false target in the else case
                using (var command = BeginCommand(PTXInstructions.UniformBranchOperation))
                {
                    var targetLabel = blockLookup[falseTarget];
                    command.AppendLabel(targetLabel);
                }
            }
        }
Ejemplo n.º 18
0
        public override void Compile(ILGenerator il)
        {
            EmitDebugInfo(il, 0, false);
            Expression.Compile(il);
            Label ifFalseLabel = il.DefineLabel();
            Label endLabel     = il.DefineLabel();

            il.Emit(OpCodes.Brfalse, ifFalseLabel);
            IfBranch.Compile(il);
            il.Emit(OpCodes.Br, endLabel);
            il.MarkLabel(ifFalseLabel);
            if (ElseBranch != null)
            {
                ElseBranch.Compile(il);
            }
            il.MarkLabel(endLabel);
        }
Ejemplo n.º 19
0
        public override void GenerateIntermediateCode()
        {
            //номер условного оператора, нужен для формирования меток
            int num_if = ++Counters.ifs;

            Condition.GenerateIntermediateCode();
            //то, что получилось, сравниваем с нулём
            if (Condition.MainVariable.Type == "int")
            {
                IntermediateCodeList.push(new CmpNode(Condition.MainVariable, new ConstantNode("int", "0", 0).MainVariable));
            }
            else if (Condition.MainVariable.Type == "bool")
            {
                IntermediateCodeList.push(new CmpNode(Condition.MainVariable, new ConstantNode("bool", "false", 0).MainVariable));
            }
            else
            {
                Console.WriteLine("Что-то не так с типами");
            }

            if (ElseBranch == null)
            {
                //если else-ветки нет, формируем метку на выход, если условие не выполнено
                //если равно нулю, то условие ложно и уходим
                IntermediateCodeList.push(new GoToLabel("exit_if_" + num_if.ToString(), "je"));
            }
            else
            {
                //если вторая ветка есть, формируем метку на неё
                IntermediateCodeList.push(new GoToLabel("else_" + num_if.ToString(), "je"));
            }
            //генерим код для if-ветки, она будет в любом случае
            IfBranch.GenerateIntermediateCode();
            //если есть вторая ветка, надо сгенерить код для неё
            if (ElseBranch != null)
            {
                //из if-ветки отправляем на выход
                IntermediateCodeList.push(new GoToLabel("exit_if_" + num_if.ToString(), "jmp"));
                //ставим метку else
                IntermediateCodeList.push(new PutLabel("else_" + num_if.ToString()));
                //Генерируем код else-ветки
                ElseBranch.GenerateIntermediateCode();
            }
            //ставим метку на выход
            IntermediateCodeList.push(new PutLabel("exit_if_" + num_if.ToString()));
        }
Ejemplo n.º 20
0
 public static TypeBuilder WithComparableCompare(this TypeBuilder builder, EntityModifier modifier = null)
 {
     return(builder.With(FunctionBuilder.Create(NameFactory.ComparableCompare,
                                                ExpressionReadMode.ReadRequired, NameFactory.OrderingNameReference(),
                                                Block.CreateStatement(
                                                    IfBranch.CreateIf(IsSame.Create(NameReference.CreateThised(), NameReference.Create("cmp")),
                                                                      new[] { Return.Create(NameFactory.OrderingEqualReference()) }),
                                                    // let obj = cmp cast? Self
                                                    VariableDeclaration.CreateStatement("obj", null, ExpressionFactory.CheckedSelfCast("cmp",
                                                                                                                                       NameFactory.ReferenceNameReference(builder.CreateTypeNameReference(TypeMutability.ReadOnly)))),
                                                    // return this.compare(obj.value)
                                                    Return.Create(FunctionCall.Create(NameReference.CreateThised(NameFactory.ComparableCompare),
                                                                                      NameReference.Create("obj")))))
                         .SetModifier(EntityModifier.Override | modifier)
                         .Parameters(FunctionParameter.Create("cmp",
                                                              NameFactory.ReferenceNameReference(NameFactory.IComparableNameReference(TypeMutability.ReadOnly))))));
 }
Ejemplo n.º 21
0
 public static TypeBuilder WithEquatableEquals(this TypeBuilder builder, EntityModifier modifier = null)
 {
     return(builder.With(FunctionBuilder.Create(NameFactory.EqualOperator,
                                                ExpressionReadMode.ReadRequired, NameFactory.BoolNameReference(),
                                                Block.CreateStatement(
                                                    IfBranch.CreateIf(IsSame.Create(NameReference.CreateThised(), NameReference.Create("cmp")),
                                                                      new[] { Return.Create(BoolLiteral.CreateTrue()) }),
                                                    // let obj = cmp cast? Self
                                                    VariableDeclaration.CreateStatement("obj", null, ExpressionFactory.CheckedSelfCast("cmp",
                                                                                                                                       NameFactory.ReferenceNameReference(builder.CreateTypeNameReference(TypeMutability.ReadOnly)))),
                                                    // return this==obj.value
                                                    Return.Create(ExpressionFactory.IsEqual(NameReference.Create(NameFactory.ThisVariableName),
                                                                                            NameReference.Create("obj")))))
                         .SetModifier(EntityModifier.Override | modifier)
                         .Parameters(FunctionParameter.Create("cmp",
                                                              NameFactory.ReferenceNameReference(NameFactory.IEquatableNameReference(TypeMutability.ReadOnly))))));
 }
Ejemplo n.º 22
0
        public IInterpreter TestingSamePointers()
        {
            var interpreter = new Interpreter.Interpreter();

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Language.Environment.Create(new Options()
                {
                    AllowInvalidMainResult             = true,
                    DebugThrowOnError                  = true,
                    DiscardingAnyExpressionDuringTests = true
                }.SetMutability(mutability));
                var root_ns = env.Root;


                var main_func = root_ns.AddBuilder(FunctionBuilder.Create(
                                                       "main",
                                                       ExpressionReadMode.OptionalUse,
                                                       NameFactory.Int64NameReference(),
                                                       Block.CreateStatement(new IExpression[] {
                    VariableDeclaration.CreateStatement("x", null,
                                                        ExpressionFactory.HeapConstructor(NameFactory.Int64NameReference(), Int64Literal.Create("2"))),
                    VariableDeclaration.CreateStatement("y", null, NameReference.Create("x")),
                    VariableDeclaration.CreateStatement("z", null,
                                                        ExpressionFactory.HeapConstructor(NameFactory.Int64NameReference(), Int64Literal.Create("2"))),
                    VariableDeclaration.CreateStatement("acc", null, Int64Literal.Create("0"), env.Options.ReassignableModifier()),
                    IfBranch.CreateIf(IsSame.Create(NameReference.Create("x"), NameReference.Create("y")), new[] {
                        Assignment.CreateStatement(NameReference.Create("acc"),
                                                   ExpressionFactory.Add(NameReference.Create("acc"), Int64Literal.Create("2")))
                    }),
                    IfBranch.CreateIf(IsSame.Create(NameReference.Create("x"), NameReference.Create("z")), new[] {
                        Assignment.CreateStatement(NameReference.Create("acc"),
                                                   ExpressionFactory.Add(NameReference.Create("acc"), Int64Literal.Create("7")))
                    }),
                    Return.Create(NameReference.Create("acc"))
                })));

                ExecValue result = interpreter.TestRun(env);

                Assert.AreEqual(2L, result.RetValue.PlainValue);
            }

            return(interpreter);
        }
Ejemplo n.º 23
0
        public IInterpreter ResolvingGenericArgumentInRuntime()
        {
            var interpreter = new Interpreter.Interpreter();

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Environment.Create(new Options()
                {
                    DebugThrowOnError = true
                }.SetMutability(mutability));
                var root_ns = env.Root;

                root_ns.AddBuilder(FunctionBuilder.Create("oracle", "O", VarianceMode.None,
                                                          NameFactory.BoolNameReference(),
                                                          Block.CreateStatement(
                                                              Return.Create(IsType.Create(NameReference.Create("thing"), NameReference.Create("O")))
                                                              ))
                                   .Parameters(FunctionParameter.Create("thing", NameFactory.ReferenceNameReference(NameFactory.IObjectNameReference()))));

                root_ns.AddBuilder(FunctionBuilder.Create(
                                       "main",
                                       ExpressionReadMode.OptionalUse,
                                       NameFactory.Nat8NameReference(),
                                       Block.CreateStatement(
                                           VariableDeclaration.CreateStatement("acc", null, Nat8Literal.Create("0"), env.Options.ReassignableModifier()),
                                           VariableDeclaration.CreateStatement("i", null, ExpressionFactory.HeapConstructor(NameFactory.IntNameReference(), IntLiteral.Create("7"))),
                                           VariableDeclaration.CreateStatement("d", null, ExpressionFactory.HeapConstructor(NameFactory.RealNameReference(), RealLiteral.Create("3.3"))),
                                           IfBranch.CreateIf(FunctionCall.Create(NameReference.Create("oracle", NameFactory.IntNameReference()),
                                                                                 NameReference.Create("i")),
                                                             new[] { ExpressionFactory.IncBy("acc", Nat8Literal.Create("2")) }),
                                           IfBranch.CreateIf(FunctionCall.Create(NameReference.Create("oracle", NameFactory.IntNameReference()),
                                                                                 NameReference.Create("d")),
                                                             new[] { ExpressionFactory.IncBy("acc", Nat8Literal.Create("88")) }),
                                           Return.Create(NameReference.Create("acc"))
                                           )));

                ExecValue result = interpreter.TestRun(env);

                Assert.AreEqual((byte)2, result.RetValue.PlainValue);
            }

            return(interpreter);
        }
Ejemplo n.º 24
0
        public IInterpreter ClosureRecursiveCall()
        {
            var interpreter = new Interpreter.Interpreter();

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Environment.Create(new Options()
                {
                    DebugThrowOnError = true
                }.SetMutability(mutability));
                var root_ns = env.Root;

                IExpression        i_eq_jack = ExpressionFactory.IsEqual(NameReference.Create("i"), NameReference.Create("jack"));
                IExpression        i_add_1   = ExpressionFactory.Add(NameReference.Create("i"), Nat8Literal.Create("1"));
                FunctionDefinition lambda    = FunctionBuilder.CreateLambda(NameFactory.Nat8NameReference(),
                                                                            Block.CreateStatement(new[] {
                    // if i==jack then return i
                    IfBranch.CreateIf(i_eq_jack, new[] { Return.Create(NameReference.Create("i")) },
                                      // else return self(i+1)
                                      IfBranch.CreateElse(new[] {
                        Return.Create(FunctionCall.Create(NameReference.Create(NameFactory.RecurFunctionName),
                                                          FunctionArgument.Create(i_add_1)))
                    }))
                }))
                                               .Parameters(FunctionParameter.Create("i", NameFactory.Nat8NameReference()));

                root_ns.AddBuilder(FunctionBuilder.Create(
                                       "main",
                                       ExpressionReadMode.OptionalUse,
                                       NameFactory.Nat8NameReference(),
                                       Block.CreateStatement(new IExpression[] {
                    VariableDeclaration.CreateStatement("jack", null, Nat8Literal.Create("50")),
                    // Immediately-Invoked Function Expression (IIEFE) in Javascript world
                    Return.Create(FunctionCall.Create(lambda, FunctionArgument.Create(Nat8Literal.Create("0"))))
                })));

                ExecValue result = interpreter.TestRun(env);

                Assert.AreEqual((byte)50, result.RetValue.PlainValue);
            }

            return(interpreter);
        }
Ejemplo n.º 25
0
        public IInterpreter RecursiveCall()
        {
            var interpreter = new Interpreter.Interpreter();

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Environment.Create(new Options()
                {
                    AllowInvalidMainResult = true
                }.SetMutability(mutability));
                var root_ns = env.Root;

                IExpression i_eq_2  = ExpressionFactory.IsEqual(NameReference.Create("i"), Int64Literal.Create("2"));
                IExpression i_add_1 = ExpressionFactory.Add(NameReference.Create("i"), Int64Literal.Create("1"));
                root_ns.AddBuilder(FunctionBuilder.Create("foo",
                                                          ExpressionReadMode.OptionalUse,
                                                          NameFactory.Int64NameReference(),
                                                          Block.CreateStatement(new[] {
                    // if i==2 then return i
                    IfBranch.CreateIf(i_eq_2, new[] { Return.Create(NameReference.Create("i")) },
                                      // else return self(i+1)
                                      IfBranch.CreateElse(new[] {
                        Return.Create(FunctionCall.Create(NameReference.Create(NameFactory.RecurFunctionName),
                                                          FunctionArgument.Create(i_add_1)))
                    }))
                }))
                                   .Parameters(FunctionParameter.Create("i", NameFactory.Int64NameReference())));

                root_ns.AddBuilder(FunctionBuilder.Create(
                                       "main",
                                       ExpressionReadMode.OptionalUse,
                                       NameFactory.Int64NameReference(),
                                       Block.CreateStatement(new IExpression[] {
                    Return.Create(FunctionCall.Create(NameReference.Create("foo"), FunctionArgument.Create(Int64Literal.Create("0"))))
                })));

                ExecValue result = interpreter.TestRun(env);

                Assert.AreEqual(2L, result.RetValue.PlainValue);
            }

            return(interpreter);
        }
Ejemplo n.º 26
0
        public IErrorReporter ErrorIfScope()
        {
            NameResolver resolver = null;

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Environment.Create(new Options()
                {
                    DiscardingAnyExpressionDuringTests = true,
                }.SetMutability(mutability));
                var root_ns = env.Root;

                NameReference bad_ref = NameReference.Create("x");

                root_ns.AddBuilder(FunctionBuilder.Create(
                                       "testing",
                                       NameFactory.UnitNameReference(),

                                       Block.CreateStatement(
                                           VariableDeclaration.CreateStatement("b", NameFactory.BoolNameReference(), Undef.Create(),
                                                                               env.Options.ReassignableModifier()),

                                           IfBranch.CreateIf(VariableDeclaration.CreateExpression("x", null, BoolLiteral.CreateTrue()),
                                                             // x is in scope
                                                             Assignment.CreateStatement("b", "x"),
                                                             IfBranch.CreateElse(
                                                                 // x is in scope as well
                                                                 Assignment.CreateStatement("b", "x"))),

                                           // here x is not in the scope (is already removed)
                                           Assignment.CreateStatement(NameReference.Create("b"), bad_ref),
                                           ExpressionFactory.Readout("b")
                                           )));

                resolver = NameResolver.Create(env);

                Assert.AreEqual(1, resolver.ErrorManager.Errors.Count);
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.ReferenceNotFound, bad_ref));
            }

            return(resolver);
        }
Ejemplo n.º 27
0
        public override bool SemanticAnalysis()
        {
            IsSemanticCorrect = true;
            try
            {
                IsSemanticCorrect &= Condition.SemanticAnalysis();
            }
            catch (SemanticException e)
            {
                Console.WriteLine(e.Message);
                IsSemanticCorrect = false;
            }

            try
            {
                IsSemanticCorrect &= IfBranch.SemanticAnalysis();
            }
            catch
            {
                IsSemanticCorrect = false;
            }

            if (ElseBranch != null)
            {
                try
                {
                    IsSemanticCorrect = ElseBranch.SemanticAnalysis();
                }
                catch (SemanticException e)
                {
                    Console.WriteLine(e.Message);
                    IsSemanticCorrect = false;
                }
            }

            IfBranch.CheckVariables();
            if (ElseBranch != null)
            {
                ElseBranch.CheckVariables();
            }
            return(IsSemanticCorrect);
        }
Ejemplo n.º 28
0
        /// <summary cref="IBackendCodeGenerator.GenerateCode(IfBranch)"/>
        public void GenerateCode(IfBranch branch)
        {
            var primitiveCondition = LoadPrimitive(branch.Condition);
            var condition          = EnsureHardwareRegister(primitiveCondition);

            using (var command = BeginCommand(
                       PTXInstructions.BranchOperation,
                       new PredicateConfiguration(condition, true)))
            {
                var trueLabel = blockLookup[branch.TrueTarget];
                command.AppendLabel(trueLabel);
            }

            // Jump to false target in the else case
            using (var command = BeginCommand(PTXInstructions.BranchOperation))
            {
                var targetLabel = blockLookup[branch.FalseTarget];
                command.AppendLabel(targetLabel);
            }
        }
Ejemplo n.º 29
0
        public IErrorReporter ErrorCannotInferResultType()
        {
            NameResolver resolver = null;

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Environment.Create(new Options()
                {
                    DiscardingAnyExpressionDuringTests = true
                }.SetMutability(mutability));
                var root_ns = env.Root;

                IExpression lambda = FunctionBuilder.CreateLambda(null,
                                                                  Block.CreateStatement(new IExpression[] {
                    IfBranch.CreateIf(BoolLiteral.CreateFalse(), new[] {
                        Return.Create(BoolLiteral.CreateTrue())
                    }),
                    Return.Create(Int64Literal.Create("2"))
                })).Build();
                root_ns.AddBuilder(FunctionBuilder.Create("me",
                                                          ExpressionReadMode.OptionalUse,
                                                          NameFactory.UnitNameReference(),

                                                          Block.CreateStatement(new IExpression[] {
                    // f = () => x
                    VariableDeclaration.CreateStatement("f", null, lambda),
                    ExpressionFactory.Readout("f")
                })));


                resolver = NameResolver.Create(env);

                Assert.AreEqual(1, resolver.ErrorManager.Errors.Count);
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.CannotInferResultType, lambda));
            }

            return(resolver);
        }
Ejemplo n.º 30
0
Archivo: Flow.cs Proyecto: macias/Skila
        public IInterpreter ParallelOptionalDeclaration()
        {
            var interpreter = new Interpreter.Interpreter();

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Language.Environment.Create(new Options()
                {
                    DebugThrowOnError = true,
                }.SetMutability(mutability));
                var root_ns = env.Root;

                IExpression opt_declaration = ExpressionFactory.OptionalDeclaration(new[] {
                    VariablePrototype.Create("x", NameFactory.Nat8NameReference()),
                    VariablePrototype.Create("y", NameFactory.Nat8NameReference())
                }, new[] {
                    ExpressionFactory.OptionOf(NameFactory.Nat8NameReference(), Nat8Literal.Create("2")),
                    ExpressionFactory.OptionOf(NameFactory.Nat8NameReference(), Nat8Literal.Create("7")),
                });

                root_ns.AddBuilder(FunctionBuilder.Create("main",
                                                          ExpressionReadMode.OptionalUse,
                                                          NameFactory.Nat8NameReference(),
                                                          Block.CreateStatement(
                                                              IfBranch.CreateIf(opt_declaration,
                                                                                Return.Create(ExpressionFactory.Add("x", "y")),
                                                                                IfBranch.CreateElse(
                                                                                    ExpressionFactory.GenericThrow()
                                                                                    ))
                                                              )));

                ExecValue result = interpreter.TestRun(env);

                Assert.AreEqual((byte)9, result.RetValue.PlainValue);
            }

            return(interpreter);
        }