Ejemplo n.º 1
0
        public FunctionDefinition Build()
        {
            if (build == null)
            {
                NameDefinition final_name;
                if (FunctionDefinition.IsValidMutableName(this.name, this.modifier))
                {
                    final_name = NameDefinition.Create(name, nameParameters);
                }
                else
                {
                    final_name = NameDefinition.Create(NameFactory.MutableName(this.name), nameParameters);
                }

                build = FunctionDefinition.CreateFunction(
                    this.modifier ?? EntityModifier.None,
                    final_name,
                    constraints,
                    parameters ?? Enumerable.Empty <FunctionParameter>(), callMode, result,
                    chainCall,
                    body,
                    includes,
                    friends);
            }
            return(build);
        }
Ejemplo n.º 2
0
        public IErrorReporter BasicTraitDefinition()
        {
            NameResolver resolver = null;

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

                root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Foo", "T", VarianceMode.None)));

                root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Foo", "T", VarianceMode.None))
                                   .SetModifier(EntityModifier.Trait)
                                   .Constraints(ConstraintBuilder.Create("T")
                                                .SetModifier(EntityModifier.Const)));

                resolver = NameResolver.Create(env);

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

            return(resolver);
        }
Ejemplo n.º 3
0
        public IErrorReporter CatVarianceExample() // Programming in Scala, 2nd ed, p. 399
        {
            NameResolver resolver = null;

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

                NameReference result_typename = NameReference.Create("Cat",
                                                                     NameReference.Create("Cat", NameReference.Create("U"), NameReference.Create("T")), NameReference.Create("U"));

                root_ns.AddBuilder(TypeBuilder.CreateInterface(NameDefinition.Create("Cat", TemplateParametersBuffer.Create()
                                                                                     .Add("T", VarianceMode.In).Add("U", VarianceMode.Out).Values))
                                   .With(FunctionBuilder.CreateDeclaration("meow", "W", VarianceMode.In, ExpressionReadMode.ReadRequired, result_typename)
                                         .Parameters(FunctionParameter.Create("volume", NameReference.Create("T")),
                                                     FunctionParameter.Create("listener",
                                                                              NameReference.Create("Cat", NameReference.Create("U"), NameReference.Create("T"))))));

                resolver = NameResolver.Create(env);

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

            return(resolver);
        }
Ejemplo n.º 4
0
        private VariableDeclaration(EntityModifier modifier, ExpressionReadMode readMode, string name,
                                    INameReference typeName,
                                    IExpression initValue,
                                    IEnumerable <LabelReference> friends = null)
            : base(readMode)
        {
            if (name == null)
            {
                throw new ArgumentNullException();
            }

            this.Modifier     = modifier ?? EntityModifier.None;
            this.Name         = NameDefinition.Create(name);
            this.TypeName     = typeName;
            this.initValue    = initValue;
            this.AccessGrants = (friends ?? Enumerable.Empty <LabelReference>()).StoreReadOnly();

            this.instancesCache = new EntityInstanceCache(this, () => GetInstance(TypeMutability.None,
                                                                                  TemplateTranslation.CreateParameterless(this), Lifetime.Timeless));

            this.closures = new List <TypeDefinition>();

            this.attachPostConstructor();

            this.flow = Later.Create(() => ExecutionFlow.CreatePath(InitValue));
        }
Ejemplo n.º 5
0
        public IErrorReporter TemplateResolving()
        {
            NameResolver resolver = null;
            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Environment.Create(new Options() { }.SetMutability(mutability));
                var root_ns = env.Root;
                var system_ns = env.SystemNamespace;

                var tuple_ref = NameReference.Create("Tuple", NameReference.Create("T"));

                var tuple_type = system_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Tuple", "T", VarianceMode.None))
                    .With(tuple_ref));
                var abc_type = system_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("ABC")));
                var derived_type = system_ns.AddBuilder(TypeBuilder.Create("Deriv").Parents(NameReference.Create("ABC")));

                var tuple_abc_ref = system_ns.AddNode(NameReference.Create("Tuple", NameReference.Create("ABC")));

                resolver = NameResolver.Create(env);

                Assert.AreEqual(1, tuple_ref.Binding.Matches.Count());
                Assert.AreEqual(tuple_type, tuple_ref.Binding.Match.Instance.Target);
                Assert.AreEqual(tuple_type.NestedTypes().Single(),
                    tuple_ref.Binding.Match.Instance.TemplateArguments.Single().Target());

                Assert.AreEqual(1, tuple_abc_ref.Binding.Matches.Count());
                Assert.AreEqual(tuple_type, tuple_abc_ref.Binding.Match.Instance.Target);
                Assert.AreEqual(abc_type, tuple_abc_ref.Binding.Match.Instance.TemplateArguments.Single().Target());
            }

            return resolver;
        }
