Ejemplo n.º 1
0
        private void createNewConstructors()
        {
            NameReference type_name = this.Name.CreateNameReference(null, this.InstanceOf, isLocal: true);

            if (!this.NestedFunctions.Any(it => it.IsNewConstructor()))
            {
                foreach (FunctionDefinition init_cons in this.NestedFunctions.Where(it => it.IsInitConstructor()).StoreReadOnly())
                {
                    //if (this.NestedFunctions.Any(it => it.IsNewConstructor()
                    //      && it.Name.Arity == init_cons.Name.Arity && it.NOT_USED_CounterpartParameters(init_cons)))
                    //continue;

                    const string local_this = "__this__";

                    var new_cons = FunctionDefinition.CreateHeapConstructor(init_cons.Modifier, init_cons.Parameters,
                                                                            type_name,
                                                                            Block.CreateStatement(new IExpression[] {
                        VariableDeclaration.CreateStatement(local_this, null, Alloc.Create(type_name, useHeap: true)),
                        FunctionCall.Create(NameReference.Create(NameReference.Create(local_this), NameFactory.InitConstructorName),
                                            init_cons.Parameters.Select(it => FunctionArgument.Create(it.Name.CreateNameReference())).ToArray()),
                        Return.Create(NameReference.Create(local_this))
                    }));

                    this.AddNode(new_cons);
                }
            }
        }
Ejemplo n.º 2
0
        public IInterpreter RawMethods()
        {
            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[] {
                    Return.Create(FunctionCall.Create(NameReference.Create(Int64Literal.Create("1"), NameFactory.AddOperator),
                                                      FunctionArgument.Create(Int64Literal.Create("1"))))
                })));

                ExecValue result = interpreter.TestRun(env);

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

            return(interpreter);
        }
Ejemplo n.º 3
0
        public IErrorReporter ErrorIgnoringFunctionResult()
        {
            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 func_def = root_ns.AddBuilder(FunctionBuilder.Create(
                                                      "foo",
                                                      ExpressionReadMode.ReadRequired,
                                                      NameFactory.RealNameReference(),
                                                      Block.CreateStatement(new[] {
                    Return.Create(RealLiteral.Create("3.3"))
                }))
                                                  .Parameters(FunctionParameter.Create("x", NameFactory.Int64NameReference(), usageMode: ExpressionReadMode.CannotBeRead)));

                root_ns.AddNode(VariableDeclaration.CreateStatement("i", NameFactory.Int64NameReference(), Undef.Create()));
                var call = FunctionCall.Create(NameReference.Create("foo"), FunctionArgument.Create(NameReference.Create("i")));
                root_ns.AddNode(Block.CreateStatement(new[] { call }));

                resolver = NameResolver.Create(env);

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

            return(resolver);
        }
Ejemplo n.º 4
0
        public IInterpreter ChannelDeadLockOnSend()
        {
            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;

                root_ns.AddBuilder(FunctionBuilder.Create(
                                       "main",
                                       ExpressionReadMode.OptionalUse,
                                       NameFactory.Int64NameReference(),
                                       Block.CreateStatement(new IExpression[] {
                    VariableDeclaration.CreateStatement("ch", null,
                                                        ExpressionFactory.HeapConstructor(NameFactory.ChannelNameReference(NameFactory.Int64NameReference()))),
                    ExpressionFactory.Readout(FunctionCall.Create(NameReference.Create("ch", NameFactory.ChannelSend),
                                                                  FunctionArgument.Create(Int64Literal.Create("2")))),
                    Return.Create(Int64Literal.Create("0"))
                })));

                int task_id = Task.WaitAny(Task.Delay(TimeSpan.FromSeconds(Interpreter.Interpreter.TimeoutSeconds)), interpreter.TestRunAsync(env));
                Assert.AreEqual(0, task_id);
            }

            return(interpreter);
        }
Ejemplo n.º 5
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.º 6
0
        public IInterpreter MinLimitVariadicFunctionWithSpread()
        {
            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;

                root_ns.AddBuilder(FunctionBuilder.Create(
                                       "sum",
                                       ExpressionReadMode.ReadRequired,
                                       NameFactory.Int64NameReference(),
                                       Block.CreateStatement(new IExpression[] {
                    // let i0 = n.at(0)
                    VariableDeclaration.CreateStatement("i0", null, FunctionCall.Create(NameReference.Create("n", NameFactory.PropertyIndexerName),
                                                                                        FunctionArgument.Create(NatLiteral.Create("0")))),
                    // let i1 = n.at(1)
                    VariableDeclaration.CreateStatement("i1", null, FunctionCall.Create(NameReference.Create("n", NameFactory.PropertyIndexerName),
                                                                                        FunctionArgument.Create(NatLiteral.Create("1")))),
                    // return i0+i1
                    Return.Create(ExpressionFactory.Add("i0", "i1"))
                }))
                                   .Parameters(FunctionParameter.Create("n", NameFactory.Int64NameReference(), Variadic.Create(2), null, isNameRequired: false)));

                var main_func = root_ns.AddBuilder(FunctionBuilder.Create(
                                                       "main",
                                                       ExpressionReadMode.OptionalUse,
                                                       NameFactory.Int64NameReference(),
                                                       Block.CreateStatement(new IExpression[] {
                    VariableDeclaration.CreateStatement("x", null,
                                                        ExpressionFactory.HeapConstructor(NameFactory.ChunkNameReference(NameFactory.Int64NameReference()),
                                                                                          FunctionArgument.Create(NatLiteral.Create("2"))),
                                                        env.Options.ReassignableModifier()),
                    Assignment.CreateStatement(FunctionCall.Indexer(NameReference.Create("x"), FunctionArgument.Create(NatLiteral.Create("0"))),
                                               Int64Literal.Create("-6")),
                    Assignment.CreateStatement(FunctionCall.Indexer(NameReference.Create("x"), FunctionArgument.Create(NatLiteral.Create("1"))),
                                               Int64Literal.Create("8")),
                    Return.Create(FunctionCall.Create(NameReference.Create("sum"),
                                                      FunctionArgument.Create(Spread.Create(NameReference.Create("x")))))
                })));

                ExecValue result = interpreter.TestRun(env);

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

            return(interpreter);
        }
