Example #1
0
        /// <summary>
        /// Gets weight of the given type match.
        /// </summary>
        /// <param name="match">The type match to get weight for.</param>
        /// <returns>The weight of given type match.</returns>
        private static int GetWeight(TypeMatch match)
        {
            switch (match)
            {
            case TypeMatch.Exact:
                return(5);

            case TypeMatch.Assignable:
                return(4);

            case TypeMatch.Widened:
                return(3);

            case TypeMatch.Narrowed:
                return(2);

            case TypeMatch.Unknown:
                return(1);

            case TypeMatch.None:
                return(0);

            default:
                throw new ArgumentOutOfRangeException("match");
            }
        }
Example #2
0
        public override IInvoker Refer(URL url)
        {
            OptimizeSerialization(url);
            var      id      = url.GetId();
            var      name    = url.ServiceName;
            IInvoker invoker = null;

            lock (_invokers)
            {
                if (_invokers.TryGetValue(name, out var list))
                {
                    invoker = list.FirstOrDefault(c => c.InvokerId == id);
                    if (invoker != null)
                    {
                        return(invoker);
                    }
                }
                else
                {
                    list = new List <IInvoker>();
                    _invokers.TryAdd(name, list);
                }
                var type = TypeMatch.MatchType(name);
                invoker           = new DubboInvoker(type, url, GetClients(url), null);
                invoker.InvokerId = id;
                list.Add(invoker);
            }
            return(invoker);
        }
Example #3
0
        public void TestCollection()
        {
            Base a = new Base();
            Base b = new Base();
            Base c = new Base();
            Base d = new Base();
            CollectionDerived e = new CollectionDerived()
            {
                Child = a, Parents = new List <Base>()
                {
                    a, b, c, d
                }
            };

            TypeConfiguration.TrustedTypes = TypeMatch.Assembly(typeof(SerializerTests).Assembly);
            ISerializationService serializer = Container.Resolve <ISerializationService>();
            string json = serializer.Serialize(e);

            Console.WriteLine(json);
            Base newE = serializer.Deserialize <Base>(json);

            Assert.IsInstanceOfType(newE, typeof(CollectionDerived));
            var listE = (CollectionDerived)newE;

            Assert.IsNotNull(listE.Parents);
            Assert.AreEqual(4, listE.Parents.Count());
            Assert.AreEqual(listE.Child, listE.Parents.ElementAt(0));
        }
Example #4
0
        internal void InferResultType(ComputationContext ctx)
        {
            if (!this.resultTypeCandidates.Any()) // no returns
            {
                setResultParameter(ctx.Env.UnitType.InstanceOf.NameOf);
            }
            else
            {
                IEntityInstance common = this.resultTypeCandidates.First();
                foreach (IEntityInstance candidate in this.resultTypeCandidates.Skip(1))
                {
                    if (!TypeMatcher.LowestCommonAncestor(ctx, common, candidate, out common))
                    {
                        ctx.AddError(ErrorCode.CannotInferResultType, this);
                        setResultParameter(Environment.JokerInstance.NameOf);
                        return;
                    }
                }

                foreach (IEntityInstance candidate in this.resultTypeCandidates)
                {
                    // it is tempting to allowing conversions here, but it would mean that we have back to all "returns"
                    // to apply such conversions, besides such fluent result type is a bit of a stretch
                    TypeMatch match = candidate.MatchesTarget(ctx, common, TypeMatching.Create(ctx.Env.Options.InterfaceDuckTyping, allowSlicing: false));
                    if (match != TypeMatch.Same && match != TypeMatch.Substitute)
                    {
                        ctx.AddError(ErrorCode.CannotInferResultType, this);
                        setResultParameter(Environment.JokerInstance.NameOf);
                        return;
                    }
                }

                setResultParameter(common.NameOf);
            }
        }
Example #5
0
        private void OptimizeSerialization(URL url)
        {
            String className = url.GetParameter(Constants.OptimizerKey, "");

            if (string.IsNullOrEmpty(className) || _optimizers.Contains(className))
            {
                return;
            }
            Logger.Info("Optimizing the serialization process for Kryo, FST, etc...");
            var clazz = TypeMatch.MatchType(className);

            if (!typeof(ISerializationOptimizer).IsAssignableFrom(clazz))
            {
                throw new Exception("The serialization optimizer " + className + " isn't an instance of " + typeof(ISerializationOptimizer).FullName);
            }
            ISerializationOptimizer optimizer = (ISerializationOptimizer)Activator.CreateInstance(clazz);

            if (optimizer.GetSerializableClasses() == null)
            {
                return;
            }
            foreach (var c in optimizer.GetSerializableClasses())
            {
                SerializableClassRegistry.RegisterClass(c);
            }
            _optimizers.Add(className);
        }