Ejemplo n.º 6
0
        public IErrorReporter CircularConversion()
        {
            NameResolver resolver = null;

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

                TypeDefinition type = root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Foo", "T", VarianceMode.Out))
                                                         .Slicing(true)
                                                         .With(FunctionDefinition.CreateInitConstructor(EntityModifier.Implicit,
                                                                                                        new[] {
                    // converting itself
                    FunctionParameter.Create(NameFactory.SourceConvConstructorParameter, NameReference.Create("Foo", NameReference.Create("T")), Variadic.None,
                                             null, isNameRequired: false, usageMode: ExpressionReadMode.CannotBeRead)
                },
                                                                                                        Block.CreateStatement())
                                                               ));

                var decl = root_ns.AddNode(
                    VariableDeclaration.CreateStatement("x",
                                                        NameReference.Create("Foo", NameFactory.Int64NameReference()), Int64Literal.Create("5")));

                resolver = NameResolver.Create(env);
            }

            return(resolver);
        }
Ejemplo n.º 7
0
        public IErrorReporter ErrorCircularValueNesting()
        {
            NameResolver resolver = null;

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

                VariableDeclaration decl1 = VariableDeclaration.CreateStatement("s", NameReference.Create("Form"), null, EntityModifier.Private);
                root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Shape"))
                                   .With(FunctionBuilder.Create("reader", NameFactory.UnitNameReference(),
                                                                Block.CreateStatement(ExpressionFactory.Readout(NameReference.CreateThised("s")))))
                                   .With(decl1));

                VariableDeclaration decl2 = VariableDeclaration.CreateStatement("f", NameReference.Create("Shape"), null, EntityModifier.Private);
                root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Form"))
                                   .With(FunctionBuilder.Create("reader", NameFactory.UnitNameReference(),
                                                                Block.CreateStatement(ExpressionFactory.Readout(NameReference.CreateThised("f")))))
                                   .With(decl2));

                resolver = NameResolver.Create(env);

                Assert.AreEqual(2, resolver.ErrorManager.Errors.Count);
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.NestedValueOfItself, decl1));
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.NestedValueOfItself, decl2));
            }

            return(resolver);
        }
Ejemplo n.º 8
0
        private FunctionParameter(ExpressionReadMode readMode, string name, INameReference typeName, Variadic variadic,
                                  IExpression defaultValue, EntityModifier modifier, bool isNameRequired)
        {
            this.UsageMode      = readMode;
            this.Modifier       = modifier ?? EntityModifier.None;
            this.Name           = NameDefinition.Create(name);
            this.IsNameRequired = isNameRequired;
            this.Variadic       = variadic;

            this.ElementTypeName = typeName;
            if (this.IsVariadic)
            {
                this.TypeName = NameFactory.ReferenceNameReference(NameFactory.ISequenceNameReference(this.ElementTypeName,
                                                                                                      mutability: TypeMutability.ForceMutable));
            }
            else
            {
                this.TypeName = this.ElementTypeName;
            }

            this.defaultValue = defaultValue;

            this.instancesCache = new EntityInstanceCache(this, () => GetInstance(TypeMutability.None,
                                                                                  TemplateTranslation.CreateParameterless(this), Lifetime.Timeless));

            this.attachPostConstructor();
        }