Ejemplo n.º 7
0
        public IInterpreter OverridingMethodWithIndexerGetter()
        {
            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;

                root_ns.AddBuilder(TypeBuilder.CreateInterface("IProvider")
                                   .With(FunctionBuilder.CreateDeclaration(NameFactory.PropertyIndexerName, ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference())
                                         .Parameters(FunctionParameter.Create("x", NameFactory.Int64NameReference()))));

                root_ns.AddBuilder(TypeBuilder.Create("Middle")
                                   .Parents("IProvider")
                                   .SetModifier(EntityModifier.Base)
                                   .With(FunctionBuilder.Create(NameFactory.PropertyIndexerName, ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference(),
                                                                Block.CreateStatement(Return.Create(Int64Literal.Create("500"))))
                                         .SetModifier(EntityModifier.Override | EntityModifier.UnchainBase)
                                         .Parameters(FunctionParameter.Create("x", NameFactory.Int64NameReference(), ExpressionReadMode.CannotBeRead))));

                root_ns.AddBuilder(TypeBuilder.Create("Last")
                                   .Parents("Middle")
                                   .SetModifier(EntityModifier.Base)
                                   .With(PropertyBuilder.CreateIndexer(env.Options, NameFactory.Int64NameReference())
                                         .Parameters(FunctionParameter.Create("x", NameFactory.Int64NameReference(), ExpressionReadMode.CannotBeRead))
                                         .With(PropertyMemberBuilder.CreateIndexerGetter(Block.CreateStatement(Return.Create(Int64Literal.Create("2"))))
                                               .Modifier(EntityModifier.Override | EntityModifier.UnchainBase))));

                root_ns.AddBuilder(FunctionBuilder.Create(
                                       "main",
                                       ExpressionReadMode.OptionalUse,
                                       NameFactory.Int64NameReference(),
                                       Block.CreateStatement(new IExpression[] {
                    VariableDeclaration.CreateStatement("p", NameFactory.PointerNameReference("IProvider"),
                                                        ExpressionFactory.HeapConstructor("Last")),
                    Return.Create(FunctionCall.Create(NameReference.Create("p", NameFactory.PropertyIndexerName),
                                                      FunctionArgument.Create(Int64Literal.Create("18"))))
                })));

                ExecValue result = interpreter.TestRun(env);

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

            return(interpreter);
        }
Ejemplo n.º 8
0
        public IInterpreter DirectRefCountings()
        {
            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 inc_def = root_ns.AddBuilder(FunctionBuilder.Create(
                                                     "inc",
                                                     ExpressionReadMode.ReadRequired,
                                                     NameFactory.Int64NameReference(),
                                                     Block.CreateStatement(new IExpression[] {
                    // let temp *Int = n; // n is argument
                    VariableDeclaration.CreateStatement("temp", NameFactory.PointerNameReference(NameFactory.Int64NameReference()),
                                                        NameReference.Create("n")),
                    // return temp + 1;
                    Return.Create(FunctionCall.Create(NameReference.Create(NameReference.Create("temp"), NameFactory.AddOperator),
                                                      FunctionArgument.Create(Int64Literal.Create("1"))))
                }))
                                                 .Parameters(FunctionParameter.Create("n", NameFactory.PointerNameReference(NameFactory.Int64NameReference()))));
                var main_func = root_ns.AddBuilder(FunctionBuilder.Create(
                                                       "main",
                                                       ExpressionReadMode.OptionalUse,
                                                       NameFactory.Int64NameReference(),
                                                       Block.CreateStatement(new IExpression[] {
                    // let p_int *Int = new *1;
                    VariableDeclaration.CreateStatement("p_int", NameFactory.PointerNameReference(NameFactory.Int64NameReference()),
                                                        ExpressionFactory.HeapConstructor(NameFactory.Int64NameReference(), FunctionArgument.Create(Int64Literal.Create("1")))),
                    // let proxy *Int = p_int;
                    VariableDeclaration.CreateStatement("proxy", NameFactory.PointerNameReference(NameFactory.Int64NameReference()), NameReference.Create("p_int")),
                    // return inc(proxy);
                    Return.Create(FunctionCall.Create(NameReference.Create("inc"), FunctionArgument.Create(NameReference.Create("proxy")))),
                })));


                ExecValue result = interpreter.TestRun(env);

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

            return(interpreter);
        }