Example #6
0
        public static bool MatchTypes(ComputationContext ctx, IEntityInstance lhsTypeInstance, IEntityInstance rhsTypeInstance)
        {
            TypeMatch lhs_rhs_match = lhsTypeInstance.MatchesTarget(ctx, rhsTypeInstance,
                                                                    TypeMatching.Create(duckTyping: false, allowSlicing: true).WithIgnoredMutability(true));

            return(lhs_rhs_match.Passed);
        }
Example #7
0
        public void TestUntrustedOut()
        {
            Derived d = new Derived();

            TypeConfiguration.TrustedTypes = TypeMatch.Type <Base>();
            ISerializationService serializer = Container.Resolve <ISerializationService>();

            Assert.ThrowsException <TypeMatchException>(() => serializer.Serialize(d));
        }
Example #8
0
        private void TestValue <T>(T value)
        {
            TypeConfiguration.TrustedTypes = TypeMatch.Assembly(typeof(SerializerTests).Assembly);
            ISerializationService serializer = Container.Resolve <ISerializationService>();
            string json = serializer.Serialize(value);

            Console.WriteLine(json);
            T newVal = serializer.Deserialize <T>(json);

            Assert.AreEqual(value, newVal, $"Value type serialization failed on {typeof(T).Name} native serializer.");
        }
Example #9
0
 public IMatchable GetMatchable(TypeMatch Type)
 {
     if (Type == TypeMatch.Project)
     {
         return(new MatchModel());
     }
     else
     {
         return(new MatchModel());
     }
 }
Example #10
0
 public IMatchDA GetMatch(TypeMatch Type)
 {
     if (Type == TypeMatch.Project)
     {
         return(new MatchProjectDA());
     }
     else
     {
         return(new MatchProjectDA());
     }
 }
 public void CreateBattleInfo()
 {
     typeMatch          = TypeMatch.BO1;
     countBattleInMatch = 1;
     winCountEnemy      = 0;
     winCountPlayer     = 0;
     turn         = 0;
     playerTurn   = false;
     endBattle    = false;
     battleStates = PerformAction.WAIT;
     //this.PostEvent(EventID.CreateBattle);
 }
Example #12
0
        public void ExplicitValueSerialize()
        {
            Vector2 vector = new Vector2(10, 40);

            TypeConfiguration.TrustedTypes = TypeMatch.Type <Vector2>();
            ISerializationService serializer = Container.Resolve <ISerializationService>();
            string json = serializer.Serialize(vector);

            Console.WriteLine(json);
            Vector2 newVector = serializer.Deserialize <Vector2>(json);

            Assert.AreEqual(vector, newVector);
        }
Example #13
0
        public static bool IsCopyInitConstructor(this FunctionDefinition @this, ComputationContext ctx)
        {
            if ([email protected]() || @this.Parameters.Count != 1)
            {
                return(false);
            }

            IEntityInstance param_type      = @this.Parameters.Single().TypeName.Evaluation.Components;
            EntityInstance  containing_type = @this.ContainingType().InstanceOf;
            TypeMatch       match           = param_type.MatchesTarget(ctx, containing_type,
                                                                       TypeMatching.Create(duckTyping: false, allowSlicing: false).WithIgnoredMutability(true));

            return(match.HasFlag(TypeMatch.Same));
        }