Ejemplo n.º 9
0
        public IErrorReporter ErrorTraitDefinition()
        {
            NameResolver resolver = null;

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

                root_ns.AddBuilder(TypeBuilder.Create("Bar")
                                   .SetModifier(EntityModifier.Base));

                TypeDefinition non_generic_trait = root_ns.AddBuilder(TypeBuilder.Create("Bar")
                                                                      .SetModifier(EntityModifier.Trait));

                root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Foo", "T", VarianceMode.None)));

                TypeDefinition unconstrained_trait = root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Foo", "T", VarianceMode.None))
                                                                        .SetModifier(EntityModifier.Trait));

                TypeDefinition missing_host = root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("MissMe", "Y", VarianceMode.None))
                                                                 .SetModifier(EntityModifier.Trait)
                                                                 .Constraints(ConstraintBuilder.Create("Y")
                                                                              .SetModifier(EntityModifier.Const)));

                root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Almost", "T", VarianceMode.None)));

                FunctionDefinition  trait_constructor = FunctionBuilder.CreateInitConstructor(Block.CreateStatement());
                VariableDeclaration trait_field       = VariableDeclaration.CreateStatement("f", NameFactory.Int64NameReference(), Int64Literal.Create("5"), EntityModifier.Public);
                root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Almost", "T", VarianceMode.None))
                                   .SetModifier(EntityModifier.Trait)
                                   .With(trait_constructor)
                                   .With(trait_field)
                                   .Constraints(ConstraintBuilder.Create("T")
                                                .SetModifier(EntityModifier.Const)));

                root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Inheriting", "T", VarianceMode.None)));

                NameReference parent_impl = NameReference.Create("Bar");
                root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Inheriting", "T", VarianceMode.None))
                                   .Parents(parent_impl)
                                   .SetModifier(EntityModifier.Trait)
                                   .Constraints(ConstraintBuilder.Create("T")
                                                .SetModifier(EntityModifier.Const)));

                resolver = NameResolver.Create(env);

                Assert.AreEqual(6, resolver.ErrorManager.Errors.Count);
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.NonGenericTrait, non_generic_trait));
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.UnconstrainedTrait, unconstrained_trait));
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.MissingHostTypeForTrait, missing_host));
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.TraitConstructor, trait_constructor));
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.TraitInheritingTypeImplementation, parent_impl));
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.FieldInNonImplementationType, trait_field));
            }

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

                root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Point", "V", VarianceMode.None))
                                   .With(Alias.Create("VType", NameReference.Create("V"), EntityModifier.Public)));

                VariableDeclaration decl = VariableDeclaration.CreateStatement("x", NameReference.Create("p", "VType"), Undef.Create(),
                                                                               env.Options.ReassignableModifier());
                root_ns.AddBuilder(FunctionBuilder.Create("main", NameFactory.Nat8NameReference(), Block.CreateStatement(
                                                              VariableDeclaration.CreateStatement("p", null,
                                                                                                  ExpressionFactory.StackConstructor(NameReference.Create("Point", NameFactory.Nat8NameReference()))),
                                                              decl,
                                                              Assignment.CreateStatement(NameReference.Create("x"), Nat8Literal.Create("5")),
                                                              Return.Create(NameReference.Create("x"))
                                                              )));

                ExecValue result = interpreter.TestRun(env);

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

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

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

                var bar_def = root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Bar"))
                                                 .With(FunctionDefinition.CreateInitConstructor(EntityModifier.None,
                                                                                                new[] { FunctionParameter.Create("a", NameFactory.Int64NameReference(),
                                                                                                                                 Variadic.None, null, isNameRequired: false, usageMode: ExpressionReadMode.CannotBeRead) },
                                                                                                Block.CreateStatement())));
                VariableDeclaration field_decl = VariableDeclaration.CreateStatement("x", NameReference.Create("Bar"), null,
                                                                                     EntityModifier.Public);
                var type_def = root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Point"))
                                                  .With(field_decl));

                resolver = NameResolver.Create(env);

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

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

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

                var foo_type = TypeBuilder.Create(NameDefinition.Create("Foo", "V", VarianceMode.None)).Build();
                system_ns.AddNode(foo_type);
                var parent_ref = NameReference.Create("Foo", NameReference.Create("T"));
                var tuple_type = TypeBuilder.Create(NameDefinition.Create("Tuple", "T", VarianceMode.None)).Parents(parent_ref).Build();
                system_ns.AddNode(tuple_type);

                resolver = NameResolver.Create(env);

                Assert.AreEqual(1, parent_ref.Binding.Matches.Count());
                Assert.AreEqual(foo_type, parent_ref.Binding.Match.Instance.Target);
                Assert.AreEqual(tuple_type.NestedTypes().Single(),
                                parent_ref.Binding.Match.Instance.TemplateArguments.Single().Target());
            }

            return(resolver);
        }