Ejemplo n.º 9
0
        public IErrorReporter DistinctTypesOverloadCall()
        {
            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 system_ns = env.SystemNamespace;

                var func_def1 = root_ns.AddBuilder(FunctionBuilder.Create(
                                                       "foo",
                                                       ExpressionReadMode.OptionalUse,
                                                       NameFactory.RealNameReference(),
                                                       Block.CreateStatement(new[] {
                    Return.Create(RealLiteral.Create("3.3"))
                }))
                                                   .Parameters(FunctionParameter.Create("x", NameFactory.Int64NameReference(), usageMode: ExpressionReadMode.CannotBeRead)));
                var func_def2 = root_ns.AddBuilder(FunctionBuilder.Create(
                                                       "foo",
                                                       ExpressionReadMode.OptionalUse,
                                                       NameFactory.RealNameReference(),
                                                       Block.CreateStatement(new[] {
                    Return.Create(RealLiteral.Create("3.3"))
                }))
                                                   .Parameters(FunctionParameter.Create("x", NameFactory.RealNameReference(), usageMode: ExpressionReadMode.CannotBeRead)));
                root_ns.AddNode(VariableDeclaration.CreateStatement("i", NameFactory.Int64NameReference(), Undef.Create()));
                root_ns.AddNode(VariableDeclaration.CreateStatement("s", NameFactory.RealNameReference(), Undef.Create()));
                var call1 = FunctionCall.Create(NameReference.Create("foo"), FunctionArgument.Create(NameReference.Create("i")));
                var call2 = FunctionCall.Create(NameReference.Create("foo"), FunctionArgument.Create(NameReference.Create("s")));
                root_ns.AddNode(VariableDeclaration.CreateStatement("x", NameFactory.RealNameReference(),
                                                                    call1, modifier: EntityModifier.Public));
                root_ns.AddNode(VariableDeclaration.CreateStatement("y", NameFactory.RealNameReference(),
                                                                    call2, modifier: EntityModifier.Public));

                resolver = NameResolver.Create(env);

                Assert.AreEqual(0, resolver.ErrorManager.Errors.Count);
                Assert.AreEqual(func_def1, call1.Resolution.TargetFunctionInstance.Target);
                Assert.AreEqual(func_def2, call2.Resolution.TargetFunctionInstance.Target);
            }

            return(resolver);
        }
Ejemplo n.º 10
0
        public static void TrapClosure(this ILambdaTransfer node, ComputationContext ctx, ref IExpression source)
        {
            if (TrapLambdaClosure(node, ctx, ref source))
            {
                return;
            }

            if (source is NameReference name_ref && name_ref.Binding.Match.Instance.Target is FunctionDefinition func)
            {
                if (func.Name.Arity > 0 && !name_ref.TemplateArguments.Any())
                {
                    ctx.AddError(ErrorCode.SelectingAmbiguousTemplateFunction, name_ref);
                }
                IExpression this_obj = name_ref.GetContext(func);
                // example scenario
                // f = my_object.my_square
                // f(4)

                // so we have to grab "my_object", make closure around it, and then put it instead of "my_object.my_square"

                name_ref.DetachFrom(node);
                if (name_ref.Prefix != null)
                {
                    name_ref.Prefix.DetachFrom(name_ref);
                    name_ref.Prefix.DereferencedCount_LEGACY = 0; // we have to clear it because we will reuse it
                }
                TypeDefinition closure_type = buildTypeOfReference(ctx, name_ref, this_obj);
                node.AddClosure(closure_type);

                if (this_obj != null)
                {
                    source = ExpressionFactory.HeapConstructor(closure_type.InstanceOf.NameOf,
                                                               FunctionArgument.Create(name_ref.Prefix));
                }
                else
                {
                    source = ExpressionFactory.HeapConstructor(closure_type.InstanceOf.NameOf);
                }
                source.AttachTo(node);

                closure_type.Surfed(ctx);
                closure_type.Evaluated(ctx, EvaluationCall.AdHocCrossJump);

                closure_type.InvokeFunctions().First().MetaThisParameter.Evaluated(ctx, EvaluationCall.AdHocCrossJump);
                source.Evaluated(ctx, EvaluationCall.Nested);
            }
        }