Example #14
0
        private void attemptMatches(TypeBuilder tBuilder, List <MethodInfo> requiredMethods, List <MethodInfo> possibleMatches)
        {
            foreach (MethodInfo requiredMethod in requiredMethods)
            {
                foreach (MethodInfo attempt in possibleMatches)
                {
                    bool      exactMatch  = true;
                    TypeMatch returnMatch = canMatchType(attempt.ReturnType, requiredMethod.ReturnType);
                    if (returnMatch == TypeMatch.NoMatch)
                    {
                        continue;
                    }
                    else if (exactMatch && returnMatch != TypeMatch.ExactMatch)
                    {
                        exactMatch = false;
                    }

                    var requireParams = requiredMethod.GetParameters();
                    var attemptParams = attempt.GetParameters();
                    var paramMatches  = new TypeMatch[requireParams.Length];

                    bool matchFailed = false;
                    for (int i = 0; i < requireParams.Length; i++)
                    {
                        TypeMatch paramMatch = canMatchType(attemptParams[i].ParameterType, requireParams[i].ParameterType);
                        if (returnMatch == TypeMatch.NoMatch)
                        {
                            matchFailed = true;
                            break;
                        }
                        else if (exactMatch && paramMatch != TypeMatch.ExactMatch)
                        {
                            exactMatch = false;
                        }

                        paramMatches[i] = paramMatch;
                    }

                    if (!matchFailed)
                    {
                        if (!exactMatch)
                        {
                            writeMappingMethod(tBuilder, requiredMethod, attempt, returnMatch, paramMatches);
                        }
                        break;
                    }
                }
            }
        }
Example #15
0
        public void TestParameterConstructor()
        {
            Base          a = new Base();
            BaseWithConst b = new BaseWithConst(a, "Fred");

            TypeConfiguration.TrustedTypes = TypeMatch.Assembly(typeof(SerializerTests).Assembly);
            ISerializationService serializer = Container.Resolve <ISerializationService>();
            string json = serializer.Serialize(b);

            Console.WriteLine(json);
            BaseWithConst newB = serializer.Deserialize <BaseWithConst>(json);

            Assert.IsInstanceOfType(newB.Child, typeof(Base));
            Assert.AreEqual(newB.Name, "Fred");
        }
Example #16
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);
        }
Example #17
0
        public void TestNoConstructor()
        {
            Base           a = new Base();
            DerivedNoConst b = new DerivedNoConst(a, "Fred");

            a.Child = b;

            TypeConfiguration.TrustedTypes = TypeMatch.Assembly(typeof(SerializerTests).Assembly);
            ISerializationService serializer = Container.Resolve <ISerializationService>();
            string json = serializer.Serialize(a);

            Console.WriteLine(json);
            Base newA = serializer.Deserialize <Base>(json);

            Assert.AreEqual(newA.Child.Child, newA);
            Assert.IsInstanceOfType(newA.Child, typeof(Derived));
            Assert.AreEqual(((Derived)newA.Child).Name, "Fred");
        }
Example #18
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);
        }
        /// <summary>
        /// This returns useful information on a match
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            string matchInfo = "wrong name";

            if (Score >= PropertyMatch.PerfectMatchValue)
            {
                matchInfo = $"{PropertyInfo.PropertyType.Name} {PropertyInfo.Name}";
            }
            else if (Score <= NoMatchAtAll)
            {
                matchInfo = "nothing matches";
            }
            else if (!NameMatched)
            {
                matchInfo = "Name not match, but type is " + TypeMatch.ToString().SplitPascalCase();
            }

            return(matchInfo);
        }
Example #20
0
        public void CustomSerializer()
        {
            GuidDerived a = new GuidDerived()
            {
                Child = null, Id = Guid.NewGuid()
            };
            Base b = new Base()
            {
                Child = a
            };

            TypeConfiguration.TrustedTypes = TypeMatch.Assembly(typeof(SerializerTests).Assembly);
            ISerializationService serializer = Container.Resolve <ISerializationService>();
            string json = serializer.Serialize(b);

            Console.WriteLine(json);
            Base newB = serializer.Deserialize <Base>(json);

            Assert.IsInstanceOfType(newB.Child, typeof(GuidDerived));
            Assert.AreEqual(a.Id, ((GuidDerived)newB.Child).Id);
        }
