/// <summary>
        /// Adds a new <typeparamref name="TIntermediateIndexer"/> with
        /// the <paramref name="nameAndReturn"/> and
        /// <paramref name="parameters"/> provided.
        /// </summary>
        /// <param name="nameAndReturn">The <see cref="TypedName"/>
        /// which specifies the indexer name and return type.</param>
        /// <param name="parameters">The <see cref="TypedNameSeries"/>
        /// which denotes the types and names of the parameters of the
        /// indexer to add.</param>
        /// <param name="canGet">Whether the property can be read.</param>
        /// <param name="canSet">Whether the property can be written.</param>
        /// <returns>A <typeparamref name="TIntermediateIndexer"/> which
        /// represents the indexer added.</returns>
        /// <exception cref="System.ArgumentException">thrown another
        /// member within the <see cref="IIntermediateIndexerMemberDictionary"/>
        /// contains the same signature.</exception>
        public TIntermediateIndexer Add(TypedName nameAndReturn, TypedNameSeries parameters, bool canGet = true, bool canSet = true)
        {
            var result = this.GetNew(nameAndReturn, parameters, canGet, canSet);

            base._Add(result.UniqueIdentifier, result);
            return(result);
        }
        /// <summary>
        /// Adds a <typeparamref name="TIntermediateEvent"/> with the <paramref name="name"/> and
        /// <paramref name="eventSignature"/> provided.
        /// </summary>
        /// <param name="name">The <see cref="String"/> name of the event.</param>
        /// <param name="eventSignature">The <see cref="TypedNameSeries"/> that designates
        /// the names and types of the parameters of a delegate signature that will be
        /// generated upon translation.</param>
        /// <returns>A <typeparamref name="TIntermediateEvent"/> instance.</returns>
        public TIntermediateEvent Add(string name, TypedNameSeries eventSignature)
        {
            var result = this.GetEvent(name, eventSignature);

            this.AddDeclaration(result);
            return(result);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Adds a new <typeparamref name="TIntermediateSignature"/> with the
        /// <paramref name="name"/>, <paramref name="parameters"/>, and
        /// <paramref name="typeParameters"/>provided.
        /// </summary>
        /// <param name="name">The <see cref="String"/> representing the name the method is referred to by.</param>
        /// <param name="parameters">The <see cref="TypedNameSeries"/> which designates
        /// the parameter names and types of the new <typeparamref name="TIntermediateSignature"/>.</param>
        /// <param name="typeParameters">An array of <see cref="GenericParameterData"/> which
        /// defines the type-parameters and their individual type and functional constraints.</param>
        /// <returns>A new <typeparamref name="TIntermediateSignature"/>
        /// which has a <see cref="System.Void"/> return-type.</returns>
        /// <exception cref="System.ArgumentNullException">thrown when <paramref name="name"/> is null, or <paramref name="typeParameters"/>
        /// is null.</exception>
        /// <exception cref="System.ArgumentException">thrown when <paramref name="name"/> is <see cref="String.Empty"/>
        /// or an element of <paramref name="parameters"/>, or <paramref name="typeParameters"/> contains an invalid type-reference (<see cref="System.Void"/>).</exception>
        public TIntermediateSignature Add(string name, TypedNameSeries parameters, params GenericParameterData[] typeParameters)
        {
            var method = this.GetNewMethodWithParametersAndTypeParameters(name, parameters, typeParameters);

            method.ReturnType = this.identityManager.ObtainTypeReference(RuntimeCoreType.VoidType);
            this.AddDeclaration(method);
            return(method);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Inserts a series of new <see cref="ITypedLocalMember"/> instances
        /// with the <see cref="TypedNameSeries"/>, relative to the active
        /// scope, for the <see cref="ITypedLocalMember"/> elements to add.
        /// </summary>
        /// <param name="namesAndTypes">The <see cref="TypedNameSeries"/>
        /// which denotes each element's name and type within the active scope.</param>
        /// <returns>a series of new <see cref="ITypedLocalMember"/> instances
        /// with the <see cref="TypedNameSeries"/> provided.</returns>
        public ITypedLocalMember[] AddRange(TypedNameSeries namesAndTypes)
        {
            var seriesElements = namesAndTypes.ToArray();
            Stack <ILocalMemberDictionary> memberScopes = GetFullScope();

            IGeneralMemberUniqueIdentifier[] ids = new IGeneralMemberUniqueIdentifier[namesAndTypes.Count];
            for (int i = 0; i < seriesElements.Length; i++)
            {
                ids[i] = TypeSystemIdentifiers.GetMemberIdentifier(seriesElements[i].Name);
            }
            for (int i = 0; i < seriesElements.Length; i++)
            {
                var iElementIdentifier = ids[i];

                /* *
                 * First check for name collisions within the series itself.
                 * */
                for (int j = i + 1; j < seriesElements.Length; j++)
                {
                    if (iElementIdentifier.Equals(ids[j]))
                    {
                        throw new ArgumentException("Duplicate name detected");
                    }
                }

                /* *
                 * Next, check for collisions within the scope.
                 * */
                foreach (var scope in memberScopes)
                {
                    if (scope.ContainsKey(iElementIdentifier))
                    {
                        throw new ArgumentException("Duplicate name detected");
                    }
                }
            }
            var parentMember = this.GetTopParent() as IIntermediateMember;

            ITypedLocalMember[] locals = new ITypedLocalMember[seriesElements.Length];
            for (int i = 0; i < seriesElements.Length; i++)
            //Parallel.For(0, seriesElements.Length, i =>
            {
                var current   = seriesElements[i];
                var localType = current.GetTypeRef();
                if (localType.ContainsSymbols())
                {
                    localType = localType.SimpleSymbolDisambiguation(parentMember);
                }
                locals[i] = new TypedLocalMember(current.Name, this.Parent, localType);
            }//**/);
            this._AddRange(from local in locals
                           select new KeyValuePair <IGeneralMemberUniqueIdentifier, ILocalMember>(local.UniqueIdentifier, local));
            return(locals);
        }
        /// <summary>
        /// Adds a <typeparamref name="TIntermediateCtor"/>
        /// with the <paramref name="parameters"/> provided.
        /// </summary>
        /// <param name="parameters">The <see cref="TypedNameSeries"/>
        /// which identifies all of the parameters by name and type.</param>
        /// <returns>A <typeparamref name="TIntermediateCtor"/> instance with
        /// the <paramref name="parameters"/> specified.</returns>
        /// <exception cref="System.ArgumentException">The provided set of <paramref name="parameters"/>
        /// exists already, or a name of one of the parameters is null.</exception>
        public new TIntermediateCtor Add(TypedNameSeries parameters)
        {
            TIntermediateCtor item = this.GetConstructor();

            item.Parameters.AddRange(parameters.ToArray());
            if (this.ContainsKey(item.UniqueIdentifier))
            {
                throw new ArgumentException("parameters");
            }
            this.AddDeclaration(item);
            return(item);
        }
Ejemplo n.º 6
0
            protected override TIntermediateIndexer GetNew(TypedName nameAndReturn, TypedNameSeries parameters, bool canGet = true, bool canSet = true)
            {
                var result = (TIntermediateIndexer)(object)this.Parent.GetNewIndexer(nameAndReturn);

                if (parameters.Count > 0)
                {
                    result.Parameters.AddRange(parameters.ToArray());
                }
                result.CanRead  = canGet;
                result.CanWrite = canSet;
                return(result);
            }
Ejemplo n.º 7
0
        /// <summary>
        /// Adds a new <typeparamref name="TIntermediateSignature"/>
        /// instane with the <paramref name="parameters"/>, <paramref name="typeParameters"/>, <paramref name="nameAndReturn"/>
        /// provided.
        /// </summary>
        /// <param name="nameAndReturn">A <see cref="TypedName"/> which designates the name of the method and its
        /// return-type.</param>
        /// <param name="parameters">The <see cref="TypedNameSeries"/> which designates
        /// the parameter names and types of the new <typeparamref name="TIntermediateSignature"/>.</param>
        /// <param name="typeParameters">An array of <see cref="GenericParameterData"/> which
        /// defines the type-parameters and their individual type and functional constraints.</param>
        /// <returns>A new <typeparamref name="TIntermediateSignature"/>.</returns>
        /// <exception cref="System.ArgumentException">thrown when the name portion of <paramref name="nameAndReturn"/> is <see cref="String.Empty"/>
        /// or an element of <paramref name="parameters"/>, or <paramref name="typeParameters"/> contains an invalid type-reference (<see cref="System.Void"/>).</exception>
        /// <exception cref="System.ArgumentNullException">thrown when <paramref name="typeParameters"/>
        /// is null.</exception>
        public TIntermediateSignature Add(TypedName nameAndReturn, TypedNameSeries parameters, params GenericParameterData[] typeParameters)
        {
            TIntermediateSignature method = this.Add(nameAndReturn.Name, parameters, typeParameters);
            var returnType = nameAndReturn.GetTypeRef();

            if (returnType.ContainsSymbols())
            {
                method.ReturnType = returnType.SimpleSymbolDisambiguation(method);
            }
            else
            {
                method.ReturnType = returnType;
            }
            return(method);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Adds a new <typeparamref name="TIntermediateSignature"/>
        /// instance with the <paramref name="parameters"/>, <paramref name="nameAndReturn"/> provided.
        /// </summary>
        /// <param name="nameAndReturn">A <see cref="TypedName"/> which designates the name of the method and its
        /// return-type.</param>
        /// <param name="parameters">The <see cref="TypedNameSeries"/> which designates
        /// the parameter names and types of the new <typeparamref name="TIntermediateSignature"/>.</param>
        /// <returns>A new <typeparamref name="TIntermediateSignature"/>.</returns>
        /// <exception cref="System.ArgumentException">thrown when the name portion of <paramref name="nameAndReturn"/> is <see cref="String.Empty"/>
        /// or an element of <paramref name="parameters"/> contains an invalid type-reference (<see cref="System.Void"/>).</exception>
        public TIntermediateSignature Add(TypedName nameAndReturn, TypedNameSeries parameters)
        {
            var method = this.GetNewMethodWithParameters(nameAndReturn.Name, parameters);
            //TIntermediateSignature method = this.Add(nameAndReturn.Name, parameters);
            var returnType = nameAndReturn.GetTypeRef();

            if (returnType.ContainsSymbols())
            {
                method.ReturnType = returnType.SimpleSymbolDisambiguation(method);
            }
            else
            {
                method.ReturnType = returnType;
            }
            this.AddDeclaration(method);
            return(method);
        }
 IIntermediateConstructorMember IIntermediateConstructorMemberDictionary.Add(TypedNameSeries parameters)
 {
     return(this.Add(parameters));
 }
 /// <summary>
 /// Adds a new <typeparamref name="TIntermediateIndexer"/> with
 /// the <paramref name="returnType"/> and
 /// <paramref name="parameters"/> provided.
 /// </summary>
 /// <param name="returnType">The <see cref="IType"/> which
 /// results from the indexer operation.</param>
 /// <param name="parameters">The <see cref="TypedNameSeries"/>
 /// which denotes the types and names of the parameters of the
 /// indexer to add.</param>
 /// <param name="canGet">Whether the property can be read.</param>
 /// <param name="canSet">Whether the property can be written.</param>
 /// <returns>A <typeparamref name="TIntermediateIndexer"/> which
 /// represents the indexer added.</returns>
 /// <exception cref="System.ArgumentException">thrown another
 /// member within the <see cref="IIntermediateIndexerMemberDictionary"/>
 /// contains the same signature.</exception>
 public TIntermediateIndexer Add(IType returnType, TypedNameSeries parameters, bool canGet = true, bool canSet = true)
 {
     return(this.Add(new TypedName(null, returnType), parameters, canGet, canSet));
 }
 IIntermediateIndexerMember IIntermediateIndexerMemberDictionary.Add(TypedName nameAndReturn, TypedNameSeries parameters, bool canGet, bool canSet)
 {
     return(this.Add(nameAndReturn, parameters, canGet, canSet));
 }
 IIntermediateIndexerMember IIntermediateIndexerMemberDictionary.Add(IType returnType, TypedNameSeries parameters, bool canGet, bool canSet)
 {
     return(this.Add(returnType, parameters, canGet, canSet));
 }
 protected abstract TIntermediateIndexer GetNew(TypedName nameAndReturn, TypedNameSeries parameters, bool canGet, bool canSet);
Ejemplo n.º 14
0
        /* *
         * Lovely method name, huh?
         * */
        private TIntermediateSignature GetNewMethodWithParametersAndTypeParameters(string name, TypedNameSeries parameters, GenericParameterData[] typeParameters)
        {
            var method = this.GetNewMethod(name);

            if (typeParameters.Length > 0)
            {
                method.TypeParameters.AddRange(typeParameters);
            }
            if (parameters.Count > 0)
            {
                var internalParameters = method.Parameters as IntermediateParameterMemberDictionary <TSignature, TIntermediateSignature, TSignatureParameter, TIntermediateSignatureParameter>;
                if (parameters != null)
                {
                    /* Method hasn't been added yet, processing the event requests would be an effort in futility. */
                    internalParameters.SkipEvents = true;
                    internalParameters.AddRange(parameters.ToArray());
                    internalParameters.SkipEvents = false;
                }
                else
                {
                    method.Parameters.AddRange(parameters.ToArray());
                }
            }
            return(method);
        }
Ejemplo n.º 15
0
        public void BuildVisitor()
        {
            var nameWithoutTail      = string.Join("", this.NameParts.Take(this.NameParts.Length - 1)).LowerFirstCharacter();
            var namePartsWithoutTail = this.NameParts.Take(this.NameParts.Length - 1).Select(k => k.ToLower()).ToArray();
            var lastItem             = namePartsWithoutTail.Last();

            if (lastItem == "code")
#pragma warning disable 642
            {
                ;//Do nothing, keep it the same.
            }
#pragma warning restore 642
            else if (lastItem.EndsWith("y"))
            {
                namePartsWithoutTail[namePartsWithoutTail.Length - 1] = lastItem.Substring(0, lastItem.Length - 1) + "ies";
            }
            else if (!lastItem.EndsWith("s"))
            {
                namePartsWithoutTail[namePartsWithoutTail.Length - 1] = lastItem + "s";
            }

            IGenericTypeParameter <IGeneralGenericTypeUniqueIdentifier, IInterfaceType> tResult;
            IGenericTypeParameter <IGeneralGenericTypeUniqueIdentifier, IInterfaceType> tContext;
            this.VisitorInterface.TypeParameters.TryGetValue(TypeSystemIdentifiers.GetGenericParameterIdentifier("TResult"), out tResult);
            this.VisitorInterface.TypeParameters.TryGetValue(TypeSystemIdentifiers.GetGenericParameterIdentifier("TContext"), out tContext);
            this.VisitorInterface.SummaryText = string.Format("Represents a basic visitor for {2}{0}{1}.", tResult != null ? " which yields a result of @t:TResult;" : string.Empty, tContext != null ? string.Format("{0} has a @t:TContext; relevant to the visit", tResult != null ? " and also" : " which") : string.Empty, string.Join(" ", namePartsWithoutTail));
            if (tResult != null)
            {
                ((IIntermediateGenericTypeParameter <IGeneralGenericTypeUniqueIdentifier, IInterfaceType, IIntermediateInterfaceType>)(tResult)).SummaryText = string.Format("Denotes the type of result the members of the @s:{0}; should yield.", this.VisitorInterface.MakeGenericClosure(this.VisitorInterface.GenericParameters).BuildTypeName(true, typeParameterDisplayMode: TypeParameterDisplayMode.CommentStandard));
            }
            if (tContext != null)
            {
                ((IIntermediateGenericTypeParameter <IGeneralGenericTypeUniqueIdentifier, IInterfaceType, IIntermediateInterfaceType>)(tContext)).SummaryText = string.Format("Denotes the type of context the members of the @s:{0}; should receive along with the types that accept the visitor.", this.VisitorInterface.MakeGenericClosure(this.VisitorInterface.GenericParameters).BuildTypeName(true, typeParameterDisplayMode: TypeParameterDisplayMode.CommentStandard));
            }
            IType resultType   = tResult ?? this._assembly.IdentityManager.ObtainTypeReference(RuntimeCoreType.VoidType);
            var   methodLookup = new Dictionary <IType, IIntermediateInterfaceMethodMember>();
            /* Skipped types are for the notion of inheritance-based visitors which are derived from multiple other visitors, we skip the types associated to those inherited visitors to avoid repeating their signatures. */
            foreach (var type in this.RelevantTypes.Except(this.SkippedTypes).OrderBy(k => k.FullName))
            {
                var gpData = new List <GenericParameterData>();
                if (type.IsGenericConstruct)
                {
                    var genericType = (IGenericType)type;
                    if (genericType.IsGenericDefinition)
                    {
                        foreach (IGenericTypeParameter typeParam in genericType.TypeParameters.Values)
                        {
                            gpData.Add(new GenericParameterData(typeParam.Name, typeParam.Constraints.Select(k => k.TurnTypeParametersIntoSymbols()) /*.Select(constraint=>constraint.IsGenericConstruct ? ((IGenericType)(constraint)).MakeGenericClosure(((IGenericType)(constraint)).GenericParameters) : constraint.IsGenericTypeParameter ? constraint.Name.GetSymbolType() : constraint)*/.ToArray())
                            {
                                SpecialConstraint = typeParam.SpecialConstraint
                            });
                        }
                    }
                }
                TypedNameSeries paramData = new TypedNameSeries();
                paramData.Add(type.WithName(nameWithoutTail));

                if (tContext != null)
                {
                    paramData.Add(tContext.WithName("context"));
                }
                var method = this.VisitorInterface.Methods.Add(resultType.WithName("Visit"), paramData, gpData.ToArray());
                methodLookup.Add(type, method);
                if (tContext != null)
                {
                    var contextParam = method.Parameters["context"];
                    contextParam.SummaryText = "The @t:TContext; relevant to the visit.";
                }
                var inputParam = method.Parameters[nameWithoutTail];
                if (tResult != null)
                {
                    method.SummaryText = string.Format("Returns a @t:{1}; after it visits the @p:{0}; provided{2}.", inputParam.Name, tResult.Name, tContext == null ? string.Empty : " with the given @p:context;");
                    method.ReturnsText = @"Returns the value of @t:TResult; relative to the implementation of the visitor.";
                }
                else
                {
                    method.SummaryText = string.Format("Visits the @p:{0}; provided{1}.", inputParam.Name, tContext == null ? string.Empty : " with the given @p:context;");
                }
                var    commentType = ((IGenericType)(type));
                string ofText      = string.Empty;
                if (commentType.IsGenericConstruct && !commentType.IsGenericDefinition && this._detail.TypeParameterVariations != null && this._detail.TypeParameterVariations.Length > 0)
                {
                    ofText      = string.Format(" of @s:{0};", commentType.GenericParameters.First().BuildTypeName());
                    commentType = (IGenericType)commentType.ElementType;
                }
                if (commentType.IsGenericConstruct && commentType.IsGenericDefinition)
                {
                    commentType = commentType.MakeGenericClosure(commentType.GenericParameters);
                }
                inputParam.SummaryText = string.Format("The @s:{0};{1} relevant to the visit.", commentType.BuildTypeName(true, typeParameterDisplayMode: TypeParameterDisplayMode.CommentStandard), ofText);
            }
            this.TypeToMethodLookup = methodLookup;
        }
 /// <summary>
 /// Obtains a <typeparamref name="TIntermediateEvent"/> to fulfill an <see cref="Add(String, TypedNameSeries)"/>
 /// request.
 /// </summary>
 /// <param name="name">The <see cref="String"/> name of the event.</param>
 /// <param name="eventSignature">The <see cref="TypedNameSeries"/> that designates
 /// the names and types of the parameters of a delegate signature that will be
 /// generated upon translation.</param>
 /// <returns>A <typeparamref name="TIntermediateEvent"/> instance.</returns>
 protected abstract TIntermediateEvent GetEvent(string name, TypedNameSeries eventSignature);
 private TypedNameSeries TransposeTypedNames(TypedNameSeries series, TIntermediateGenericParameter target)
 {
     return(new TypedNameSeries((from s in series
                                 select TransposeTypedName(s, target)).ToArray()));
 }
Ejemplo n.º 18
0
 /// <summary>
 /// Converts the <see cref="TypedNameSeries"/> to a <see cref="SignatureData"/>
 /// instance.
 /// </summary>
 /// <param name="series">The <see cref="TypedNameSeries"/> to convert.</param>
 /// <returns>A new <see cref="SignatureData"/> instance equivalent to
 /// <paramref name="series"/>.</returns>
 public static SignatureData FromTypedNameSeries(TypedNameSeries series)
 {
     return(series);
 }
Ejemplo n.º 19
0
 private TIntermediateSignature GetNewMethodWithParameters(string name, TypedNameSeries parameters)
 {
     return(this.GetNewMethodWithParametersAndTypeParameters(name, parameters, GenericParameterData.EmptySet));
 }
Ejemplo n.º 20
0
 IIntermediateMethodSignatureMember IIntermediateMethodSignatureMemberDictionary.Add(TypedName nameAndReturn, TypedNameSeries parameters, params GenericParameterData[] typeParameters)
 {
     return(this.Add(nameAndReturn, parameters, typeParameters));
 }
Ejemplo n.º 21
0
 IIntermediateMethodSignatureMember IIntermediateMethodSignatureMemberDictionary.Add(string name, TypedNameSeries parameters)
 {
     return(this.Add(name, parameters));
 }
Ejemplo n.º 22
0
        protected override IntermediateClassType <TInstanceIntermediateType> .EventMember GetNewEvent(string name, TypedNameSeries eventSignature)
        {
            var result = new EventMember(((TInstanceIntermediateType)(object)this))
            {
                SignatureSource = EventSignatureSource.Declared,
                Name            = name
            };

            foreach (var param in eventSignature)
            {
                result.Parameters.Add(param.Name, param.GetTypeRef(), param.Direction);
            }
            return(result);
        }
        public void BuildImplementation(IAssembly target)
        {
            if (IEnumerableOfT == null)
            {
                IEnumerableOfT = typeof(IEnumerable <>).GetTypeReference <IInterfaceType>(this._assembly.IdentityManager);
            }
            if (IControlledDictionaryOfTKeyTValue == null)
            {
                IControlledDictionaryOfTKeyTValue = typeof(IControlledDictionary <,>).GetTypeReference <IInterfaceType>(this._assembly.IdentityManager);
            }
            if (IntermediateDeclDict == null)
            {
                IntermediateDeclDict = typeof(IIntermediateDeclarationDictionary <, ,>).GetTypeReference <IInterfaceType>(this._assembly.IdentityManager);
            }
            IType ignoreAttr    = typeof(VisitorImplementationIgnorePropertyAttribute).GetTypeReference(this._assembly.IdentityManager);
            IType ignoreSetAttr = typeof(VisitorImplementationIgnoreLocalSetAttribute).GetTypeReference(this._assembly.IdentityManager);
            var   requireAttr   = typeof(VisitorPropertyRequirementAttribute).GetTypeReference(this._assembly.IdentityManager);
            bool  visitorsDoNotNeedConstraints = !string.IsNullOrEmpty(this.Detail.VisitRefactorName);
            var   builderInterfaces            = this._builders.SelectMany(k => k.RelevantTypes).Distinct().OfType <IInterfaceType>().ToArray();
            //var allEnumerables = builderInterfaces.Select(k => CreateEnumerableVariant(k)).ToArray();
            var distinctInterfaces =
                builderInterfaces.Concat(builderInterfaces.SelectMany(k => k.ImplementedInterfaces)).Distinct().ToArray();
            var interfaceProperties =
                (from iFace in distinctInterfaces.OfType <IInterfaceType>()
                 from prop in iFace.Properties.Values /*.Where(k => IsPropertyRelevant(ignoreAttr, builderInterfaces, k))*/.DefaultIfEmpty()
                 group prop by iFace).ToDictionary(k => k.Key, v => (v.First() == null ? (IEnumerable <IInterfacePropertyMember>) new IInterfacePropertyMember[0] : v).ToList());
            var interfacesWithAccept       = distinctInterfaces.OfType <IInterfaceType>().Where(k => k.Methods.Values.Any(j => j.Name == "Accept")).ToArray();
            var actionDetail               = typeof(VisitorImplementationActionDetailAttribute).GetTypeReference <IClassType>(this._assembly.IdentityManager);
            var relevantActionDetail       = target.Metadata.Where(k => k.Type == actionDetail && k.Parameters.GetIndexedParameter <string>(0).Item2 == this.Detail.TargetContext);
            var relevantActionDetailLookup = relevantActionDetail.ToDictionary(k => k.Parameters.GetIndexedParameter <IType>(1).Item2, v => VisitorImplementationActionDetail.DeriveFromMetadata(v));
            var relevantActionTypes        = relevantActionDetailLookup.Keys.ToArray();

            //foreach (var key in relevantActionTypes)
            //    foreach (var @interface in key.ImplementedInterfaces)
            //        if (!relevantActionDetailLookup.ContainsKey(@interface))
            //            relevantActionDetailLookup.Add(@interface, relevantActionDetailLookup[key]);
            builderInterfaces = builderInterfaces.Concat(interfacesWithAccept).Distinct().ToArray();
            var inheritanceDetail = (from iFace in builderInterfaces
                                     let baseTypes = iFace.ImplementedInterfaces.OfType <IInterfaceType>()
                                                     from iFace2 in new[] { iFace }.Concat(baseTypes).Distinct()
                                     group iFace2 by iFace).ToDictionary(k => k.Key, v => v.ToArray());

            bool isVoidReturn = !this.Detail.YieldingVisitor;

            if (visitorsDoNotNeedConstraints)
            {
                this.SecondaryResult = this.VisitorResult.Parts.Add();
                var relativeRoot = new string[] { this.VisitorResult.NamespaceName, this._assembly.DefaultNamespace.FullName }.GetRelativeRoot(".");
                if (!string.IsNullOrEmpty(relativeRoot))
                {
                    relativeRoot = this.VisitorResult.NamespaceName.Substring(relativeRoot.Length + 1);
                    relativeRoot = relativeRoot.Replace(".", @"\") + @"\";
                }

                this.SecondaryResult.Assembly.FileName = string.Format("{2}{0} ({1} Signatures)", this.Detail.TargetContext, this.Detail.VisitRefactorName, relativeRoot);
                this.VisitorResult.Assembly.FileName   = string.Format("{1}{0} (Visitor Signatures)", this.Detail.TargetContext, relativeRoot);
            }
            foreach (var builder in this._builders)
            {
                if (this.Detail.InheritedVisitors.Contains(builder.Detail.TargetContext))
                {
                    this.VisitorResult.ImplementedInterfaces.ImplementInterfaceQuick(builder.VisitorInterface);
                }
                foreach (var method in builder.VisitorInterface.Methods.Values)
                {
                    var gpData = new GenericParameterData[method.GenericParameters.Count];
                    if (method.TypeParameters.Count > 0)
                    {
                        for (int i = 0; i < method.TypeParameters.Count; i++)
                        {
                            var gParam = method.TypeParameters.Values[i];
                            gpData[i] = new GenericParameterData(gParam.Name);
                            if (!visitorsDoNotNeedConstraints)
                            {
                                gpData[i].Constraints.AddRange(gParam.Constraints.Select(k => k.TurnTypeParametersIntoSymbols()));
                                gpData[i].SpecialConstraint = gParam.SpecialConstraint;
                            }
                        }
                    }
                    var parameterData = new TypedNameSeries(method.Parameters.Values.Select(k => k.ParameterType.WithName(k.Name)));
                    var newMethod     = this.VisitorResult.Methods.Add(method.ReturnType.WithName(method.Name), parameterData, gpData);
                    if (visitorsDoNotNeedConstraints)
                    {
                        newMethod.Implementations.Add(builder.VisitorInterface);
                        foreach (var gpDetail in from gpDatum in gpData
                                 join genericParameter in method.TypeParameters.Values on gpDatum.Name equals genericParameter.Name
                                 select new { GenericParameterDatum = gpDatum, GenericParameter = genericParameter })
                        {
                            gpDetail.GenericParameterDatum.Constraints.AddRange(gpDetail.GenericParameter.Constraints.Select(k => k.TurnTypeParametersIntoSymbols()));
                            gpDetail.GenericParameterDatum.SpecialConstraint = gpDetail.GenericParameter.SpecialConstraint;
                        }
                        var secondNewMethod = this.SecondaryResult.Methods.Add(method.ReturnType.WithName(this.Detail.VisitRefactorName), parameterData, gpData);
                        secondNewMethod.AccessLevel = AccessLevelModifiers.Public;
                        if (this.Detail.VisitRefactorAbstract)
                        {
                            secondNewMethod.IsAbstract = true;
                        }
                        var paramRefs  = parameterData.Select(k => newMethod.Parameters[k.Name].GetReference()).ToArray();
                        var invocation = newMethod.IsGenericConstruct
                                         ? secondNewMethod.GetReference(null, newMethod.GenericParameters).Invoke(paramRefs)
                                         : secondNewMethod.GetReference(null).Invoke(paramRefs);
                        var firstParam     = newMethod.Parameters.Values[0];
                        var firstParamType = firstParam.ParameterType;
                        if (firstParamType is IInterfaceType)
                        {
                            foreach (var prop in EnumerateInterfaceProperties((IInterfaceType)firstParamType, ignoreAttr, inheritanceDetail, interfaceProperties))
                            {
                                var propertyRelevanceInfo        = IsPropertyRelevant(prop.Item1, builderInterfaces, ignoreAttr, relevantActionTypes);
                                var requirement                  = prop.Item1.Metadata[requireAttr];
                                IBlockStatementParent codeTarget = secondNewMethod;
                                if (propertyRelevanceInfo.Item2 != VisitorImplementationTypeRelevance.NotRelevant)
                                {
                                    if (requirement != null)
                                    {
                                        codeTarget = codeTarget.If(firstParam.GetReference().GetProperty(requirement.Parameters.GetIndexedParameter <string>(0).Item2));
                                    }
                                    else if (prop.Item1.PropertyType.Type == TypeKind.Interface || prop.Item1.PropertyType.Type == TypeKind.Class)
                                    {
                                        codeTarget = codeTarget.If(firstParam.GetReference().GetProperty(prop.Item1.Name).InequalTo(IntermediateGateway.NullValue));
                                    }
                                }
                                switch (propertyRelevanceInfo.Item2)
                                {
                                case VisitorImplementationTypeRelevance.AsItem:
                                    codeTarget.Call(firstParam.GetReference().GetProperty(prop.Item1.Name).GetMethod("Accept").Invoke(new IExpression[] { this.VisitorResult.GetThis() }.Concat(newMethod.Parameters.Values.Skip(1).Select(k => k.GetReference())).ToArray()));
                                    break;

                                case VisitorImplementationTypeRelevance.AsActionableItemSet:
                                    ProcessActionableSet(relevantActionDetailLookup, firstParam, prop, propertyRelevanceInfo, codeTarget, 0, null);
                                    break;

                                case VisitorImplementationTypeRelevance.AsActionableValueSet:
                                    ProcessActionableSet(relevantActionDetailLookup, firstParam, prop, propertyRelevanceInfo, codeTarget, 1, "Values");
                                    break;

                                case VisitorImplementationTypeRelevance.AsActionableDeclValueSet:
                                    ProcessActionableSet(relevantActionDetailLookup, firstParam, prop, propertyRelevanceInfo, codeTarget, 2, "Values");
                                    break;

                                case VisitorImplementationTypeRelevance.AsActionableItem:
                                    IType ratType = propertyRelevanceInfo.Item1;
                                    if (ratType.IsGenericTypeParameter)
                                    {
                                        var gpRat      = (IGenericParameter)(ratType);
                                        var interfaces = gpRat.Constraints.Concat(gpRat.Constraints.SelectMany(r => r.ImplementedInterfaces)).Distinct().ToArray();
                                        ratType = interfaces.FirstOrDefault(k => relevantActionDetailLookup.ContainsKey(k));
                                    }
                                    else if (!relevantActionDetailLookup.ContainsKey(ratType))
                                    {
                                        var interfaces = ratType.ImplementedInterfaces;
                                        ratType = interfaces.FirstOrDefault(k => relevantActionDetailLookup.ContainsKey(k));
                                    }
                                    var currentActionDetail = relevantActionDetailLookup[ratType];
                                    codeTarget.Call(
                                        this.VisitorResult
                                        .GetThis()
                                        .GetMethod(currentActionDetail.TargetAction)
                                        .Invoke(
                                            firstParam
                                            .GetReference()
                                            .GetProperty(prop.Item1.Name)));
                                    break;
                                //case VisitorImplementationTypeRelevance.AsActionableItemSet:
                                //    IType enumerableRatType = propertyRelevanceInfo.Item1;
                                //    var genericParam = ((IGenericType)(enumerableRatType)).GenericParameters.FirstOrDefault();
                                //    if (genericParam != null)
                                //    {
                                //        if (genericParam.IsGenericTypeParameter)
                                //        {
                                //            var gpRat = (IGenericParameter)(genericParam);
                                //            var interfaces = gpRat.Constraints.Concat(gpRat.Constraints.SelectMany(r => r.ImplementedInterfaces)).Distinct().ToArray();
                                //            genericParam = interfaces.FirstOrDefault(k => relevantActionDetailLookup.ContainsKey(k));
                                //        }
                                //        else if (!relevantActionDetailLookup.ContainsKey(genericParam))
                                //        {
                                //            var interfaces = genericParam.ImplementedInterfaces;
                                //            genericParam = interfaces.FirstOrDefault(k => relevantActionDetailLookup.ContainsKey(k));
                                //        }
                                //        var currentActionSetDetail = relevantActionDetailLookup[genericParam];
                                //        codeTarget.Call(this.VisitorResult.GetThis().GetMethod(currentActionSetDetail.TargetPluralAction).Invoke(firstParam.GetReference().GetProperty(prop.Item1.Name)));
                                //    }
                                //    break;

                                case VisitorImplementationTypeRelevance.AsValueSet:
                                case VisitorImplementationTypeRelevance.AsDeclValueSet:
                                    codeTarget.Call(this.VisitorResult.GetThis().GetMethod(this.Detail.VisitRefactorName ?? "Visit").Invoke(firstParam.GetReference().GetProperty(prop.Item1.Name).GetProperty("Values")));
                                    break;

                                case VisitorImplementationTypeRelevance.AsItemSet:
                                    codeTarget.Call(this.VisitorResult.GetThis().GetMethod(this.Detail.VisitRefactorName ?? "Visit").Invoke(firstParam.GetReference().GetProperty(prop.Item1.Name)));
                                    break;

                                default:
                                    break;
                                }
                            }
                            if (!firstParamType.Metadata.Contains(ignoreSetAttr))
                            {
                                var enAccess = IsTypeRelevantForEnumerableAccess(builderInterfaces, firstParamType, relevantActionTypes);
                                if (enAccess.Item2 == VisitorImplementationTypeRelevance.AsItemSet)
                                {
                                    secondNewMethod.Call(this.VisitorResult.GetThis().GetMethod(this.Detail.VisitRefactorName ?? "Visit").Invoke(firstParam.GetReference().Cast(enAccess.Item1)));
                                }
                            }
                        }
                        if (isVoidReturn)
                        {
                            newMethod.Call(invocation);
                        }
                        else
                        {
                            newMethod.Return(invocation);
                        }
                    }
                    else
                    {
                    }
                }
            }
        }
Ejemplo n.º 24
0
            protected override TIntermediateEvent GetEvent(string name, TypedNameSeries eventSignature)
            {
                EventMember result = this.Parent.GetNewEvent(name, eventSignature);

                return((TIntermediateEvent)((object)(result)));
            }
        private static void BuildStructureConstructors(IProductionRuleCaptureStructure targetStructure, OilexerGrammarProductionRuleEntry structureRoot, ITypeIdentityManager identityManager)
        {
            int stateIndex = 0;

            foreach (var element in targetStructure.Values)
            {
                element.StateIndex = stateIndex++;
            }
            IEnumerable <IEnumerable <Tuple <IProductionRuleCaptureStructuralItem, bool> > > validVariations = new IEnumerable <Tuple <IProductionRuleCaptureStructuralItem, bool> > [0];
            var firstOrDefSeries         = (IProductionRuleSeries)targetStructure.Sources.FirstOrDefault(k => k is IProductionRuleSeries);
            var firstOrDefProductionRule = (IOilexerGrammarProductionRuleEntry)targetStructure.Sources.FirstOrDefault(k => k is IOilexerGrammarProductionRuleEntry);
            var optg = PickOptionalGroups(firstOrDefProductionRule == null ? firstOrDefSeries : firstOrDefProductionRule, targetStructure);

            foreach (var parameterSet in targetStructure.Structures)
            {
                var limitedSet = (from param in parameterSet
                                  join item in targetStructure.Keys on param equals item
                                  select new { Name = item, Item = targetStructure[item] }).ToArray();
                var optionalSet = (from l in limitedSet
                                   where l.Item.Optional
                                   select l).ToArray();
                if (limitedSet.Length > 0)
                {
                    var parameterPermutations = VariateSeries(new LockedLinkedList <IProductionRuleCaptureStructuralItem>(from l in limitedSet
                                                                                                                          select l.Item).First, optg).Distinct();
                    validVariations = validVariations.Concat(parameterPermutations);
                    foreach (var variation in parameterPermutations)
                    {
                        bool[] parameterStateFlags = (from k in variation.ToArray()
                                                      select k.Item2).ToArray();
                        List <string> parameterResult = new List <string>();
                        for (int parameterIndex = 0; parameterIndex < parameterStateFlags.Length; parameterIndex++)
                        {
                            if (parameterStateFlags[parameterIndex])
                            {
                                var limitedEntry = limitedSet[parameterIndex];
                                parameterResult.Add(limitedEntry.Name);
                            }
                        }
                        //if (!resultantParameterSets.Any(k => k.SequenceEqual(parameterResult)))
                        //    resultantParameterSets.Add(parameterResult);
                    }
                }
            }
            List <IEnumerable <Tuple <IProductionRuleCaptureStructuralItem, bool> > > toRemove = new List <IEnumerable <Tuple <IProductionRuleCaptureStructuralItem, bool> > >();
            var exclusiveDistinctions = (from set in validVariations.Distinct().ToArray()
                                         let parameters =
                                             from parameter in set
                                             where parameter.Item2
                                             select parameter.Item1
                                             orderby string.Join(string.Empty, from k in parameters
                                                                 select k.BucketName)
                                             select new HashList <IProductionRuleCaptureStructuralItem>(parameters)).Distinct();
            var stateField     = targetStructure.ResultClass.Fields.Add(new TypedName("state", identityManager.ObtainTypeReference(RuntimeCoreType.Int32)));
            var toStringMethod = targetStructure.ResultClass.Methods.Add(new TypedName("ToString", identityManager.ObtainTypeReference(RuntimeCoreType.String)));

            toStringMethod.AccessLevel = AccessLevelModifiers.Public;
            toStringMethod.IsOverride  = true;
            var toStringStateSwitch = toStringMethod.Switch(stateField.GetReference());

            toStringMethod.Return(identityManager.ObtainTypeReference(RuntimeCoreType.String).GetTypeExpression().GetField("Empty"));
            var formatMethod = identityManager.ObtainTypeReference(RuntimeCoreType.String).GetTypeExpression().GetMethod("Format");

            foreach (var parameterSetVariation in exclusiveDistinctions)
            {
                TypedNameSeries currentCtorTNS    = new TypedNameSeries();
                int             currentStateValue = 0;
                foreach (var parameterEntry in parameterSetVariation)
                {
                    var   parameterName  = parameterEntry.BucketName;
                    var   currentElement = targetStructure[parameterName];
                    IType parameterType  = null;
                    switch (currentElement.ResultType)
                    {
                    case ResultedDataType.EnumerationItem:
                    case ResultedDataType.Flag:
                        parameterType = identityManager.ObtainTypeReference(RuntimeCoreType.Boolean);
                        break;

                    case ResultedDataType.Enumeration:
                        IProductionRuleCaptureStructure enumStructure = (IProductionRuleCaptureStructure)currentElement;
                        parameterType = enumStructure.AggregateSetEnum ?? enumStructure.ResultEnumSet[0];
                        break;

                    case ResultedDataType.ComplexType:
                        IProductionRuleCaptureStructure dualStructure = (IProductionRuleCaptureStructure)currentElement;
                        parameterType = dualStructure.ResultInterface;
                        break;

                    case ResultedDataType.Counter:
                        parameterType = identityManager.ObtainTypeReference(RuntimeCoreType.Int32);
                        break;

                    case ResultedDataType.Character:
                        parameterType = identityManager.ObtainTypeReference(RuntimeCoreType.Char);
                        break;

                    case ResultedDataType.String:
                        parameterType = identityManager.ObtainTypeReference(RuntimeCoreType.String);
                        break;

                    default:
                        throw new InvalidOperationException("Unknown parameter type.");
                    }
                    currentStateValue |= (int)Math.Pow(2, parameterEntry.StateIndex);
                    currentCtorTNS.Add(LowerFirstCharacter(parameterName), parameterType);
                }
                var currentCtor = targetStructure.ResultClass.Constructors.Add(currentCtorTNS);
                currentCtor.AccessLevel = AccessLevelModifiers.Public;
                currentCtor.Assign(stateField.GetReference(), currentStateValue.ToPrimitive());
                var currentStateCase  = toStringStateSwitch.Case(currentStateValue.ToPrimitive());
                var currentInvocation = formatMethod.Invoke();
                currentStateCase.Return(currentInvocation);
                var currentFormat = string.Empty.ToPrimitive();
                currentInvocation.Arguments.Add(currentFormat);
                StringBuilder formatBuilder     = new StringBuilder();
                bool          first             = true;
                int           currentParamIndex = 0;
                foreach (var parameterEntry in parameterSetVariation)
                {
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        formatBuilder.Append(", ");
                    }
                    formatBuilder.AppendFormat("{{{0}}}", currentParamIndex++);
                    var parameterName  = parameterEntry.BucketName;
                    var currentElement = targetStructure[parameterName];
                    IIntermediateFieldMember currentField = currentElement.AssociatedField;
                    currentInvocation.Arguments.Add(currentField.GetReference());
                    currentCtor.Assign(currentField.GetReference(), currentCtor.Parameters[LowerFirstCharacter(parameterName)].GetReference());
                }
                currentFormat.Value = formatBuilder.ToString();
            }
        }
Ejemplo n.º 26
0
            protected override IIntermediateGenericParameterIndexerMember <TGenericParameter, TIntermediateGenericParameter> GetNew(TypedName nameAndReturn, TypedNameSeries parameters, bool canGet = true, bool canSet = true)
            {
                var result = new IndexerMember(nameAndReturn.Name, this.Parent, this.Parent.Assembly);

                if (parameters.Count > 0)
                {
                    result.Parameters.AddRange(parameters.ToArray());
                }
                result.PropertyType = nameAndReturn.TypeReference;
                result.CanRead      = canGet;
                result.CanWrite     = canSet;
                return(result);
            }
 IIntermediateEventMember IIntermediateEventMemberDictionary.Add(string name, TypedNameSeries eventSignature)
 {
     return(this.Add(name, eventSignature));
 }