Ejemplo n.º 11
0
        public IInterpreter DereferenceOnAssignment()
        {
            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[] {
                    // p_int *Int = new Int(1)
                    VariableDeclaration.CreateStatement("p_int", NameFactory.PointerNameReference(NameFactory.Int64NameReference(env.Options.ReassignableTypeMutability())),
                                                        ExpressionFactory.HeapConstructor(NameFactory.Int64NameReference(env.Options.ReassignableTypeMutability()),
                                                                                          FunctionArgument.Create(Int64Literal.Create("1"))), env.Options.ReassignableModifier()),
                    // v_int Int = *p_int // automatic dereference
                    VariableDeclaration.CreateStatement("v_int", NameFactory.Int64NameReference(), NameReference.Create("p_int")),
                    // z_int Int
                    VariableDeclaration.CreateStatement("z_int", NameFactory.Int64NameReference(), null, env.Options.ReassignableModifier()),
                    // z_int = *p_int // automatic derereference
                    Assignment.CreateStatement(NameReference.Create("z_int"), NameReference.Create("p_int")),
                    // p_int = new Int(77)
                    Assignment.CreateStatement(NameReference.Create("p_int"),
                                               ExpressionFactory.HeapConstructor(NameFactory.Int64NameReference(env.Options.ReassignableTypeMutability()),
                                                                                 FunctionArgument.Create(Int64Literal.Create("77")))),
                    // return v_int + z_int
                    Return.Create(FunctionCall.Create(NameReference.Create(NameReference.Create("v_int"), NameFactory.AddOperator),
                                                      FunctionArgument.Create(NameReference.Create("z_int"))))
                })));


                ExecValue result = interpreter.TestRun(env);

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

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

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

                var point_type = root_ns.AddBuilder(TypeBuilder.Create("Point")
                                                    .SetModifier(EntityModifier.Mutable)
                                                    .With(VariableDeclaration.CreateStatement("x", NameFactory.Int64NameReference(), null,
                                                                                              EntityModifier.Public | env.Options.ReassignableModifier()))
                                                    .With(FunctionBuilder.Create("empty",
                                                                                 ExpressionReadMode.CannotBeRead,
                                                                                 NameFactory.UnitNameReference(),

                                                                                 Block.CreateStatement())
                                                          .Parameters(FunctionParameter.Create("p", NameFactory.PointerNameReference(NameReference.Create("Point")), Variadic.None,
                                                                                               null, isNameRequired: false, usageMode: ExpressionReadMode.CannotBeRead))));

                FunctionArgument mutable_arg    = FunctionArgument.Create(NameReference.Create("r"));
                NameReference    mutable_method = NameReference.Create("r", "empty");
                var main_func = root_ns.AddBuilder(FunctionBuilder.Create(
                                                       "main",
                                                       ExpressionReadMode.OptionalUse,
                                                       NameFactory.Int64NameReference(),
                                                       Block.CreateStatement(new IExpression[] {
                    VariableDeclaration.CreateStatement("r", null, ExpressionFactory.HeapConstructor(NameReference.Create("Point"))),
                    Spawn.Create(FunctionCall.Create(mutable_method, mutable_arg)),
                    Return.Create(NameReference.Create("r", "x"))
                })));

                resolver = NameResolver.Create(env);

                Assert.AreEqual(2, resolver.ErrorManager.Errors.Count);
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.CannotSpawnWithMutableArgument, mutable_arg));
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.CannotSpawnOnMutableContext, mutable_method));
            }

            return(resolver);
        }
Ejemplo n.º 13
0
        public IInterpreter SingleMessage()
        {
            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;

                root_ns.AddBuilder(FunctionBuilder.Create(
                                       "sender",
                                       ExpressionReadMode.CannotBeRead,
                                       NameFactory.UnitNameReference(),
                                       Block.CreateStatement(new IExpression[] {
                    ExpressionFactory.AssertTrue(FunctionCall.Create(NameReference.Create("ch", NameFactory.ChannelSend),
                                                                     FunctionArgument.Create(Int64Literal.Create("2")))),
                }))
                                   .Parameters(FunctionParameter.Create("ch", NameFactory.PointerNameReference(NameFactory.ChannelNameReference(NameFactory.Int64NameReference())),
                                                                        Variadic.None, null, isNameRequired: false)));

                root_ns.AddBuilder(FunctionBuilder.Create(
                                       "main",
                                       ExpressionReadMode.OptionalUse,
                                       NameFactory.Int64NameReference(),
                                       Block.CreateStatement(new IExpression[] {
                    VariableDeclaration.CreateStatement("ch", null,
                                                        ExpressionFactory.HeapConstructor(NameFactory.ChannelNameReference(NameFactory.Int64NameReference()))),
                    Spawn.Create(FunctionCall.Create(NameReference.Create("sender"), FunctionArgument.Create(NameReference.Create("ch")))),
                    VariableDeclaration.CreateStatement("r", null,
                                                        FunctionCall.Create(NameReference.Create("ch", NameFactory.ChannelReceive))),
                    ExpressionFactory.AssertOptionIsSome(NameReference.Create("r")),
                    Return.Create(ExpressionFactory.GetOptionValue(NameReference.Create("r")))
                })));

                ExecValue result = interpreter.TestRun(env);

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

            return(interpreter);
        }
Ejemplo n.º 14
0
        public IInterpreter AutoProperties()
        {
            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;

                var point_type = root_ns.AddBuilder(TypeBuilder.Create("Point")
                                                    .SetModifier(EntityModifier.Mutable)
                                                    .With(Property.Create(env.Options, "x", NameFactory.Int64NameReference(),
                                                                          new[] { Property.CreateAutoField(NameFactory.PropertyAutoField, NameFactory.Int64NameReference(), Int64Literal.Create("1"),
                                                                                                           env.Options.ReassignableModifier()) },
                                                                          new[] { Property.CreateAutoGetter(NameFactory.PropertyAutoField, NameFactory.Int64NameReference()) },
                                                                          new[] { Property.CreateAutoSetter(NameFactory.PropertyAutoField, NameFactory.Int64NameReference()) }
                                                                          )));
                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.x = 1+p.x
                    Assignment.CreateStatement(NameReference.Create(NameReference.Create("p"), "x"),
                                               FunctionCall.Create(NameReference.Create(Int64Literal.Create("1"), NameFactory.AddOperator),
                                                                   FunctionArgument.Create(NameReference.Create("p", "x")))),
                    // return p.x
                    Return.Create(NameReference.Create("p", "x"))
                })));

                ExecValue result = interpreter.TestRun(env);

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

            return(interpreter);
        }