Example #21
0
        /// <summary>
        /// 初始化Dubbo消费端
        /// </summary>
        public static void Init(ProtocolConfig protocol, RegistryConfig registryConfig)
        {
            DependencyRegistor.Register("Dubbo.Net.Proxy");
            var registryUrl     = URL.ValueOf(registryConfig.ToRegistryString());
            var registryFactory = ObjectFactory.GetInstance <IRegistryFactory>(registryUrl.Protocol);
            var registry        = registryFactory.GetRegistry(registryUrl);
            var assemblies      = AppDomain.CurrentDomain.GetAssemblies();
            var generator       = ObjectFactory.GetInstance <IServiceProxyGenerater>();
            var types           = new List <Type>();

            foreach (var assembly in assemblies)
            {
                var ts = assembly.GetTypes();
                foreach (var type in ts)
                {
                    if (!type.IsInterface)
                    {
                        continue;
                    }
                    var attr = type.GetCustomAttribute <ReferAttribute>();
                    if (attr != null)
                    {
                        types.Add(type);
                    }
                }
            }

            foreach (var type in types)
            {
                TypeMatch.RegisterType(type);
                var url     = ReferenceConfig.Init(type, registryConfig, protocol);
                var impl    = generator.GenerateProxys(type);
                var ctor    = impl.GetConstructor(new[] { typeof(URL) });
                var service = ctor.Invoke(new object[] { url });
                ObjectFactory.Register(type, impl);
                ObjectFactory.Register(impl, service);
                registry.Subscribe(url.ServiceName).Wait();
            }
            registry.Start();
        }
Example #22
0
        private List <TableRowItemDefinition> GetActiveTableRowDefinition(TableControlBody tableBody, PSObject so)
        {
            if (tableBody.optionalDefinitionList.Count == 0)
            {
                // we do not have any override, use default
                return(tableBody.defaultDefinition.rowItemDefinitionList);
            }

            // see if we have an override that matches
            TableRowDefinition matchingRowDefinition = null;

            var       typeNames = so.InternalTypeNames;
            TypeMatch match     = new TypeMatch(_expressionFactory, _typeInfoDatabase, typeNames);

            foreach (TableRowDefinition x in tableBody.optionalDefinitionList)
            {
                if (match.PerfectMatch(new TypeMatchItem(x, x.appliesTo)))
                {
                    matchingRowDefinition = x;
                    break;
                }
            }

            if (matchingRowDefinition == null)
            {
                matchingRowDefinition = match.BestMatch as TableRowDefinition;
            }

            if (matchingRowDefinition == null)
            {
                Collection <string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames);
                if (typesWithoutPrefix != null)
                {
                    match = new TypeMatch(_expressionFactory, _typeInfoDatabase, typesWithoutPrefix);

                    foreach (TableRowDefinition x in tableBody.optionalDefinitionList)
                    {
                        if (match.PerfectMatch(new TypeMatchItem(x, x.appliesTo)))
                        {
                            matchingRowDefinition = x;
                            break;
                        }
                    }

                    if (matchingRowDefinition == null)
                    {
                        matchingRowDefinition = match.BestMatch as TableRowDefinition;
                    }
                }
            }

            if (matchingRowDefinition == null)
            {
                // no matching override, use default
                return(tableBody.defaultDefinition.rowItemDefinitionList);
            }

            // we have an override, we need to compute the merge of the active cells
            List <TableRowItemDefinition> activeRowItemDefinitionList = new List <TableRowItemDefinition>();
            int col = 0;

            foreach (TableRowItemDefinition rowItem in matchingRowDefinition.rowItemDefinitionList)
            {
                // Check if the row is an override or not
                if (rowItem.formatTokenList.Count == 0)
                {
                    // It's a place holder, use the default
                    activeRowItemDefinitionList.Add(tableBody.defaultDefinition.rowItemDefinitionList[col]);
                }
                else
                {
                    // Use the override
                    activeRowItemDefinitionList.Add(rowItem);
                }

                col++;
            }

            return(activeRowItemDefinitionList);
        }
