public static IMethod ImplementForwardingCaseFactory(this VirtualType type, string caseName, IMethod caseCtor, IMethod valueTypeCtor)
        {
            var valueType = caseCtor.Parameters.Single().Type;

            Debug.Assert(valueType == valueTypeCtor.DeclaringType);

            var caseFactory = new VirtualMethod(type, Accessibility.Public,
                                                E.SymbolNamer.NameMethod(type, caseName, 0, valueTypeCtor.Parameters, isOverride: false),
                                                valueTypeCtor.Parameters,
                                                returnType: type,
                                                isStatic: true,
                                                doccomment: (valueTypeCtor as IWithDoccomment)?.Doccomment
                                                );

            caseFactory.BodyFactory = () => {
                var call = new IL.NewObj(valueTypeCtor);
                call.Arguments.AddRange(valueTypeCtor.Parameters.Select((p, i) => new IL.LdLoc(new IL.ILVariable(IL.VariableKind.Parameter, p.Type, i))));
                return(EmitExtensions.CreateExpressionFunction(caseFactory,
                                                               new IL.NewObj(caseCtor)
                {
                    Arguments = { call }
                }
                                                               ));
            };
            type.Methods.Add(caseFactory);
            return(caseFactory);
        }
Exemple #2
0
        public DefFunction(XmlElement elem)
            : base(elem)
        {
            if (elem.Name != "function")
            {
                throw new Exception("Wrong element; expected 'function'.");
            }

            switch (elem.GetAttribute("virt"))
            {
            case "virtual":
                VirtualType = VirtualType.Virtual;
                break;

            case "non-virtual":
                VirtualType = VirtualType.NonVirtual;
                break;

            case "pure-virtual":
                VirtualType = VirtualType.PureVirtual;
                break;

            default:
                throw new Exception("unexpected");
            }
            _isConstFunctionCall = bool.Parse(elem.GetAttribute("const"));
        }
Exemple #3
0
        public static (VirtualProperty prop, IField field) AddAutoProperty(this VirtualType declaringType, string name, IType propertyType, Accessibility accessibility = Accessibility.Public, bool isReadOnly = true)
        {
            name = E.SymbolNamer.NameMember(declaringType, name, lowerCase: accessibility == Accessibility.Private);


            var field = new VirtualField(declaringType, Accessibility.Private, string.Format(AutoPropertyField, name), propertyType, isReadOnly: isReadOnly, isHidden: true);

            field.Attributes.Add(declaringType.Compilation.CompilerGeneratedAttribute());

            var getter = new VirtualMethod(declaringType, accessibility, string.Format(PropertyGetter, name), Array.Empty <IParameter>(), propertyType, isHidden: true);

            getter.BodyFactory = () => CreateExpressionFunction(getter,
                                                                new IL.LdObj(new IL.LdFlda(new IL.LdLoc(new IL.ILVariable(IL.VariableKind.Parameter, declaringType, -1)), field), propertyType)
                                                                );
            getter.Attributes.Add(declaringType.Compilation.CompilerGeneratedAttribute());
            var setter = isReadOnly ? null :
                         new VirtualMethod(declaringType, accessibility, string.Format(PropertySetter, name), new [] { new VirtualParameter(propertyType, "value") }, declaringType.Compilation.FindType(typeof(void)), isHidden: true);

            var prop = new VirtualProperty(declaringType, accessibility, name, getter, setter);

            declaringType.Methods.Add(getter);
            if (setter != null)
            {
                declaringType.Methods.Add(setter);
            }

            declaringType.Fields.Add(field);
            declaringType.Properties.Add(prop);

            return(prop, field);
        }