Ejemplo n.º 15
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.º 16
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.º 17
0
        public IErrorReporter ImplicitValueReferenceConversionOnCall()
        {
            NameResolver resolver = null;

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

                root_ns.AddBuilder(FunctionBuilder.Create(
                                       "main",
                                       ExpressionReadMode.CannotBeRead,
                                       NameFactory.UnitNameReference(),

                                       Block.CreateStatement(new[] {
                    FunctionCall.Create(NameReference.Create("foo"), FunctionArgument.Create(Int64Literal.Create("5")))
                })));
                root_ns.AddBuilder(FunctionBuilder.Create(
                                       "foo",
                                       ExpressionReadMode.CannotBeRead,
                                       NameFactory.UnitNameReference(),

                                       Block.CreateStatement())
                                   .Parameters(FunctionParameter.Create("x", NameFactory.ReferenceNameReference(NameFactory.Int64NameReference()),
                                                                        usageMode: ExpressionReadMode.CannotBeRead)));

                resolver = NameResolver.Create(env);

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

            return(resolver);
        }
Ejemplo n.º 18
0
        private static TypeDefinition buildTypeOfReference(ComputationContext ctx,
                                                           NameReference funcReference, IExpression thisObject)
        {
            if (funcReference.Owner != null)
            {
                throw new Exception("Detach it first.");
            }

            const string meta_this = "mThis";

            FunctionDefinition function = funcReference.Binding.Match.Instance.Target.CastFunction();

            FunctionDefinition cons;
            NameReference      func_field_ref;

            if (thisObject != null)
            {
                cons = FunctionDefinition.CreateInitConstructor(EntityModifier.None,
                                                                new[] { FunctionParameter.Create(meta_this, thisObject.Evaluation.Components.NameOf) },
                                                                Block.CreateStatement(
                                                                    new[] {
                    Assignment.CreateStatement(NameReference.Create(NameFactory.ThisVariableName, meta_this),
                                               NameReference.Create(meta_this)),
                }));

                func_field_ref = NameReference.Create(NameFactory.ThisVariableName, meta_this);
            }
            else
            {
                func_field_ref = null;
                cons           = null;
            }

            IEnumerable <FunctionParameter> trans_parameters = function.Parameters.Select(pit =>
                                                                                          FunctionParameter.Create(pit.Name.Name, pit.TypeName.Evaluated(ctx, EvaluationCall.AdHocCrossJump)
                                                                                                                   .TranslateThrough(funcReference.Binding.Match.Instance).NameOf));
            FunctionDefinition invoke = FunctionBuilder.Create(NameFactory.LambdaInvoke, ExpressionReadMode.ReadRequired,
                                                               function.ResultTypeName,
                                                               Block.CreateStatement(new[] {
                Return.Create(FunctionCall.Create(
                                  NameReference.Create(func_field_ref, funcReference.Name,
                                                       funcReference.TemplateArguments.Select(it => it.TypeName).ToArray()),
                                  function.Parameters.Select(it => FunctionArgument.Create(NameReference.Create(it.Name.Name))).ToArray()))
            }))
                                        .SetModifier(EntityModifier.Override)
                                        .Parameters(trans_parameters.ToArray());


            TypeBuilder closure_builder = TypeBuilder.Create(NameDefinition.Create(AutoName.Instance.CreateNew("Closure")))
                                          .With(invoke)
                                          .Parents(invoke.CreateFunctionInterface());

            if (thisObject != null)
            {
                VariableDeclaration this_field = VariableDeclaration.CreateStatement(meta_this,
                                                                                     thisObject.Evaluation.Components.NameOf, Undef.Create());
                closure_builder
                .With(cons)
                .With(this_field);

                TypeMutability mutability = thisObject.Evaluation.Components.MutabilityOfType(ctx);
                if (mutability == TypeMutability.ForceMutable)
                {
                    closure_builder.SetModifier(EntityModifier.Mutable);
                }
                else if (mutability != TypeMutability.ConstAsSource)
                {
                    throw new NotImplementedException();
                }
            }

            return(closure_builder);
        }