Ejemplo n.º 13
0
        public IErrorReporter ErrorInheritingFinalType()
        {
            NameResolver resolver = null;

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

                root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Point")));

                NameReference parent_name = NameReference.Create("Point");
                root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("PointEx"))
                                   .Parents(parent_name));

                resolver = NameResolver.Create(env);

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

            return(resolver);
        }
Ejemplo n.º 14
0
        public IErrorReporter ErrorTypeImplementationAsSecondaryParent()
        {
            NameResolver resolver = null;

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

                root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Point1")).SetModifier(EntityModifier.Base));
                root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Point2")).SetModifier(EntityModifier.Base));

                NameReference parent_name = NameReference.Create("Point2");
                root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("PointEx"))
                                   .Parents(NameReference.Create("Point1"), parent_name));

                resolver = NameResolver.Create(env);

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

            return(resolver);
        }
Ejemplo n.º 15
0
        public static TypeBuilder Create(string name, params string[] typeParameters)
        {
            var buff = TemplateParametersBuffer.Create();

            typeParameters.ForEach(it => buff.Add(it, VarianceMode.None));
            return(new TypeBuilder(NameDefinition.Create(name, buff.Values)));
        }
Ejemplo n.º 16
0
        private static TypeDefinition buildTypeOfLambda(ComputationContext ctx,
                                                        FunctionDefinition lambda, IEnumerable <VariableDeclaration> fields)
        {
            if (lambda.Owner != null)
            {
                throw new Exception("Internal error");
            }

            FunctionDefinition cons = FunctionDefinition.CreateInitConstructor(EntityModifier.None,
                                                                               fields.Select(it => FunctionParameter.Create(it.Name.Name, it.TypeName)),
                                                                               Block.CreateStatement(
                                                                                   fields.Select(it
                                                                                                 => Assignment.CreateStatement(NameReference.Create(NameFactory.ThisVariableName, it.Name.Name),
                                                                                                                               NameReference.Create(it.Name.Name)))
                                                                                   ));

            lambda.SetModifier(EntityModifier.Override | lambda.Modifier);

            TypeDefinition functor = TypeBuilder.Create(NameDefinition.Create(AutoName.Instance.CreateNew("Closure")))
                                     .With(fields)
                                     .With(cons)
                                     .With(lambda)
                                     .Parents(lambda.CreateFunctionInterface());

            return(functor);
        }
Ejemplo n.º 17
0
        public IErrorReporter ErrorTransitiveMutabilityTypeInheritance()
        {
            NameResolver resolver = null;

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

                root_ns.AddBuilder(TypeBuilder.Create("Alien")
                                   .SetModifier(EntityModifier.Mutable));

                root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Container", "CCC", VarianceMode.None))
                                   .SetModifier(EntityModifier.Base));

                // we should get error here because the parent should evaluate to mutable type, and current one is non-mutable
                NameReference parent_name = NameReference.Create("Container", NameReference.Create("Alien"));
                root_ns.AddBuilder(TypeBuilder.Create("Done")
                                   .Parents(parent_name));

                resolver = NameResolver.Create(env);

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

            return(resolver);
        }
Ejemplo n.º 18
0
 public static FunctionDefinition CreateSetter(INameReference typeName, Block body, EntityModifier modifier = null)
 {
     return(FunctionDefinition.CreateFunction(EntityModifier.Accessor | modifier | EntityModifier.Mutable,
                                              NameDefinition.Create(NameFactory.PropertySetter),
                                              null,
                                              new[] { FunctionParameter.Create(NameFactory.PropertySetterValueParameter, typeName) },
                                              ExpressionReadMode.OptionalUse,
                                              NameFactory.UnitNameReference(),
                                              body));
 }