Exemple #4
0
        public static IProperty AddExplicitInterfaceProperty(this VirtualType declaringType, IProperty ifcProperty, IMember baseMember)
        {
            Debug.Assert(declaringType.Equals(baseMember.DeclaringType) || declaringType.GetAllBaseTypeDefinitions().Contains(baseMember.DeclaringType));
            Debug.Assert(ifcProperty.DeclaringType.Kind == TypeKind.Interface);

            var getter = new VirtualMethod(declaringType, Accessibility.Private, "get_" + ifcProperty.FullName, new IParameter[0], ifcProperty.ReturnType, explicitImplementations: new [] { ifcProperty.Getter }, isHidden: true);

            getter.BodyFactory = () => {
                var thisParam = new IL.ILVariable(IL.VariableKind.Parameter, declaringType, -1);
                return(CreateExpressionFunction(getter, new IL.LdLoc(thisParam).AccessMember(baseMember)));
            };
            var setter =
                ifcProperty.Setter == null ? null :
                new VirtualMethod(declaringType, Accessibility.Private, "get_" + ifcProperty.FullName, ifcProperty.Setter.Parameters, ifcProperty.Setter.ReturnType, explicitImplementations: new [] { ifcProperty.Setter }, isHidden: true);

            if (setter != null)
            {
                setter.BodyFactory = () => {
                    var thisParam  = new IL.ILVariable(IL.VariableKind.Parameter, declaringType, -1);
                    var valueParam = new IL.ILVariable(IL.VariableKind.Parameter, declaringType, 0);
                    return(CreateExpressionFunction(getter, new IL.LdLoc(thisParam).AssignMember(baseMember, new IL.LdLoc(valueParam))));
                }
            }
            ;

            var prop = new VirtualProperty(declaringType, Accessibility.Private, ifcProperty.FullName, getter, setter, explicitImplementations: new [] { ifcProperty });

            getter.ApplyAction(declaringType.Methods.Add);
            setter?.ApplyAction(declaringType.Methods.Add);
            prop.ApplyAction(declaringType.Properties.Add);

            return(prop);
        }
        static IMethod ImplementIntoCaseConversion(this VirtualType type, IType valueType, IMethod caseCtor, bool isImplicit = true)
        {
            Debug.Assert(valueType == caseCtor.Parameters.Single().Type);
            Debug.Assert(valueType.Kind != TypeKind.Interface); // can't have conversion from interface
            Debug.Assert(valueType != type);                    // can't have conversion from itself

            var caseFactory = new VirtualMethod(type, Accessibility.Public,
                                                isImplicit ? "op_Implicit" : "op_Explicit",
                                                new[] { new VirtualParameter(valueType, "item") },
                                                returnType: type,
                                                isStatic: true
                                                );

            caseFactory.BodyFactory = () => {
                var @this             = new IL.ILVariable(IL.VariableKind.Parameter, valueType, 0);
                IL.ILInstruction body = new IL.NewObj(caseCtor)
                {
                    Arguments = { new IL.LdLoc(@this) }
                };
                if (valueType.IsReferenceType == true)
                {
                    // pass nulls
                    body = new IL.IfInstruction(
                        new IL.Comp(IL.ComparisonKind.Inequality, Sign.None, new IL.LdLoc(@this), new IL.LdNull()),
                        body,
                        new IL.LdNull()
                        );
                }
                return(EmitExtensions.CreateExpressionFunction(caseFactory, body));
            };
            type.Methods.Add(caseFactory);
            return(caseFactory);
        }
        private void GenerateContractServiceKnownTypes(CodeTypeDeclaration contractInterface, DomainOperationEntry operation, HashSet <Type> registeredTypes)
        {
            List <Attribute> knownTypeAttributes = new List <Attribute>();

            foreach (DomainOperationParameter parameter in operation.Parameters)
            {
                Type t = CodeGenUtilities.TranslateType(parameter.ParameterType);

                // All Nullable<T> types are unwrapped to the underlying non-nullable, because
                // that is they type we need to represent, not typeof(Nullable<T>)
                t = TypeUtility.GetNonNullableType(t);

                if (TypeUtility.IsPredefinedListType(t) || TypeUtility.IsComplexTypeCollection(t))
                {
                    Type elementType = TypeUtility.GetElementType(t);
                    if (elementType != null)
                    {
                        t = elementType.MakeArrayType();
                    }
                }

                // Check if the type is a simple type or already registered
                if (registeredTypes.Contains(t) || !this.TypeRequiresRegistration(t))
                {
                    continue;
                }

                // Record the type to prevent redundant [ServiceKnownType]'s.
                // This loop executes within a larger loop over multiple
                // DomainOperationEntries that may have already processed it.
                registeredTypes.Add(t);

                // If we determine we need to generate this enum type on the client,
                // then we need to register that intent and conjure a virtual type
                // here in our list of registered types to account for the fact it
                // could get a different root namespace on the client.
                if (t.IsEnum && this.ClientProxyGenerator.NeedToGenerateEnumType(t))
                {
                    // Request deferred generation of the enum
                    this.ClientProxyGenerator.RegisterUseOfEnumType(t);

                    // Compose a virtual type that will reflect the correct namespace
                    // on the client when the [ServiceKnownType] is created.
                    t = new VirtualType(t.Name, CodeGenUtilities.TranslateNamespace(t, this.ClientProxyGenerator), t.Assembly, t.BaseType);
                }

                knownTypeAttributes.Add(new ServiceKnownTypeAttribute(t));
            }

            if (knownTypeAttributes.Count > 0)
            {
                CustomAttributeGenerator.GenerateCustomAttributes(
                    this.ClientProxyGenerator,
                    contractInterface,
                    knownTypeAttributes,
                    contractInterface.CustomAttributes,
                    contractInterface.Comments,
                    true /* force propagation, we want a compile error if these types aren't present on client */);
            }
        }