Ejemplo n.º 19
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.º 20
0
        public IErrorReporter ErrorHasConstraint()
        {
            NameResolver resolver = null;

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

                FunctionDefinition func_constraint = FunctionBuilder.CreateDeclaration("getMe",
                                                                                       ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference());

                // this function accepts any parameter where parameter type has function "getMe"
                FunctionDefinition constrained_func = root_ns.AddBuilder(FunctionBuilder.Create("proxy",
                                                                                                TemplateParametersBuffer.Create().Add("T").Values,
                                                                                                ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference(), Block.CreateStatement(new[] {
                    Return.Create(FunctionCall.Create(NameReference.Create("t", "getMe")))
                }))
                                                                         .Constraints(ConstraintBuilder.Create("T").Has(func_constraint))
                                                                         .Parameters(FunctionParameter.Create("t", NameFactory.PointerNameReference("T"))));

                // this type does NOT have function "getMe"
                TypeDefinition type_impl = root_ns.AddBuilder(TypeBuilder.Create("YMan")
                                                              .With(FunctionBuilder.Create("missing",
                                                                                           ExpressionReadMode.ReadRequired,
                                                                                           NameFactory.Int64NameReference(),
                                                                                           Block.CreateStatement(new[] {
                    Return.Create(Int64Literal.Create("2"))
                }))));

                FunctionCall call = FunctionCall.Create(NameReference.Create("proxy"), FunctionArgument.Create(NameReference.Create("y_man")));
                root_ns.AddBuilder(FunctionBuilder.Create(
                                       "main",
                                       ExpressionReadMode.OptionalUse,
                                       NameFactory.Int64NameReference(),
                                       Block.CreateStatement(new IExpression[] {
                    VariableDeclaration.CreateStatement("y_man", null, ExpressionFactory.HeapConstructor(NameReference.Create("YMan"))),
                    Return.Create(call)
                })));

                resolver = NameResolver.Create(env);

                Assert.AreEqual(1, resolver.ErrorManager.Errors.Count);
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.ViolatedHasFunctionConstraint, call.Callee));
            }

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

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

                VariableDeclaration decl = VariableDeclaration.CreateStatement("x",
                                                                               NameFactory.PointerNameReference(NameFactory.Int64NameReference(env.Options.ReassignableTypeMutability())),
                                                                               ExpressionFactory.HeapConstructor(NameFactory.Int64NameReference(env.Options.ReassignableTypeMutability()),
                                                                                                                 FunctionArgument.Create(Int64Literal.Create("4"))),
                                                                               env.Options.ReassignableModifier());
                var main_func = root_ns.AddBuilder(FunctionBuilder.Create(
                                                       "main",
                                                       ExpressionReadMode.OptionalUse,
                                                       NameFactory.Int64NameReference(),
                                                       Block.CreateStatement(new IExpression[] {
                    // x *Int = new Int(4)
                    decl,
                    // y *Int = x
                    VariableDeclaration.CreateStatement("y",
                                                        NameFactory.PointerNameReference(NameFactory.Int64NameReference(env.Options.ReassignableTypeMutability())),
                                                        NameReference.Create("x")),
                    // *x = 7 // y <- 7
                    Assignment.CreateStatement(Dereference.Create(NameReference.Create("x")), Int64Literal.Create("7")),
                    // z *Int
                    VariableDeclaration.CreateStatement("z",
                                                        NameFactory.PointerNameReference(NameFactory.Int64NameReference(env.Options.ReassignableTypeMutability())),
                                                        null, env.Options.ReassignableModifier()),
                    // z = x
                    Assignment.CreateStatement(NameReference.Create("z"), NameReference.Create("x")),
                    // v = y + z  // 14
                    VariableDeclaration.CreateStatement("v", null, ExpressionFactory.Add("y", "z"), env.Options.ReassignableModifier()),
                    // x = -12
                    Assignment.CreateStatement(NameReference.Create("x"),
                                               ExpressionFactory.HeapConstructor(NameFactory.Int64NameReference(env.Options.ReassignableTypeMutability()),
                                                                                 FunctionArgument.Create(Int64Literal.Create("-12")))),
                    // *z = *x   // z <- -12
                    Assignment.CreateStatement(Dereference.Create(NameReference.Create("z")), Dereference.Create(NameReference.Create("x"))),
                    // x = -1000
                    Assignment.CreateStatement(NameReference.Create("x"),
                                               ExpressionFactory.HeapConstructor(NameFactory.Int64NameReference(env.Options.ReassignableTypeMutability()),
                                                                                 FunctionArgument.Create(Int64Literal.Create("-1000")))),
                    // v = v+z  // v = 14 + (-12)
                    Assignment.CreateStatement(NameReference.Create("v"), ExpressionFactory.Add("v", "z")),
                    Return.Create(NameReference.Create("v"))
                })));


                ExecValue result = interpreter.TestRun(env);

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

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

            foreach (var mutability in Options.AllMutabilityModes)
            {
                // todo: add analogous test with storing iterable as sequence

                // yes, this test seems like pointless thing but it is important nevertheless because
                // we have to check if conversion does NOT happen
                var env = Language.Environment.Create(new Options()
                {
                }.SetMutability(mutability));
                var root_ns = env.Root;

                var main_func = root_ns.AddBuilder(FunctionBuilder.Create(
                                                       "main",
                                                       ExpressionReadMode.OptionalUse,
                                                       NameFactory.Nat8NameReference(),
                                                       Block.CreateStatement(new IExpression[] {
                    VariableDeclaration.CreateStatement("x", null,
                                                        ExpressionFactory.HeapConstructor(NameFactory.ChunkNameReference(NameFactory.Int64NameReference()),
                                                                                          FunctionArgument.Create(NatLiteral.Create("2"))),
                                                        env.Options.ReassignableModifier()),
                    ExpressionFactory.InitializeIndexable("x", Int64Literal.Create("-6"), Int64Literal.Create("8")),
                    // conversion should NOT happen
                    VariableDeclaration.CreateStatement("stored", null,
                                                        FunctionCall.Create(NameFactory.StoreFunctionReference(), NameReference.Create("x"))),
                    Return.Create(ExpressionFactory.Ternary(IsSame.Create("x", "stored"), Nat8Literal.Create("2"), Nat8Literal.Create("7")))
                })));

                ExecValue result = interpreter.TestRun(env);

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

            return(interpreter);
        }
Ejemplo n.º 23
0
 public static IExpression InitializeIndexable(string name, params IExpression[] arguments)
 {
     return(Block.CreateStatement(arguments.ZipWithIndex().Select(it =>
                                                                  Assignment.CreateStatement(FunctionCall.Indexer(NameReference.Create(name),
                                                                                                                  FunctionArgument.Create(NatLiteral.Create($"{it.Item2}"))),
                                                                                             it.Item1))));
 }