Ejemplo n.º 19
0
        public IErrorReporter InternalDirectTranslationTables()
        {
            NameResolver resolver = null;

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

                const string parent_typename = "Oldman";
                const string parent_elemtype = "PT";

                FunctionDefinition base_func = FunctionBuilder.CreateDeclaration("getMe",
                                                                                 ExpressionReadMode.CannotBeRead,
                                                                                 NameFactory.ReferenceNameReference(parent_elemtype));
                TypeDefinition parent = root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create(parent_typename,
                                                                                                    TemplateParametersBuffer.Create(parent_elemtype).Values))
                                                           .SetModifier(EntityModifier.Abstract)
                                                           .With(base_func));

                const string child_typename = "Kid";
                const string child_elemtype = "CT";

                FunctionDefinition deriv_func = FunctionBuilder.Create("getMe",
                                                                       ExpressionReadMode.CannotBeRead,
                                                                       NameFactory.ReferenceNameReference(child_elemtype),
                                                                       Block.CreateStatement(Return.Create(Undef.Create())))
                                                .SetModifier(EntityModifier.Override);
                TypeDefinition child = root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create(child_typename,
                                                                                                   TemplateParametersBuffer.Create(child_elemtype).Values))
                                                          .Parents(NameReference.Create(parent_typename, NameReference.Create(child_elemtype)))
                                                          .With(deriv_func));

                resolver = NameResolver.Create(env);

                // testing here template translation
                EntityInstance  child_ancestor = child.Inheritance.OrderedAncestorsWithoutObject.Single();
                IEntityInstance translated     = base_func.ResultTypeName.Evaluation.Components.TranslateThrough(child_ancestor);

                // we have single function overriden, so it is easy to debug and spot if something goes wrong
                bool result = FunctionDefinitionExtension.IsDerivedOf(resolver.Context, deriv_func, base_func, child_ancestor);

                Assert.IsTrue(result);
            }

            return(resolver);
        }
Ejemplo n.º 20
0
        public IErrorReporter ErrorViolatingConstConstraint()
        {
            NameResolver resolver = null;

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

                root_ns.AddBuilder(TypeBuilder.Create("Bar")
                                   .SetModifier(EntityModifier.Mutable));
                root_ns.AddBuilder(TypeBuilder.Create("Foo"));

                // we build type Point<T> with enforced "const" on T -- meaning we can pass only trully immutable types
                // as T
                VariableDeclaration field = VariableDeclaration.CreateStatement("m", NameReference.Create("T"),
                                                                                Undef.Create(), modifier: EntityModifier.Public);
                TypeDefinition point_type = root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Point",
                                                                                                        TemplateParametersBuffer.Create().Add("T").Values))
                                                               .Constraints(ConstraintBuilder.Create("T")
                                                                            .SetModifier(EntityModifier.Const))
                                                               .With(field));

                // Bar is mutable type, so we cannot construct Point<Bar> since Point requires immutable type
                NameReference wrong_type = NameReference.Create("Point", NameReference.Create("Bar"));
                var           func_def   = root_ns.AddBuilder(FunctionBuilder.Create(
                                                                  "foo", null,
                                                                  ExpressionReadMode.OptionalUse,
                                                                  NameFactory.UnitNameReference(),

                                                                  Block.CreateStatement(new[] {
                    VariableDeclaration.CreateStatement("x", NameReference.Create("Point", NameReference.Create("Foo")), Undef.Create()),
                    VariableDeclaration.CreateStatement("y", wrong_type, Undef.Create()),
                    ExpressionFactory.Readout("x"),
                    ExpressionFactory.Readout("y"),
                })));


                resolver = NameResolver.Create(env);

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

            return(resolver);
        }
Ejemplo n.º 21
0
 public static FunctionDefinition CreateAutoSetter(string autoFieldName,
                                                   INameReference typeName, EntityModifier modifier = null)
 {
     return(FunctionDefinition.CreateFunction(EntityModifier.Mutable | EntityModifier.Accessor | modifier,
                                              NameDefinition.Create(NameFactory.PropertySetter),
                                              null,
                                              new[] { FunctionParameter.Create(NameFactory.PropertySetterValueParameter, typeName) },
                                              ExpressionReadMode.OptionalUse,
                                              NameFactory.UnitNameReference(),
                                              Block.CreateStatement(new[] {
         Assignment.CreateStatement(
             NameReference.CreateThised(autoFieldName),
             NameReference.Create(NameFactory.PropertySetterValueParameter))
     })));
 }