Example #23
0
        private List <TableRowItemDefinition> GetActiveTableRowDefinition(TableControlBody tableBody, PSObject so)
        {
            if (tableBody.optionalDefinitionList.Count == 0)
            {
                return(tableBody.defaultDefinition.rowItemDefinitionList);
            }
            TableRowDefinition bestMatch         = null;
            ConsolidatedString internalTypeNames = so.InternalTypeNames;
            TypeMatch          match             = new TypeMatch(this.expressionFactory, this.typeInfoDatabase, internalTypeNames);

            foreach (TableRowDefinition definition2 in tableBody.optionalDefinitionList)
            {
                if (match.PerfectMatch(new TypeMatchItem(definition2, definition2.appliesTo)))
                {
                    bestMatch = definition2;
                    break;
                }
            }
            if (bestMatch == null)
            {
                bestMatch = match.BestMatch as TableRowDefinition;
            }
            if (bestMatch == null)
            {
                Collection <string> typeNames = Deserializer.MaskDeserializationPrefix(internalTypeNames);
                if (typeNames != null)
                {
                    match = new TypeMatch(this.expressionFactory, this.typeInfoDatabase, typeNames);
                    foreach (TableRowDefinition definition3 in tableBody.optionalDefinitionList)
                    {
                        if (match.PerfectMatch(new TypeMatchItem(definition3, definition3.appliesTo)))
                        {
                            bestMatch = definition3;
                            break;
                        }
                    }
                    if (bestMatch == null)
                    {
                        bestMatch = match.BestMatch as TableRowDefinition;
                    }
                }
            }
            if (bestMatch == null)
            {
                return(tableBody.defaultDefinition.rowItemDefinitionList);
            }
            List <TableRowItemDefinition> list = new List <TableRowItemDefinition>();
            int num = 0;

            foreach (TableRowItemDefinition definition4 in bestMatch.rowItemDefinitionList)
            {
                if (definition4.formatTokenList.Count == 0)
                {
                    list.Add(tableBody.defaultDefinition.rowItemDefinitionList[num]);
                }
                else
                {
                    list.Add(definition4);
                }
                num++;
            }
            return(list);
        }
Example #24
0
        private Type Match(ArgumentSet arguments)
        {
            bool useDefault = arguments.Any(a => a.Value.IsDefault);

            var matchingTypes = new List <TypeMatch>();

            foreach (var type in Types)
            {
                object[] customAttributes = type.GetCustomAttributes(typeof(DefaultArgumentsAttribute), false);
                bool     isDefaultArgs    = customAttributes.Length > 0;

                bool isMatch = isDefaultArgs && arguments.Count == 0;

                var matchingType = new TypeMatch
                {
                    Type = type
                };

                foreach (var argument in arguments)
                {
                    if (isDefaultArgs && useDefault && argument.Value.IsDefault)
                    {
                        isMatch = true;
                        argument.Value.IsDefault = true;
                        argument.Value.Value     = argument.Key;
                        matchingType.ArgumentMatches++;
                    }
                    else
                    {
                        if (GetPropertyInfo(type, argument.Key) != null)
                        {
                            isMatch = true;
                            matchingType.ArgumentMatches++;
                        }
                    }
                }

                if (isMatch)
                {
                    matchingTypes.Add(matchingType);
                }
            }

            if (matchingTypes.Count == 1)
            {
                return(matchingTypes[0].Type);
            }

            var matchingTypesInOrder = matchingTypes.OrderByDescending(x => x.ArgumentMatches).ToList();

            if (matchingTypes.Count > 1)
            {
                if (matchingTypesInOrder[0].ArgumentMatches == matchingTypesInOrder[1].ArgumentMatches)
                {
                    throw new Exception(string.Format("The arguments [{0}] and [{1}] are non deterministic in respect to the args: {2}",
                                                      matchingTypesInOrder[0].Type.Name,
                                                      matchingTypesInOrder[1].Type.Name,
                                                      arguments));
                }
            }

            TypeMatch matching = matchingTypesInOrder.FirstOrDefault();

            if (matching != null)
            {
                return(matching.Type);
            }

            return(null);
        }
Example #25
0
 /// <summary>
 /// Creates a new <see cref="ReflectionConstructor"/>.
 /// </summary>
 public ReflectionConstructor()
 {
     SupportedTypes = TypeMatch.All();
     Priority       = GraphPriority.Reflection;
 }
Example #26
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);
        }