Ejemplo n.º 24
0
        public IInterpreter RefCountsOnReadingFunctionCall()
        {
            var interpreter = new Interpreter.Interpreter();

            foreach (var mutability in Options.AllMutabilityModes)
            {
                // the aim of this test is to test heap manager if it correctly handles reading function which returns pointer

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

                root_ns.AddBuilder(FunctionBuilder.Create(
                                       "provider",
                                       ExpressionReadMode.OptionalUse,
                                       NameFactory.PointerNameReference(NameFactory.Int64NameReference()),
                                       Block.CreateStatement(new IExpression[] {
                    VariableDeclaration.CreateStatement("p_int", null,
                                                        ExpressionFactory.HeapConstructor(NameFactory.Int64NameReference(),
                                                                                          FunctionArgument.Create(Int64Literal.Create("77")))),
                    Return.Create(NameReference.Create("p_int")),
                })));

                var main_func = root_ns.AddBuilder(FunctionBuilder.Create(
                                                       "main",
                                                       ExpressionReadMode.OptionalUse,
                                                       NameFactory.Int64NameReference(),
                                                       Block.CreateStatement(new IExpression[] {
                    VariableDeclaration.CreateStatement("i", NameFactory.Int64NameReference(),
                                                        FunctionCall.Create(NameReference.Create("provider"))),
                    Return.Create(NameReference.Create("i")),
                })));


                ExecValue result = interpreter.TestRun(env);

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

            return(interpreter);
        }
Ejemplo n.º 25
0
 public static ConstructorCall HeapConstructor(TypeMutability mutability, NameReference innerTypeName, params IExpression[] arguments)
 {
     return(HeapConstructor(mutability, innerTypeName, arguments.Select(it => FunctionArgument.Create(it)).ToArray()));
 }
Ejemplo n.º 26
0
 public static ConstructorCall Constructor(NameReference typeName, Memory memory, params IExpression[] arguments)
 {
     return(Constructor(typeName, memory, arguments.Select(it => FunctionArgument.Create(it)).ToArray()));
 }
Ejemplo n.º 27
0
        public static bool TrapLambdaClosure(this ILambdaTransfer node, ComputationContext ctx, ref IExpression source)
        {
            if (!(source is FunctionDefinition lambda))
            {
                return(false);
            }

            // example scenario
            // f = (x) => x*x
            // f(4)

            // we already have tracked all the variables used inside lambda (which are declared outside, locals are OK),
            // so all we have to do it is to remove it and put into closure type

            if (!lambda.IsComputed)
            {
                throw new Exception("Internal error");
            }

            lambda.DetachFrom(node);
            TypeDefinition closure_type = buildTypeOfLambda(ctx, lambda, lambda.LambdaTrap.Fields);

            node.AddClosure(closure_type);

            source = ExpressionFactory.HeapConstructor(closure_type.InstanceOf.NameOf,
                                                       lambda.LambdaTrap.Fields.Select(it => FunctionArgument.Create(NameReference.Create(it.Name.Name))).ToArray());
            source.AttachTo(node);

            lambda.LambdaTrap = null;

            // we have to manually evaluate this expression, because it is child of current node, and child nodes
            // are evaluated before their parents
            closure_type.Surfed(ctx);
            closure_type.Evaluated(ctx, EvaluationCall.AdHocCrossJump);

            // todo: this is ugly -- we are breaking into details of separate type
            // since the function is already computed, it won't evaluate meta this parameter
            lambda.MetaThisParameter.Evaluated(ctx, EvaluationCall.AdHocCrossJump);
            source.Evaluated(ctx, EvaluationCall.Nested);

            return(true);
        }
Ejemplo n.º 28
0
        public IInterpreter StackChunkWithBasicPointers()
        {
            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;

                root_ns.AddBuilder(FunctionBuilder.Create(
                                       "main",
                                       ExpressionReadMode.OptionalUse,
                                       NameFactory.Int64NameReference(),
                                       Block.CreateStatement(new IExpression[] {
                    VariableDeclaration.CreateStatement("chicken", null,
                                                        ExpressionFactory.StackConstructor(NameFactory.ChunkNameReference(NameFactory.PointerNameReference(NameFactory.Int64NameReference())),
                                                                                           FunctionArgument.Create(NatLiteral.Create("2")))),
                    Assignment.CreateStatement(FunctionCall.Indexer(NameReference.Create("chicken"), NatLiteral.Create("0")),
                                               ExpressionFactory.HeapConstructor(NameFactory.Int64NameReference(), Int64Literal.Create("-6"))),
                    Assignment.CreateStatement(FunctionCall.Indexer(NameReference.Create("chicken"), NatLiteral.Create("1")),
                                               ExpressionFactory.HeapConstructor(NameFactory.Int64NameReference(), Int64Literal.Create("8"))),
                    Return.Create(ExpressionFactory.Add(FunctionCall.Indexer(NameReference.Create("chicken"), NatLiteral.Create("0")),
                                                        FunctionCall.Indexer(NameReference.Create("chicken"), NatLiteral.Create("1"))))
                })));

                ExecValue result = interpreter.TestRun(env);

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

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

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

                FunctionDefinition func_constraint = FunctionBuilder.CreateDeclaration("getMe",
                                                                                       ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference());
                root_ns.AddBuilder(FunctionBuilder.Create("proxy",
                                                          TemplateParametersBuffer.Create().Add("T").Values,
                                                          ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference(), Block.CreateStatement(new[] {
                    Return.Create(FunctionCall.Create(NameReference.Create("t", "getMe")))
                }))
                                   .Constraints(ConstraintBuilder.Create("T").Has(func_constraint))
                                   .Parameters(FunctionParameter.Create("t", NameReference.Create("T"))));

                TypeDefinition type_impl = root_ns.AddBuilder(TypeBuilder.Create("Y")
                                                              .With(FunctionBuilder.Create("getMe",
                                                                                           ExpressionReadMode.ReadRequired,
                                                                                           NameFactory.Int64NameReference(),
                                                                                           Block.CreateStatement(new[] {
                    Return.Create(Int64Literal.Create("2"))
                }))));

                FunctionCall call = FunctionCall.Create(NameReference.Create("proxy"), FunctionArgument.Create(NameReference.Create("y")));
                root_ns.AddBuilder(FunctionBuilder.Create(
                                       "main",
                                       ExpressionReadMode.OptionalUse,
                                       NameFactory.Int64NameReference(),
                                       Block.CreateStatement(new IExpression[] {
                    VariableDeclaration.CreateStatement("y", null, ExpressionFactory.StackConstructor(NameReference.Create("Y"))),
                    Return.Create(call)
                })));

                ExecValue result = interpreter.TestRun(env);

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

            return(interpreter);
        }
Ejemplo n.º 30
0
        public static bool DataTransfer(this IEvaluable @this, ComputationContext ctx, ref IExpression source,
                                        IEntityInstance targetTypeName, bool ignoreMutability = false)
        {
            if (source == null)
            {
                return(true);
            }

            IEntityInstance src_type = source.Evaluation.Components;

            TypeMatch match = src_type.MatchesTarget(ctx, targetTypeName,
                                                     TypeMatching.Create(ctx.Env.Options.InterfaceDuckTyping, allowSlicing: false)
                                                     .WithIgnoredMutability(ignoreMutability)
                                                     .AllowedLifetimeChecking(true));

            if (match.HasFlag(TypeMatch.Attachment))
            {
                match ^= TypeMatch.Attachment;
            }

            if (match == TypeMatch.No)
            {
                ctx.ErrorManager.AddError(ErrorCode.TypeMismatch, source);
                return(false);
            }
            else if (match == TypeMatch.Lifetime)
            {
                ctx.ErrorManager.AddError(ErrorCode.EscapingReference, source);
                return(false);
            }
            else if (match == TypeMatch.InConversion)
            {
                source.DetachFrom(@this);
                source = ExpressionFactory.StackConstructor((targetTypeName as EntityInstance).NameOf, FunctionArgument.Create(source));
                source.AttachTo(@this);
                TypeMatch m = source.Evaluated(ctx, EvaluationCall.AdHocCrossJump).MatchesTarget(ctx, targetTypeName, TypeMatching.Create(ctx.Env.Options.InterfaceDuckTyping, allowSlicing: false));
                if (m != TypeMatch.Same && m != TypeMatch.Substitute)
                {
                    throw new Exception("Internal error");
                }
            }
            else if (match.HasFlag(TypeMatch.ImplicitReference))
            {
                match ^= TypeMatch.ImplicitReference;
                if (match != TypeMatch.Substitute && match != TypeMatch.Same)
                {
                    throw new NotImplementedException();
                }

                source.DetachFrom(@this);
                source = AddressOf.CreateReference(source);
                source.AttachTo(@this);
                IEntityInstance source_eval = source.Evaluated(ctx, EvaluationCall.AdHocCrossJump);
                TypeMatch       m           = source_eval.MatchesTarget(ctx, targetTypeName, TypeMatching.Create(ctx.Env.Options.InterfaceDuckTyping,
                                                                                                                 allowSlicing: true));
                if (m != TypeMatch.Same && m != TypeMatch.Substitute)
                {
                    throw new Exception($"Internal error: matching result {m}");
                }
            }
            else if (match == TypeMatch.OutConversion)
            {
                source.DetachFrom(@this);
                source = FunctionCall.ConvCall(source, (targetTypeName as EntityInstance).NameOf);
                source.AttachTo(@this);
                TypeMatch m = source.Evaluated(ctx, EvaluationCall.AdHocCrossJump).MatchesTarget(ctx, targetTypeName, TypeMatching.Create(ctx.Env.Options.InterfaceDuckTyping, allowSlicing: false));
                if (m != TypeMatch.Same && m != TypeMatch.Substitute)
                {
                    throw new Exception("Internal error");
                }
            }
            else if (match.HasFlag(TypeMatch.AutoDereference))
            {
                source.DereferencedCount_LEGACY = match.Dereferences;
                @this.Cast <IExpression>().DereferencingCount = match.Dereferences;

                match ^= TypeMatch.AutoDereference;
                if (match != TypeMatch.Substitute && match != TypeMatch.Same)
                {
                    throw new NotImplementedException();
                }
            }
            else if (match != TypeMatch.Same && match != TypeMatch.Substitute)
            {
                throw new NotImplementedException();
            }

            return(true);
        }