Esempio n. 1
0
        protected virtual void ValidateCompositeTypeModel(CompositeValidationResult result, CompositeModel compositeModel)
        {
            // TODO validate that none of fragments have abstract non-composite methods.

            if (compositeModel.PublicTypes.Any())
            {
                Type   firstType  = compositeModel.PublicTypes.First();
                Type[] gArgs      = firstType.GetGenericArguments();
                Int32  gArgsCount = gArgs.Length;
                foreach (Type cType in compositeModel.GetAllCompositeTypes())
                {
                    this.ValidateCompositeType(result, compositeModel, cType);
                }

                foreach (Type fType in compositeModel.GetAllFragmentTypes())
                {
                    this.ValidateFragmentType(result, compositeModel, fType);
                }

                foreach (Type type in compositeModel.PublicTypes)
                {
                    this.ValidateCompositeType(result, compositeModel, type);

                    Type[] typeGargs = type.GetGenericArguments();
                    Int32  typeCount = typeGargs.Length;

                    if (typeCount > 0)
                    {
                        if (type.IsGenericTypeDefinition() != firstType.IsGenericTypeDefinition() || typeGargs.Take(Math.Min(gArgsCount, typeCount)).Where((tGArg, idx) => tGArg.IsGenericParameter != gArgs[idx].IsGenericParameter).Any())
                        {
                            result.StructureValidationErrors.Add(ValidationErrorFactory.NewStructureError("All type interfaces must be either genericless, generic type definitions, or having all generic parameters closed.", compositeModel));
                        }
                        else
                        {
                            // TODO generic arguments constraints
                        }
                    }
                }
                if (compositeModel.PublicTypes.Count(pType => !pType
#if WINDOWS_PHONE_APP
                                                     .GetTypeInfo()
#endif
                                                     .IsInterface) > 1)
                {
                    result.StructureValidationErrors.Add(ValidationErrorFactory.NewStructureError("Composite types must contain at most one class, but found the following classes:\n" + String.Join(", ", compositeModel.PublicTypes.Select(pType => !pType
#if WINDOWS_PHONE_APP
                                                                                                                                                                                                                                             .GetTypeInfo()
#endif
                                                                                                                                                                                                                                             .IsInterface)), compositeModel));
                }
            }
            else
            {
                result.StructureValidationErrors.Add(ValidationErrorFactory.NewStructureError("Composite must have at least one public type", compositeModel));
            }
        }
        public CompositeTypeModelImpl(CompositeModel compositeModel, CompositeValidationResultMutable vResult)
        {
            var collectionsFactory = compositeModel.ApplicationModel.CollectionsFactory;

            this._publicCompositeGenericArguments = collectionsFactory.NewListProxy(GetCompositeModelPublicTypeGenericArguments(compositeModel).ToList()).CQ;

            var injThisTypes = compositeModel.GetAllInjectableModelsWithInjectionScope <ThisAttribute>()
                               .Select(inj => new ThisTypeInfo(inj))
                               .ToArray();
            var thisTypesInModel = compositeModel.Methods
                                   .Select(m => m.NativeInfo.DeclaringType)
                                   .Concat(compositeModel.PublicTypes)
                                   .Concat(injThisTypes.Select(inj => inj.resolvedTargetType))
                                   .Concat(compositeModel.GetAllFragmentTypes().SelectMany(ft => ft.GetAllParentTypes(false)))
                                   .GetBottomTypes();

            foreach (var injThisType in injThisTypes)
            {
                injThisType.resolvedTargetTypeFromModel = thisTypesInModel.First(tType => injThisType.resolvedTargetType.GetGenericDefinitionIfContainsGenericParameters().IsAssignableFrom_IgnoreGenericArgumentsForGenericTypes(tType));
            }

            var thisTypesToProcess = new HashSet <ThisTypeInfo>(injThisTypes.GetBottomTypes(model => model.resolvedTargetType).Distinct(INJECTABLE_MODEL_EQ_COMPARER));

            thisTypesToProcess.ExceptWith(thisTypesToProcess.Where(type => compositeModel.PublicTypes.Any(role => type.resolvedTargetType.GetGenericDefinitionIfGenericType().IsAssignableFrom_IgnoreGenericArgumentsForGenericTypes(role))).ToArray());

            // TODO check that if type binding has more than one list with indirect bindings -> throw or add error.

            var privateComposites = new Dictionary <Type, TypeBindingInformationState>();

            while (thisTypesToProcess.Any())
            {
                var processedTypes = new HashSet <ThisTypeInfo>(GDEF_EQ_COMPARER);
                foreach (var thisType in thisTypesToProcess)
                {
                    if (this.ModifyTypeBindingInfoDictionary(privateComposites, this.NewTypeBindingInformation(null, collectionsFactory, compositeModel, null, thisType.resolvedTargetTypeFromModel, thisType.resolvedTargetType, GetBottommostDeclaringType(thisType.model), privateComposites)))
                    {
                        processedTypes.Add(thisType);
                    }
                }
                thisTypesToProcess.ExceptWith(thisTypesToProcess.Where(t => processedTypes.Any(p => t.resolvedTargetType.GetGenericDefinitionIfContainsGenericParameters().Equals(p.resolvedTargetType.GetGenericDefinitionIfContainsGenericParameters()))).ToArray());
                if (processedTypes.Count == 0)
                {
                    // We are stuck
                    vResult.StructureValidationErrors.Add(ValidationErrorFactory.NewStructureError("Could not deduce generic bindings for types " + String.Join(", ", thisTypesToProcess.Select(ttp => ttp.resolvedDeclaringType)), compositeModel));
                    break;
                }
                else
                {
                    processedTypes.Clear();
                }
            }

            var fragmentTypeInfos = new Dictionary <Type, TypeBindingInformationState>();

            foreach (var fragmentType in compositeModel.GetAllFragmentTypes())
            {
                // TODO check - if any parent is public or private composite type (genericdefifgenerictype), error
                if (fragmentType.IsGenericType())
                {
                    var it = FindImplementingTypeFrom(fragmentType, compositeModel.PublicTypes);
                    if (it != null || !fragmentType.ContainsGenericParameters())
                    {
                        this.ModifyTypeBindingInfoDictionary(fragmentTypeInfos, this.NewTypeBindingInformation(vResult, collectionsFactory, compositeModel, null, fragmentType, fragmentType, fragmentType, privateComposites));
                    }
                    else
                    {
                        // Private composite fragment
                        // Process all base types + injectable models of this fragment, and all their generic arguments as DFS
                        var dependentStates = Enumerable.Repeat <Tuple <Int32, TypeBindingInformationState> >(null, fragmentType.GetGenericArguments().Length).ToList();

                        foreach (var typeToProcess in fragmentType.GetAllParentTypes(false)
                                 .Concat(
                                     compositeModel.GetAllInjectableModels()
                                     .Where(inj => fragmentType.GetClassHierarchy().Contains(inj.DeclaringType))
                                     .Select(inj => inj.TargetType)
                                     ))
                        {
                            if (dependentStates.Any(item => item == null))
                            {
                                var gArgs = typeToProcess.GetGenericArguments();
                                for (var i = 0; i < gArgs.Length; ++i)
                                {
                                    foreach (var typeOrGArg in gArgs[i].AsDepthFirstEnumerable(t => t.GetGenericArgumentsSafe()))
                                    {
                                        if (typeOrGArg.IsGenericParameter && dependentStates[typeOrGArg.GenericParameterPosition] == null)
                                        {
                                            TypeBindingInformationState other;
                                            if (!privateComposites.TryGetValue(typeToProcess.GetGenericDefinitionIfContainsGenericParameters(), out other) &&
                                                compositeModel.PublicTypes.Contains(typeToProcess)
                                                )
                                            {
                                                other            = new TypeBindingInformationState(collectionsFactory);
                                                other.NativeInfo = typeToProcess;
                                            }
                                            if (other != null)
                                            {
                                                dependentStates[typeOrGArg.GenericParameterPosition] = Tuple.Create(i, other);
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                        if (!dependentStates.Any(item => item == null))
                        {
                            var state = new TypeBindingInformationState(collectionsFactory);
                            state.NativeInfo = fragmentType;
                            var max = Math.Max(1, dependentStates.Max(dState => dState.Item2.Bindings.CQ.Count));
                            if (dependentStates.Select(dState => dState.Item2.Bindings.CQ.Count).Where(c => c > 1).Distinct().Count() > 1)
                            {
                                throw new NotImplementedException("Very complex private type binding is not yet supported.");
                            }
                            else
                            {
                                for (var i = 0; i < max; ++i)
                                {
                                    state.Bindings.Add(collectionsFactory.NewListProxy(dependentStates.Select(dState =>
                                    {
                                        AbstractGenericTypeBinding gtb;
                                        if (dState.Item2.Bindings.CQ.Any())
                                        {
                                            // Private composite binding
                                            gtb = dState.Item2.Bindings.CQ[i].CQ[dState.Item1];
                                        }
                                        else
                                        {
                                            var iState = new IndirectGenericTypeBindingState();
                                            iState.GenericDefinition = dState.Item2.NativeInfo.GetGenericDefinitionIfGenericType();
                                            iState.GenericIndex      = dState.Item1;
                                            gtb = new IndirectGenericTypeBindingImpl(iState);
                                        }
                                        return(gtb);
                                    }).ToList()));
                                }
                                this.ModifyTypeBindingInfoDictionary(fragmentTypeInfos, state);
                            }
                        }
                    }
                }
                else
                {
                    var state = new TypeBindingInformationState(collectionsFactory);
                    state.NativeInfo = fragmentType;
                    this.ModifyTypeBindingInfoDictionary(fragmentTypeInfos, state);
                }
            }

            this._fragmentTypeInfos             = collectionsFactory.NewDictionaryProxy(fragmentTypeInfos.ToDictionary(kvp => kvp.Key, kvp => (TypeBindingInformation) new TypeBindingInformationImpl(kvp.Value))).CQ;
            this._concernInvocationTypeInfos    = collectionsFactory.NewDictionaryProxy(this.CreateInvocationInfos <ConcernForAttribute>(vResult, collectionsFactory, compositeModel, privateComposites).ToDictionary(kvp => kvp.Key, kvp => (TypeBindingInformation) new TypeBindingInformationImpl(kvp.Value))).CQ;
            this._sideEffectInvocationTypeInfos = collectionsFactory.NewDictionaryProxy(this.CreateInvocationInfos <SideEffectForAttribute>(vResult, collectionsFactory, compositeModel, privateComposites).ToDictionary(kvp => kvp.Key, kvp => (TypeBindingInformation) new TypeBindingInformationImpl(kvp.Value))).CQ;
            this._privateCompositeTypeInfos     = collectionsFactory.NewDictionaryProxy(privateComposites.ToDictionary(kvp => kvp.Key, kvp => (TypeBindingInformation) new TypeBindingInformationImpl(kvp.Value))).CQ;
        }
        public PublicCompositeTypeGenerationResultImpl(
            CompositeModel cModel,
            CompositeTypeModel tModel,
            EventHandler <AssemblyLoadingArgs> loadingEvt,
            IDictionary <Assembly, Assembly> assDic,
            CompositeCodeGenerationInfo codeGenerationInfo
            )
        {
            //var orderer = new TypeLoadOrderer( cModel );

            var collectionsFactory = cModel.ApplicationModel.CollectionsFactory;
            var publicTypes        = cModel
                                     .GetAllCompositeTypes()
                                     .Concat(cModel.GetAllFragmentTypes())
                                                                                                    //.OrderBy( t => t, orderer )
                                     .Where(t => cModel.ApplicationModel.AffectedAssemblies.Contains(t.GetAssembly()))
                                     .OrderBy(t => t.Equals(cModel.MainCodeGenerationType) ? 0 : 1) // Populate main code generation type first
                                     .Select(t => GetGeneratedPublicType(t, cModel, codeGenerationInfo, loadingEvt, assDic))
                                     .Distinct()
                                     .ToArray();

            var mainTypes = publicTypes.Where(iResult => iResult.IsPublicTypeMainCompositeType());

            if (!mainTypes.Any() || mainTypes.Skip(1).Any())
            {
                throw new ArgumentException((mainTypes.Any() ? "Too many" : "Too little") + " generated main types (" + String.Join(", ", mainTypes) + "), exactly one allowed.");
            }
            var mainType = mainTypes.First();

            this._compositeFactory = (CompositeFactory)mainType.GetAssembly().GetType(mainType.Name + codeGenerationInfo.CompositeFactorySuffix, true)
#if WINDOWS_PHONE_APP
                                     .GetAllInstanceConstructors().First()
#else
                                     .GetConstructors()[0]
#endif
                                     .Invoke(null);

            var fragmentTypeGenerationResults = tModel.FragmentTypeInfos.Keys
                                                //.OrderBy( t => t, orderer )
                                                .Select(t => Tuple.Create(t, GetParticipantType(t, cModel, codeGenerationInfo, loadingEvt, assDic, codeGenerationInfo.FragmentPrefix, true)))
                                                .Where(t => t.Item2 != null)
                                                .Select(t => (FragmentTypeGenerationResult) new FragmentTypeGenerationResultImpl(t.Item1, t.Item2))
                                                .ToArray();
            var concernInvocationGenerationResults = tModel.ConcernInvocationTypeInfos.Keys
                                                     //.OrderBy( t => t, orderer )
                                                     .Select(t => Tuple.Create(t, GetParticipantType(t, cModel, codeGenerationInfo, loadingEvt, assDic, codeGenerationInfo.ConcernInvocationPrefix)))
                                                     .Where(t => t.Item2 != null)
                                                     .Select(t => (TypeGenerationResult) new TypeGenerationResultImpl(t.Item2, t.Item1))
                                                     .ToArray();
            var sideEffectInvocationGenerationResults = tModel.SideEffectInvocationTypeInfos.Keys
                                                        //.OrderBy( t => t, orderer )
                                                        .Select(t => Tuple.Create(t, GetParticipantType(t, cModel, codeGenerationInfo, loadingEvt, assDic, codeGenerationInfo.SideEffectInvocationPrefix)))
                                                        .Where(t => t.Item2 != null)
                                                        .Select(t => (TypeGenerationResult) new TypeGenerationResultImpl(t.Item2, t.Item1))
                                                        .ToArray();
            var privateCompositeGenerationresults = tModel.PrivateCompositeTypeInfos.Keys
                                                    //.OrderBy( t => t, orderer )
                                                    .Select(t => Tuple.Create(t, GetParticipantType(t, cModel, codeGenerationInfo, loadingEvt, assDic, codeGenerationInfo.PrivateCompositePrefix)))
                                                    .Where(t => t.Item2 != null)
                                                    .Select(t => (TypeGenerationResult) new TypeGenerationResultImpl(t.Item2, t.Item1))
                                                    .ToArray();

            var pGArgs = collectionsFactory.NewDictionaryProxy(
                tModel.PublicCompositeGenericArguments
                .Select((gArg, idx) => Tuple.Create(gArg, idx))
                .GroupBy(tuple => tuple.Item1.DeclaringType)
                .ToDictionary(grouping => grouping.Key, grouping => collectionsFactory.NewListProxy(grouping.Select(tuple => tuple.Item2).ToList()).CQ));

            this._generatedPublicMainType = mainType;
            this._maxParamCountForCtors   = mainType
#if WINDOWS_PHONE_APP
                                            .GetAllInstanceConstructors().First()
#else
                                            .GetConstructors(BindingFlags.Instance | BindingFlags.Public)[0]
#endif
                                            .GetParameters().Length;

            this._generatedPublicTypes = collectionsFactory.NewListProxy(publicTypes.Select(
                                                                             pt => (GeneratedTypeInfo) new GeneratedTypeInfoImpl(pt))
                                                                         .ToList()).CQ;
            this._publicCompositeGenericArguments       = pGArgs.CQ;
            this._privateCompositeGenerationResults     = collectionsFactory.NewListProxyFromParams(privateCompositeGenerationresults).CQ;
            this._fragmentGenerationResults             = collectionsFactory.NewListProxyFromParams(fragmentTypeGenerationResults).CQ;
            this._concernInvocationGenerationResults    = collectionsFactory.NewListProxyFromParams(concernInvocationGenerationResults).CQ;
            this._sideEffectInvocationGenerationResults = collectionsFactory.NewListProxyFromParams(sideEffectInvocationGenerationResults).CQ;

            // Remember to remove Qi4CS assembly if present
            assDic.Remove(ReflectionHelper.QI4CS_ASSEMBLY);
        }