Ejemplo n.º 22
0
        private FunctionDefinition(EntityModifier modifier,
                                   NameDefinition name,
                                   NameDefinition label,
                                   IEnumerable <TemplateConstraint> constraints,
                                   IEnumerable <FunctionParameter> parameters,
                                   ExpressionReadMode callMode,
                                   INameReference result,
                                   FunctionCall constructorChainCall,
                                   Block body,
                                   IEnumerable <NameReference> includes,
                                   IEnumerable <LabelReference> friends)
            : base(modifier | (body == null ? EntityModifier.Abstract : EntityModifier.None), name, constraints, includes)
        {
            parameters = parameters ?? Enumerable.Empty <FunctionParameter>();

            this.Label        = label ?? NameDefinition.Create(name.Name);
            this.AccessGrants = (friends ?? Enumerable.Empty <LabelReference>()).StoreReadOnly();
            this.Parameters   = parameters.Indexed().StoreReadOnlyList();
            setResultParameter(result);
            this.IsResultTypeNameInfered = result == null;
            if (this.IsResultTypeNameInfered)
            {
                this.resultTypeCandidates = new List <IEntityInstance>();
            }
            this.UserBody = body;
            this.CallMode = callMode;

            // attaching zero-constructor call to the body of the function will be done when attaching entire function to a type
            if (constructorChainCall != null)
            {
                this.UserBody.SetConstructorChainCall(constructorChainCall);
            }

            if (this.IsLambdaInvoker)
            {
                this.LambdaTrap = new LambdaTrap();
            }

            this.attachPostConstructor();

            this.flow = Later.Create(() => ExecutionFlow.CreatePath(UserBody));
            this.constructionCompleted = true;

            if (!IsValidMutableName(this.Name.Name, this.Modifier))
            {
                throw new ArgumentException($"Mutable function has to be marked with name as well {this.Name}");
            }
        }
Ejemplo n.º 23
0
        // used for creating embedded type definitions of type parameters, e.g. Tuple<T1,T2>, here we create T1 and T2
        public static TypeDefinition CreateTypeParameter(TemplateParameter typeParameter)
        {
            EntityModifier modifier = typeParameter.Constraint.Modifier;

            if (typeParameter.Constraint.HasFunctions.Any())
            {
                modifier |= EntityModifier.Protocol;
            }
            else
            {
                modifier |= EntityModifier.Base | EntityModifier.Interface;
            }
            return(new TypeDefinition(modifier, false, NameDefinition.Create(typeParameter.Name), null,
                                      typeParameter.Constraint.InheritsNames, typeParameter.Constraint.HasFunctions,
                                      typeParameter, includes: null));
        }
Ejemplo n.º 24
0
        public IErrorReporter OutgoingConversion()
        {
            NameResolver resolver = null;

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

                var type_foo_def = root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Foo"))
                                                      .With(FunctionBuilder.Create(
                                                                NameFactory.ConvertFunctionName,
                                                                null, ExpressionReadMode.ReadRequired, NameReference.Create("Bar"),
                                                                Block.CreateStatement(new IExpression[] { Return.Create(Undef.Create()) }))
                                                            .SetModifier(EntityModifier.Implicit))
                                                      // added second conversion to check if compiler correctly disambiguate the call
                                                      .With(FunctionBuilder.Create(
                                                                NameFactory.ConvertFunctionName,
                                                                null, ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference(),
                                                                Block.CreateStatement(new IExpression[] { Return.Create(Undef.Create()) }))
                                                            .SetModifier(EntityModifier.Implicit)));
                var type_bar_def = root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Bar")));


                root_ns.AddBuilder(FunctionBuilder.Create(
                                       "wrapper",
                                       ExpressionReadMode.OptionalUse,
                                       NameFactory.UnitNameReference(),

                                       Block.CreateStatement(new[] {
                    VariableDeclaration.CreateStatement("f", NameReference.Create("Foo"),
                                                        initValue: Undef.Create()),
                    VariableDeclaration.CreateStatement("b", NameReference.Create("Bar"),
                                                        initValue: NameReference.Create("f")),
                    ExpressionFactory.Readout("b")
                })));

                resolver = NameResolver.Create(env);

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

            return(resolver);
        }
Ejemplo n.º 25
0
        private Alias(EntityModifier modifier, string name, INameReference replacement)
            : base(ExpressionReadMode.CannotBeRead)
        {
            if (name == null)
            {
                throw new ArgumentNullException();
            }

            this.Modifier    = (modifier ?? EntityModifier.None) | EntityModifier.Static;
            this.Name        = NameDefinition.Create(name);
            this.Replacement = replacement;

            this.instancesCache = new EntityInstanceCache(this, () => GetInstance(TypeMutability.None,
                                                                                  TemplateTranslation.CreateParameterless(this), Lifetime.Timeless));

            this.attachPostConstructor();
        }