Example #27
0
        private static IEnumerable <CallResolution> resolveOverloading(IEnumerable <CallResolution> targets)
        {
            if (targets.Count() < 2)
            {
                return(targets);
            }

            // the less, the better
            var arguments_matches = new List <Tuple <CallResolution, List <FunctionOverloadWeight> > >();

            foreach (CallResolution call_target in targets)
            {
                var weights = new List <FunctionOverloadWeight>();
                foreach (FunctionArgument arg in call_target.ExtensionsArguments)
                {
                    FunctionParameter param = call_target.GetParamByArg(arg);
                    var weight = new FunctionOverloadWeight();
                    // prefer non-variadic parameters
                    if (param.IsVariadic)
                    {
                        weight.Penalty += 1;
                    }
                    // prefer concrete type over generic one (foo(Int) better than foo<T>(T))
                    // note we use untranslated param evaluation here to achieve this effect
                    if (!param.Evaluation.Components.IsExactlySame(arg.Evaluation.Components, jokerMatchesAll: true))
                    {
                        weight.Penalty += 2;
                    }

                    // prefer exact match instead more general match (Int->Int is better than Int->Object)
                    IEntityInstance param_trans_eval = call_target.GetTransParamEvalByArg(arg);
                    TypeMatch       m = call_target.TypeMatches[arg.Index].Value;
                    if (m.HasFlag(TypeMatch.Substitute))
                    {
                        weight.Penalty += 4;
                        weight.SubstitutionDistance = m.Distance;
                    }
                    else if (!m.HasFlag(TypeMatch.Same)) // conversions
                    {
                        weight.Penalty += 8;
                    }

                    weights.Add(weight);
                }
                // bonus if optional parameters are explicitly targeted (i.e. default values are not used)
                weights.Add(new FunctionOverloadWeight(call_target.AllParametersUsed() ? 0 : 1));

                arguments_matches.Add(Tuple.Create(call_target, weights));
            }

            Option <Tuple <CallResolution, List <FunctionOverloadWeight> > > best = arguments_matches
                                                                                    .IntransitiveMin((a, b) => Extensions.Tools.HasOneLessNoneGreaterThan(a.Item2, b.Item2, (x, y) => x < y));

            if (best.HasValue)
            {
                return new[] { best.Value.Item1 }
            }
            ;
            else
            {
                return(targets);
            }
        }
Example #28
0
 /// <summary>
 /// Creates a new <see cref="CustomSerializer{T}"/>.
 /// </summary>
 public StringSerializer()
 {
     SupportedTypes = TypeMatch.Type <T>();
 }
Example #29
0
 /// <summary>
 /// Creates a new <see cref="CustomSerializer{T}"/>.
 /// </summary>
 public CustomSerializer()
 {
     SupportedTypes = TypeMatch.Type <T>();
 }
Example #30
0
        public static bool IsDerivedOf(ComputationContext ctx, FunctionDefinition derivedFunc,
                                       FunctionDefinition baseFunc, EntityInstance baseTemplate)
        {
            if (derivedFunc.IsPropertyAccessor(out Property derived_prop))
            {
                if (baseFunc.IsPropertyAccessor(out Property base_prop))
                {
                    // properties have to much and name (kind) of the accessor
                    if (!EntityNameArityComparer.Instance.Equals(derived_prop.Name, base_prop.Name) ||
                        !EntityNameArityComparer.Instance.Equals(derivedFunc.Name, baseFunc.Name))
                    {
                        return(false);
                    }
                }
                // property-getters can override regular methods
                else if (derived_prop.Getter != derivedFunc ||
                         !EntityNameArityComparer.Instance.Equals(derived_prop.Name, baseFunc.Name))
                {
                    return(false);
                }
            }
            // todo: we have to check constraints as well
            else if (!EntityNameArityComparer.Instance.Equals(derivedFunc.Name, baseFunc.Name))
            {
                return(false);
            }

            foreach (Tuple <TemplateParameter, TemplateParameter> param_pair in derivedFunc.Name.Parameters
                     .SyncZip(baseFunc.Name.Parameters))
            {
                if (!TemplateParameterExtension.IsSame(param_pair.Item1, param_pair.Item2, baseTemplate))
                {
                    return(false);
                }
            }

            {
                IEntityInstance base_result_type = baseFunc.ResultTypeName.Evaluation.Components.TranslateThrough(baseTemplate);
                TypeMatch       match            = derivedFunc.ResultTypeName.Evaluation.Components.MatchesTarget(ctx, base_result_type,
                                                                                                                  TypeMatching.Create(ctx.Env.Options.InterfaceDuckTyping, allowSlicing: false));
                if (match != TypeMatch.Same && match != TypeMatch.Substitute)
                {
                    return(false);
                }
            }

            if (derivedFunc.Parameters.Count != baseFunc.Parameters.Count)
            {
                return(false);
            }

            foreach (Tuple <FunctionParameter, FunctionParameter> param_pair in derivedFunc.Parameters.SyncZip(baseFunc.Parameters))
            {
                if (!FunctionParameterExtension.IsDerivedOf(ctx, param_pair.Item1, param_pair.Item2, baseTemplate))
                {
                    return(false);
                }
            }

            return(true);
        }