Exemple #7
0
 public void AddField(VirtualType type, string name, string description)
 {
     if (type == null)
     {
         throw new ArgumentNullException(nameof(type));
     }
     fields.Add(NewField(type, name, description));
 }
        public void VirtualType_ctors()
        {
            VirtualType vt = new VirtualType("name", "namespace", this.GetType().Assembly, this.GetType());

            Assert.AreEqual("name", vt.Name);
            Assert.AreEqual("namespace", vt.Namespace);
            Assert.AreEqual(this.GetType().Assembly, vt.Assembly);
            Assert.AreEqual(this.GetType(), vt.BaseType);

            vt = new VirtualType(this.GetType());
            this.AssertEquivalentTypes(this.GetType(), vt);
        }
        /// Implements "forwarding constructor" that creates creates an instance of the inner class from it's constructor parameters
        public static ImmutableArray <IMethod> TryImplementForwardingCaseFactory(this VirtualType type, string caseName, IMethod caseCtor)
        {
            var valueType = caseCtor.Parameters.Single().Type;

            // allowed only for "our" types
            if (!(valueType is VirtualType))
            {
                return(ImmutableArray <IMethod> .Empty);
            }

            return
                (valueType.GetConstructors(c => c.Accessibility == Accessibility.Public)
                 .Select(ctor => type.ImplementForwardingCaseFactory(caseName, caseCtor, ctor))
                 .ToImmutableArray());
        }
Exemple #10
0
        private Field NewField(VirtualType type, string name, string description)
        {
            var field = new Field
            {
                Type        = type,
                Name        = name,
                Description = description,
            };

            if (type is CustomType customType)
            {
                innerTypes.Add(customType);
            }
            return(field);
        }
        public static IMethod[] ImplementAllIntoCaseConversions(this VirtualType type, IMethod[] caseCtors, bool isImplicit = true)
        {
            var dupTypes = new HashSet <IType>(
                caseCtors
                .GroupBy(c => c.Parameters.Single().Type)
                .Where(t => t.Count() > 1)
                .Select(t => t.Key));

            var result =
                from ctor in caseCtors
                let valueType = ctor.Parameters.Single().Type
                                where valueType.Kind != TypeKind.Interface
                                where valueType != type
                                where !dupTypes.Contains(valueType)
                                select ImplementIntoCaseConversion(type, valueType, ctor, isImplicit);

            return(result.ToArray());
        }
Exemple #12
0
        public override IMessage Invoke(IMessage msg)
        {
            IMethodCallMessage msgCall = msg as IMethodCallMessage;

            if (msgCall != null)
            {
                try{
                    object[] args = msgCall.Args;
                    object   ret  = VirtualType.InvokeMethod(msgCall.MethodBase, this.GetTransparentProxy(), args);
                    return(new ReturnMessage(ret, args, args.Length, msgCall.LogicalCallContext, msgCall));
                }catch (TargetInvocationException e)
                {
                    return(new ReturnMessage(e.InnerException, msgCall));
                }catch (Exception e)
                {
                    return(new ReturnMessage(e, msgCall));
                }
            }
            return(null);
        }
        public static IMethod ImplementBasicCaseFactory(this VirtualType type, string caseName, IMethod caseCtor)
        {
            var valueType   = caseCtor.Parameters.Single().Type;
            var doccomment  = (valueType.GetDefinition() as IWithDoccomment)?.Doccomment;
            var caseFactory = new VirtualMethod(type, Accessibility.Public,
                                                E.SymbolNamer.NameMethod(type, caseName, 0, new [] { valueType }, isOverride: false),
                                                new[] { new VirtualParameter(valueType, "item") },
                                                returnType: type,
                                                isStatic: true,
                                                doccomment: doccomment
                                                );

            caseFactory.BodyFactory = () =>
                                      EmitExtensions.CreateExpressionFunction(caseFactory,
                                                                              new IL.NewObj(caseCtor)
            {
                Arguments = { new IL.LdLoc(new IL.ILVariable(IL.VariableKind.Parameter, valueType, 0)) }
            }
                                                                              );
            type.Methods.Add(caseFactory);
            return(caseFactory);
        }