Ejemplo n.º 26
0
        public IErrorReporter InheritanceMatching()
        {
            NameResolver resolver = null;

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

                var unrelated_type = system_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Separate")));
                var abc_type       = system_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("ABC")));
                var derived_type   = system_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Deriv"))
                                                          .Parents(NameReference.Create("ABC")));
                var foo_type = system_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Foo", "V", VarianceMode.Out))
                                                    .Parents(NameReference.Create("ABC")));
                var tuple_type = system_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Tuple", "T", VarianceMode.None))
                                                      .Parents(NameReference.Create("Foo", NameReference.Create("T"))));


                var separate_ref    = system_ns.AddNode(NameReference.Create("Separate"));
                var abc_ref         = system_ns.AddNode(NameReference.Create("ABC"));
                var deriv_ref       = system_ns.AddNode(NameReference.Create("Deriv"));
                var tuple_deriv_ref = system_ns.AddNode(NameReference.Create("Tuple", NameReference.Create("Deriv")));
                var foo_abc_ref     = system_ns.AddNode(NameReference.Create("Foo", NameReference.Create("ABC")));
                var tuple_abc_ref   = system_ns.AddNode(NameReference.Create("Tuple", NameReference.Create("ABC")));
                var foo_deriv_ref   = system_ns.AddNode(NameReference.Create("Foo", NameReference.Create("Deriv")));

                resolver = NameResolver.Create(env);

                Assert.AreNotEqual(TypeMatch.Same, separate_ref.Binding.Match.Instance.MatchesTarget(resolver.Context, abc_ref.Binding.Match.Instance,
                                                                                                     TypeMatching.Create(env.Options.InterfaceDuckTyping, allowSlicing: true)));
                Assert.AreEqual(TypeMatch.Substitute, deriv_ref.Binding.Match.Instance.MatchesTarget(resolver.Context, abc_ref.Binding.Match.Instance,
                                                                                                     TypeMatching.Create(env.Options.InterfaceDuckTyping, allowSlicing: true)));
                Assert.AreEqual(TypeMatch.Substitute, tuple_deriv_ref.Binding.Match.Instance.MatchesTarget(resolver.Context, foo_abc_ref.Binding.Match.Instance,
                                                                                                           TypeMatching.Create(env.Options.InterfaceDuckTyping, allowSlicing: true)));
                TypeMatch match = tuple_abc_ref.Binding.Match.Instance.MatchesTarget(resolver.Context, foo_deriv_ref.Binding.Match.Instance,
                                                                                     TypeMatching.Create(env.Options.InterfaceDuckTyping, allowSlicing: true));
                Assert.AreNotEqual(TypeMatch.Same, match);
                Assert.AreNotEqual(TypeMatch.Substitute, match);
            }

            return(resolver);
        }
Ejemplo n.º 27
0
        public IErrorReporter ErrorVariableNotUsed()
        {
            NameResolver resolver = null;

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

                VariableDeclaration member = VariableDeclaration.CreateStatement("x", NameFactory.Int64NameReference(),
                                                                                 Int64Literal.Create("5"));
                root_ns.AddBuilder(TypeBuilder.Create("Thing")
                                   .With(member));

                var            decl1      = VariableDeclaration.CreateStatement("s", NameFactory.Int64NameReference(), null);
                var            decl2      = VariableDeclaration.CreateStatement("t", NameFactory.Int64NameReference(), null);
                NameDefinition loop_label = NameDefinition.Create("here");
                var            loop       = Loop.CreateFor(loop_label,
                                                           init: null,
                                                           condition: null,
                                                           step: null,
                                                           body: new IExpression[] { decl1, decl2 });
                var func_def = root_ns.AddBuilder(FunctionBuilder.Create(
                                                      "main",
                                                      ExpressionReadMode.OptionalUse,
                                                      NameFactory.UnitNameReference(),

                                                      Block.CreateStatement(new IExpression[] {
                    loop,
                })));

                resolver = NameResolver.Create(env);

                Assert.AreEqual(4, resolver.ErrorManager.Errors.Count);
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.BindableNotUsed, decl1.Name));
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.BindableNotUsed, decl2.Name));
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.BindableNotUsed, loop_label));
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.BindableNotUsed, member.Name));
            }

            return(resolver);
        }