Exemple #14
0
        public static Dictionary <MemberSignature, string> NameMembers(TypeDef type, VirtualType realType, bool adjustCasing)
        {
            var result = new Dictionary <MemberSignature, string>();

            // TODO: overrides
            // foreach (var m in type.Members.OfType<MethodDef>().Where(m => m.Signature.IsOverride))
            // {
            //     var overridesName = m.Implements.Where(i => i.DeclaringType.Kind == "class").Select(cx.GetMethod).SingleOrDefault()?.Name;

            // }

            foreach (var m in type.Members
                     .Where(m => !IsSpecial(m.Signature))
                     .OrderBy(m =>
                              m.Signature.Accessibility == Accessibility.APrivate ? 20 :                                                                  // private
                              m.Signature.Accessibility == Accessibility.AInternal || m.Signature.Accessibility == Accessibility.APrivateProtected ? 19 : // internal
                              m.Signature.Accessibility == Accessibility.APublic ? 0 :                                                                    // public - top priority
                              10                                                                                                                          // protected (so kindof public)
                              ))
            {
                if (m is MethodDef method)
                {
                    var lowerCase = adjustCasing ? false : (bool?)null;
                    var name      = NameMethod(realType, result, m.Signature.Name, method.Signature.TypeParameters.Length, method.Signature.Params.Select(p => p.Type).ToArray(), method.Signature.IsOverride, lowerCase);
                    result.Add(method.Signature, name);
                }
                else
                {
                    var blacklist = m is TypeDef typeMember?BlacklistedTypeNames(typeMember) : null;

                    var lowerCase = adjustCasing ? m is FieldDef : (bool?)null;
                    var name      = NameMember(realType, result, m.Signature.Name, lowerCase, blacklist);
                    result.Add(m.Signature, name);
                }
            }

            // Special Names:
            // don't sanitize nor avoid collisions
            // just replace <oldName> with <newName> for property names
            var propertyTranslationTable =
                type.Members
                .OfType <PropertyDef>()
                .Where(p => !IsSpecial(p.Signature))
                .ToDictionary(p => $"<{p.Signature.Name}>", p => $"<{result[p.Signature]}>");
            var propertyTranslationRegex =
                string.Join("|",
                            propertyTranslationTable.Keys
                            .Select(k => "(" + Regex.Escape(k) + ")"));

            foreach (var m in type.Members.Where(m => IsSpecial(m.Signature)))
            {
                var name = m.Signature.Name;
                if (propertyTranslationTable.Any())
                {
                    name = Regex.Replace(name, propertyTranslationRegex, m => propertyTranslationTable[m.Value]);
                }
                result.Add(m.Signature, name);
            }

            return(result);
        }
        public void VirtualType_BaseTypes()
        {
            VirtualType vt = new VirtualType(typeof(VT_C));

            this.AssertEquivalentTypes(typeof(VT_C), vt);
        }
Exemple #16
0
 //检查指定字段是否符合导入类型
 public virtual void CheckImportField(string memberName, VirtualType memberType)
 {
     throw new InnerException();
 }
Exemple #17
0
 public ArrayType(VirtualType baseType)
 {
     this.baseType = baseType;
 }
Exemple #18
0
 public VirtualObject(string id, VirtualType type)
 {
     Id        = id;
     this.type = type;
 }
Exemple #19
0
 static VirtualMethod CreateSignatureCore(VirtualType type, IEnumerable <(IType type, string desiredName)> properties, bool isOptional, bool returnValidationResult, string doccomment)
Exemple #20
0
 public void SetIdField(VirtualType type, string description)
 {
     IdField = NewField(type, Config.IdName, description);
 }
 public static IMethod ImplementEquality(this VirtualType type, params IMember[] properties) =>
 ImplementEquality(type, properties.Select(p =>
Exemple #22
0
        private static void ParseSplitField(Dictionary <string, SplitField> parent, string fieldPartName, VirtualType type, string description)
        {
            fieldPartName.TrySplit2By('.', out var name, out var body);
            if (!parent.TryGetValue(name, out var splitField))
            {
                splitField = new SplitField();
                parent.Add(name, splitField);
            }

            //check consist
            splitField.Type?.CheckImportField(body, type);

            if (body.Contains("."))
            {
                ParseSplitField(splitField.ChildFields, body, type, description);
            }
            else
            {
                splitField.DeclaredMembers.Add(new DeclaredMember
                {
                    Name        = body,
                    Type        = type,
                    Description = description,
                });
            }
        }