Ejemplo n.º 28
0
        public IErrorReporter UnionMatching()
        {
            NameResolver resolver = null;

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

                root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Separate")));
                root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("ABC")));
                root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Deriv"))
                                   .Parents(NameReference.Create("ABC")));
                root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Deriz"))
                                   .Parents(NameReference.Create("Deriv")));
                root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("qwerty"))
                                   .Parents(NameReference.Create("ABC")));
                root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("sink"))
                                   .Parents(NameReference.Create("qwerty"), NameReference.Create("Separate")));


                var separate_deriv_union = root_ns.AddNode(NameReferenceUnion.Create(NameReference.Create("Separate"), NameReference.Create("Deriv")));
                var separate_deriz_union = root_ns.AddNode(NameReferenceUnion.Create(NameReference.Create("Separate"), NameReference.Create("Deriz")));
                var separate_abc_union   = root_ns.AddNode(NameReferenceUnion.Create(NameReference.Create("Separate"), NameReference.Create("ABC")));
                var sink_union           = root_ns.AddNode(NameReferenceUnion.Create(NameReference.Create("sink")));
                var sink_deriv_union     = root_ns.AddNode(NameReferenceUnion.Create(NameReference.Create("sink"), NameReference.Create("Deriv")));

                resolver = NameResolver.Create(env);

                Assert.AreEqual(TypeMatch.Substitute, separate_deriz_union.Evaluation.Components.MatchesTarget(resolver.Context,
                                                                                                               separate_deriv_union.Evaluation.Components, TypeMatching.Create(env.Options.InterfaceDuckTyping, allowSlicing: true)));
                Assert.AreEqual(TypeMatch.Substitute, sink_union.Evaluation.Components.MatchesTarget(resolver.Context,
                                                                                                     separate_abc_union.Evaluation.Components, TypeMatching.Create(env.Options.InterfaceDuckTyping, allowSlicing: true)));
                TypeMatch match = sink_deriv_union.Evaluation.Components.MatchesTarget(resolver.Context,
                                                                                       separate_deriz_union.Evaluation.Components, TypeMatching.Create(env.Options.InterfaceDuckTyping, allowSlicing: true));
                Assert.AreNotEqual(TypeMatch.Same, match);
                Assert.AreNotEqual(TypeMatch.Substitute, match);
            }

            return(resolver);
        }
Ejemplo n.º 29
0
        private IInterpreter duckVirtualCallWithGenericBase(Options options)
        {
            var interpreter = new Interpreter.Interpreter();

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env     = Environment.Create(options.SetMutability(mutability));
                var root_ns = env.Root;

                root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("X", TemplateParametersBuffer.Create()
                                                                            .Add("T").Values))
                                   .SetModifier(options.InterfaceDuckTyping ? EntityModifier.Interface : EntityModifier.Protocol)
                                   .With(FunctionBuilder.CreateDeclaration(
                                             "bar",
                                             ExpressionReadMode.ReadRequired,
                                             NameReference.Create("T"))));

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

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

                ExecValue result = interpreter.TestRun(env);

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

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

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

                root_ns.AddBuilder(TypeBuilder.CreateInterface(NameDefinition.Create("IBar",
                                                                                     TemplateParametersBuffer.Create("TA").Values))
                                   .With(FunctionBuilder.CreateDeclaration(
                                             "barend", "FA", VarianceMode.None,
                                             ExpressionReadMode.OptionalUse,
                                             NameFactory.Int64NameReference())
                                         .Constraints(ConstraintBuilder.Create("FA").Inherits(NameReference.Create("TA")))
                                         .Parameters(FunctionParameter.Create("x", NameReference.Create("TA")))));

                TypeDefinition type_impl = root_ns.AddBuilder(
                    TypeBuilder.Create(NameDefinition.Create("Impl", TemplateParametersBuffer.Create("TB").Values))
                    .With(FunctionBuilder.Create(
                              "barend", TemplateParametersBuffer.Create("FB").Values,
                              ExpressionReadMode.OptionalUse,
                              NameFactory.Int64NameReference(),
                              Block.CreateStatement(new[] {
                    Return.Create(Int64Literal.Create("2"))
                }))
                          .Parameters(FunctionParameter.Create("x", NameReference.Create("TB"),
                                                               usageMode: ExpressionReadMode.CannotBeRead))
                          .Constraints(ConstraintBuilder.Create("FB").Inherits(NameReference.Create("TB")))
                          .SetModifier(EntityModifier.Override))
                    .Parents(NameReference.Create("IBar", NameReference.Create("TB"))));

                resolver = NameResolver.Create(env);

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

            return(resolver);
        }