Example #1
0
 /// <summary>
 /// All all interfaces in the given signature to the given type definition.
 /// </summary>
 private void ImplementInterfaces(NetTypeDefinition typeDef, ClassSignature signature, TargetFramework target)
 {
     if (signature == null)
     {
         return;
     }
     foreach (var interfaceName in signature.Interfaces)
     {
         try
         {
             NetTypeDefinition iDef;
             if (target.TypeNameMap.TryGetByJavaClassName(interfaceName.ClassName, out iDef) && iDef.IsInterface)
             {
                 var iRef = interfaceName.Resolve(target, this, false);
                 if (!typeDef.Interfaces.Any(x => x.AreSame(iRef)))
                 {
                     typeDef.Interfaces.Add(iRef);
                 }
             }
         }
         catch (ClassNotFoundException)
         {
             Console.WriteLine("Interface {0} not found in {1}", interfaceName.ClassName, typeDef.FullName);
         }
     }
 }
Example #2
0
            public bool Visit(NetTypeDefinition type, INetMemberVisibility member)
            {
                if (!member.HasSameScope(type))
                {
                    return(false);
                }

                if (member.IsPublic || member.IsFamily || member.IsFamilyOrAssembly || member.IsNestedPublic)
                {
                    // Member is publicly visible
                    if (type.IsNotPublic)
                    {
                        type.IsPublic = true;
                        return(true);
                    }
                    if (type.IsNestedPrivate || type.IsNestedFamily || type.IsNestedFammilyOrAssembly || type.IsNestedAssembly)
                    {
                        type.IsNestedPublic = true;
                        return(true);
                    }
                }
                else if (member.IsAssembly)
                {
                    // Member is internally visible
                    if (type.IsNestedPrivate)
                    {
                        type.IsNestedAssembly = true;
                        return(true);
                    }
                }
                return(false);
            }
Example #3
0
        /// <summary>
        /// Remove duplicate methods from the type definition.
        /// </summary>
        protected static void RemoveDuplicateMethods(NetTypeDefinition typeDef)
        {
            var methods = typeDef.Methods.ToList();

            for (var i = 0; i < methods.Count; i++)
            {
                var m1 = methods[i];
                for (var j = i + 1; j < methods.Count;)
                {
                    var mj = methods[j];
                    if (m1.IsDuplicate(mj))
                    {
                        // Remove m2
                        methods.RemoveAt(j);
                        typeDef.Methods.Remove(mj);
                        if (m1.Description == null)
                        {
                            m1.Description = mj.Description;
                        }
                    }
                    else
                    {
                        j++;
                    }
                }
            }
        }
Example #4
0
 /// <summary>
 /// Gets the base type + implemented interfaces of the given type.
 /// </summary>
 internal static IEnumerable <NetTypeReference> GetBaseTypes(this NetTypeDefinition type, bool recursive)
 {
     if (type.BaseType != null)
     {
         yield return(type.BaseType);
     }
     foreach (var intf in type.Interfaces)
     {
         yield return(intf);
     }
     if (recursive)
     {
         if ((type.BaseType != null))
         {
             foreach (var t in type.BaseType.GetElementType().GetBaseTypes(true))
             {
                 yield return(t);
             }
         }
         foreach (var t in type.Interfaces.Select(x => x.GetElementType()).SelectMany(intf => intf.GetBaseTypes(true)))
         {
             yield return(t);
         }
     }
 }
Example #5
0
 /// <summary>
 /// Create a type defrinition for the given class file and all inner classes.
 /// </summary>
 public override void CreateType(NetTypeDefinition declaringType, NetModule module, TargetFramework target)
 {
     // Create basic type
     typeDef = new NetTypeDefinition(ClassFile.Empty, target, Scope) { Name = name, Namespace = @namespace, Attributes = Attributes };
     module.Types.Add(typeDef);
     target.TypeNameMap.Add("custom/" + name, typeDef);
 }
        /// <summary>
        /// Create a NetTypeDefinition wrapper for the given dex import.
        /// </summary>
        private NetTypeDefinition CreateNetTypeDef(AssemblyClassLoader.DexImport dexImport, Action <ClassFile> classLoaded,
                                                   Func <TypeDefinition, AssemblyClassLoader.DexImport> type2DexImport, TargetFramework target)
        {
            // Convert dex import to class file
            var dexMethods = new List <AssemblyClassLoader.DexImportMethod>();
            var classFile  = dexImport.Resolve(assemblyClassLoader, classLoaded, dexMethods);

            // Build type-definition
            var typeDef = new NetTypeDefinition(classFile, target, dexImport.Scope)
            {
                Namespace           = dexImport.FirstType.Namespace,
                Name                = StripGenerics(dexImport.FirstType.Name),
                Attributes          = (TypeAttributes)dexImport.FirstType.Attributes,
                ImportedFromMapping = true
            };

            // Build custom attribute
            typeDef.CustomAttributes.Add(BuildCustomAttribute(dexImport.ImportAttribute));

            // Add generic parameters
            if (dexImport.FirstType.HasGenericParameters)
            {
                foreach (var gp in dexImport.FirstType.GenericParameters)
                {
                    typeDef.GenericParameters.Add(new NetGenericParameter(gp.Name, gp.Name, typeDef));
                }
            }

            // Record builder to complete later
            implementationBuilders.Add(new NetTypeImplementationBuilder(this, classFile, typeDef, dexImport, dexMethods, type2DexImport));

            return(typeDef);
        }
        /// <summary>
        /// Create a type defrinition for the given class file and all inner classes.
        /// </summary>
        public override void CreateType(NetTypeDefinition declaringType, NetModule module, TargetFramework target)
        {
            if (declaringType != null)
            {
                throw new ArgumentException("Declaring type should be null");
            }
            docClass = target.GetXmlClass(cf);

            var fullName = GetFullName();
            var dotIndex = fullName.LastIndexOf('.');
            var ns       = (dotIndex > 0) ? NameConverter.UpperCamelCase(fullName.Substring(0, dotIndex)) : String.Empty;
            var name     = (dotIndex > 0) ? NameConverter.UpperCamelCase(fullName.Substring(dotIndex + 1)) : fullName;

            name = CreateTypeName(null, cf, name, ns);

            typeDef                        = new NetTypeDefinition(cf, target, module.Scope);
            typeDef.Name                   = name;
            typeDef.Namespace              = ns;
            typeDef.OriginalJavaClassName  = cf.ClassName;
            typeDef.Attributes             = GetAttributes(cf, cf.Fields.Any());
            typeDef.IgnoreGenericArguments = !AddGenericParameters;
            typeDef.Description            = (docClass != null) ? docClass.Description : null;
            module.Types.Add(typeDef);

            // Prepare generics
            CreateGenericParameters(cf, typeDef);

            // Add mapping
            var finalFullName = string.IsNullOrEmpty(ns) ? name : ns + "." + name;

            RegisterType(target, cf, typeDef);
            CreateNestedTypes(cf, typeDef, finalFullName, module, target);
        }
Example #8
0
        /// <summary>
        /// Create the field in the given type
        /// </summary>
        public void Create(NetTypeDefinition declaringType, TargetFramework target)
        {
            // Do not add private fields
            if ((javaField.AccessFlags & FieldAccessFlags.Private) != 0)
            {
                return;
            }

            // Find documentation
            var docClass = declaringTypeBuilder.Documentation;

            docField = (docClass != null) ? docClass.Fields.FirstOrDefault(x => x.Name == javaField.Name) : null;

            //var fieldType = declaringType.IsEnum ? target.TypeNameMap.GetByType(typeof(int)) : javaField.Signature.Resolve(target, declaringTypeBuilder);
            NetTypeReference fieldType;

            if (!javaField.Signature.TryResolve(target, declaringTypeBuilder, false, out fieldType))
            {
                return;
            }

            //var fieldTypeIsValueType = declaringType.IsEnum ? true : javaField.FieldType.
            var name = declaringTypeBuilder.GetFieldName(javaField);

            field                  = new NetFieldDefinition();
            field.Name             = name;
            field.OriginalJavaName = javaField.Name;
            field.FieldType        = fieldType;
            field.Attributes       = GetAttributes(javaField, false);
            field.Description      = (docField != null) ? docField.Description : null;
            declaringType.Fields.Add(field);
        }
Example #9
0
        /// <summary>
        /// Create a type defrinition for the given class file and all inner classes.
        /// </summary>
        public override void CreateType(NetTypeDefinition declaringType, NetModule module, TargetFramework target)
        {
            if (declaringType == null)
            {
                throw new ArgumentNullException("declaringType");
            }
            docClass = target.GetXmlClass(cf);

            var name = NameConverter.UpperCamelCase(inner.IsAnonymous ? cf.Name : inner.Name);

            name = CreateTypeName(declaringType, cf, name, null);

            var finalFullName = parentFullName + "/" + name;

            var attributes = GetAttributes(cf);

            typeDef = new NetTypeDefinition(cf, target, module.Scope)
            {
                Name = name, Attributes = attributes
            };
            typeDef.OriginalJavaClassName = cf.ClassName;
            typeDef.Description           = (docClass != null) ? docClass.Description : null;
            parent.AddNestedType(typeDef, "", module, ref finalFullName);

            // Prepare generics
            CreateGenericParameters(cf, typeDef);

            // Add mapping
            RegisterType(target, cf, typeDef);
            CreateNestedTypes(cf, typeDef, finalFullName, module, target);
        }
Example #10
0
        /// <summary>
        /// Create wrapper for given jar file
        /// </summary>
        private void CreateAssembly(JarFile jf, string folder)
        {
            // Create java type wrappers
            var module = new NetModule(jf.Scope);

            var classTypeBuilders = jf.ClassNames.SelectMany(n => StandardTypeBuilder.Create(jf.LoadClass(n), target));

            var typeBuilders = classTypeBuilders.OrderBy(x => x.Priority).ToList();

            typeBuilders.ForEach(x => x.CreateType(null, module, target));

            // Implement and finalize types
            Implement(typeBuilders, target);

            var assemblyAttributes = new List <NetCustomAttribute>();

            if (!importAsStubs)
            {
                // Import code
                var attrType = new NetTypeDefinition(ClassFile.Empty, target, AttributeConstants.Dot42Scope)
                {
                    Name      = AttributeConstants.JavaCodeAttributeName,
                    Namespace = AttributeConstants.Dot42AttributeNamespace
                };
                string hash = JarReferenceHash.ComputeJarReferenceHash(jarFilePath);
                var    attr = new NetCustomAttribute(attrType, hash, Path.GetFileName(jarFilePath));
                assemblyAttributes.Add(attr);
            }

            // Save
            CodeGenerator.Generate(folder, module.Types, assemblyAttributes, target, this, target);
        }
Example #11
0
        /// <summary>
        /// Add a default ctor if there is none, but there are other ctors.
        /// </summary>
        private void AddDefaultConstructor(NetTypeDefinition typeDef, TargetFramework target)
        {
            if (typeDef.IsStruct || typeDef.IsInterface || (this is IInterfaceConstantsTypeBuilder))
            {
                return;
            }
            var ctors = typeDef.Methods.Where(x => x.IsConstructor).ToList();

            if (ctors.Count == 0)
            {
                return;
            }
            // Is there a default ctor?
            if (ctors.Any(x => x.Parameters.Count == 0))
            {
                return;
            }

            // Add default ctor
            var ctor = new NetMethodDefinition(".ctor", null, typeDef, target, SignedByteMode.None, "TypeBuilder.AddDefaultConstructor")
            {
                Attributes           = MethodAttributes.FamORAssem,
                AccessFlags          = (int)MethodAccessFlags.Protected,
                EditorBrowsableState = EditorBrowsableState.Never
            };

            typeDef.Methods.Add(ctor);
        }
Example #12
0
 /// <summary>
 /// Gets the name for a type parameter of a method of my class.
 /// If the name is the same as a type parameter of this class, we rename it, otherwise the given original is returned.
 /// </summary>
 internal static string GetMethodGenericParameterName(NetTypeDefinition typeDef, string original)
 {
     if (typeDef.GenericParameters.Any(x => x.Name == original))
     {
         return("Java" + original);
     }
     return(original);
 }
Example #13
0
 /// <summary>
 /// Fix base type relations.
 /// </summary>
 protected override void FixBaseType(NetTypeDefinition typeDef, TargetFramework target)
 {
     if ((typeDef.BaseType != null) && (typeDef.BaseType.FullName == "Java.Lang.Number"))
     {
         typeDef.BaseType = null;
     }
     base.FixBaseType(typeDef, target);
 }
Example #14
0
 /// <summary>
 /// Default ctor
 /// </summary>
 public CodeTypeReferenceBuilder(NetTypeDefinition context, bool useShortTypeNames, bool useShortNestedTypeNames, bool allowVoid, TypeNameMap typeNameMap)
 {
     this.context                 = context;
     this.useShortTypeNames       = useShortTypeNames;
     this.useShortNestedTypeNames = useShortNestedTypeNames;
     this.allowVoid               = allowVoid;
     this.typeNameMap             = typeNameMap;
 }
Example #15
0
        /// <summary>
        /// Convert type attributes to string
        /// </summary>
        private static String Convert(NetTypeDefinition type, TypeAttributes source)
        {
            string result;

            switch (source & TypeAttributes.VisibilityMask)
            {
            case TypeAttributes.NotPublic:
            case TypeAttributes.NestedAssembly:
                result = "internal ";
                break;

            case TypeAttributes.Public:
            case TypeAttributes.NestedPublic:
                result = "public ";
                break;

            case TypeAttributes.NestedPrivate:
                result = "private ";
                break;

            case TypeAttributes.NestedFamily:
            case TypeAttributes.NestedFamANDAssem:
                result = "protected ";
                break;

            case TypeAttributes.NestedFamORAssem:
                result = "protected internal ";
                break;

            default:
                throw new ArgumentException(string.Format("Unknown visibility 0x{0:X4}", (int)(source & TypeAttributes.VisibilityMask)));
            }
            if (!(type.IsInterface || type.IsStruct || type.IsEnum || type.IsStatic))
            {
                if (source.HasFlag(TypeAttributes.Abstract))
                {
                    result += "abstract ";
                }
                if (source.HasFlag(TypeAttributes.Sealed))
                {
                    result += "sealed ";
                }
            }
            if (type.IsStatic)
            {
                result += "static ";
            }
            if (type.IsEnum)
            {
                result += "sealed ";
            }
            if (!type.IsEnum)
            {
                result += "partial ";
            }
            return(result);
        }
Example #16
0
        /// <summary>
        /// Gets the base type, parent base type, parent parent base type and so on.
        /// </summary>
        internal static IEnumerable <NetTypeReference> GetBaseTypesWithoutInterfaces(this NetTypeDefinition type)
        {
            while (type.BaseType != null)
            {
                yield return(type.BaseType);

                type = type.BaseType.GetElementType();
            }
        }
Example #17
0
        /// <summary>
        /// Update the attributes of the given method
        /// </summary>
        protected static MethodAttributes GetMethodAttributes(NetTypeDefinition typeDef, MethodDefinition method, MethodAttributes attributes)
        {
            if ((typeDef.IsStruct) || ((typeDef.Attributes & TypeAttributes.Sealed) != 0))
            {
                attributes |= MethodAttributes.Final;
            }

            return(attributes);
        }
Example #18
0
        /// <summary>
        /// Create type attributes
        /// </summary>
        private static MethodAttributes GetAttributes(NetTypeDefinition declaringType, NetMethodDefinition method, MethodDefinition javaMethod, string methodName, TypeNameMap typeNameMap)
        {
            var result   = (MethodAttributes)0;
            var isStatic = javaMethod.IsStatic;

            if (javaMethod.IsPublic)
            {
                result |= MethodAttributes.Public;
            }
            else if (javaMethod.IsProtected)
            {
                result |= MethodAttributes.FamORAssem;
            }
            else if (javaMethod.IsPrivate)
            {
                result |= MethodAttributes.Private;
            }
            else if (javaMethod.IsPackagePrivate)
            {
                result |= MethodAttributes.Assembly;
            }

            if (isStatic)
            {
                result |= MethodAttributes.Static;
            }
            if (javaMethod.IsAbstract)
            {
                result |= MethodAttributes.Abstract;
            }
            if (declaringType.IsInterface)
            {
                result |= MethodAttributes.Abstract;
            }

            if ((!javaMethod.IsFinal) && !isStatic && (methodName != ".ctor") && (!declaringType.IsStruct))
            {
                result |= MethodAttributes.Virtual;
            }
            else
            {
                result |= MethodAttributes.Final;
            }

            if (methodName == ".cctor")
            {
                result |= MethodAttributes.Static;
            }

            if (declaringType.IsSealed)
            {
                result &= ~MethodAttributes.Virtual;
            }

            return(result);
        }
Example #19
0
 /// <summary>
 /// Create a type defrinition for the given class file and all inner classes.
 /// </summary>
 public override void CreateType(NetTypeDefinition declaringType, NetModule module, TargetFramework target)
 {
     // Create basic type
     typeDef = new NetTypeDefinition(ClassFile.Empty, target, Scope)
     {
         Name = name, Namespace = @namespace, Attributes = Attributes
     };
     module.Types.Add(typeDef);
     target.TypeNameMap.Add("custom/" + name, typeDef);
 }
Example #20
0
        /// <summary>
        /// Add a private default constructor.
        /// </summary>
        private static void AddPrivateDefaultCtor(NetTypeDefinition typeDef, TargetFramework target)
        {
            var ctor = new NetMethodDefinition(".ctor", null, typeDef, target, SignedByteMode.None, "TypeBuilder.AddPrivateDefaultCtor")
            {
                Attributes  = MethodAttributes.Private,
                AccessFlags = (int)MethodAccessFlags.Private
            };

            typeDef.Methods.Add(ctor);
        }
Example #21
0
            /// <summary>
            /// Gets the root part of the namespace.
            /// </summary>
            public string GetNamespaceRoot(NetTypeDefinition type)
            {
                var ns = type.Namespace;

                if (!string.IsNullOrEmpty(ns))
                {
                    return(ns);
                }
                return(PossibleRoots[0]);
            }
Example #22
0
        /// <summary>
        /// Try to resolve the given NET name.
        /// </summary>
        void ITypeMapResolver.TryResolve(Type netType, TypeNameMap typeNameMap)
        {
            // Auto create a typedef.
            var typeDef = new NetTypeDefinition(ClassFile.Empty, target, AttributeConstants.Dot42Scope)
            {
                Namespace = netType.Namespace, Name = netType.Name
            };

            typeNameMap.Add(netType.FullName, typeDef);
        }
Example #23
0
        public static bool IsNameClash(NetTypeDefinition typeDef, NetPropertyDefinition prop)
        {
            if ((prop.Getter ?? prop.Setter).InterfaceType != null)
                return false;

            var name = prop.Name;
            return prop.Name == typeDef.Name
                             || typeDef.NestedTypes.Any(x => x.Name == name)
                             || typeDef.Methods.Any(x => (x != prop.Getter && x != prop.Setter) && (x.Name == name));
        }
Example #24
0
 /// <summary>
 /// Remove abstract methods that override another abstract method.
 /// </summary>
 private static void RemoveAbstractOverrides(NetTypeDefinition typeDef)
 {
     foreach (var iterator in typeDef.Methods.Where(x => x.IsAbstract).ToList())
     {
         var method = iterator;
         if (typeDef.GetBaseTypesWithoutInterfaces().SelectMany(x => x.GetElementType().Methods).Any(x => x.IsAbstract && x.IsExactDuplicate(method)))
         {
             typeDef.Methods.Remove(method);
         }
     }
 }
Example #25
0
        /// <summary>
        /// Gets the declaring types of the given type.
        /// </summary>
        internal static IEnumerable <NetTypeDefinition> GetDeclaringTypes(this NetTypeDefinition type)
        {
            var declaringType = type.DeclaringType;

            while (declaringType != null)
            {
                yield return(declaringType);

                declaringType = declaringType.DeclaringType;
            }
        }
 /// <summary>
 /// Default ctor
 /// </summary>
 public NetTypeImplementationBuilder(TypeNameMap typeNameMap, ClassFile classFile, NetTypeDefinition typeDef, AssemblyClassLoader.DexImport dexImport,
                                     List <AssemblyClassLoader.DexImportMethod> dexMethods,
                                     Func <TypeDefinition, AssemblyClassLoader.DexImport> type2DexImport)
 {
     this.typeNameMap    = typeNameMap;
     this.classFile      = classFile;
     this.typeDef        = typeDef;
     this.dexMethods     = dexMethods;
     this.type2DexImport = type2DexImport;
     this.dexImport      = dexImport;
 }
Example #27
0
 /// <summary>
 /// Remove all ctors from interfaces.
 /// </summary>
 private static void RemoveInterfaceConstructors(NetTypeDefinition typeDef)
 {
     if (!typeDef.IsInterface)
     {
         return;
     }
     foreach (var ctor in typeDef.Methods.Where(x => x.IsConstructor).ToList())
     {
         typeDef.Methods.Remove(ctor);
     }
 }
Example #28
0
 /// <summary>
 /// Adds the given nested type to my type declaration.
 /// </summary>
 protected internal override void AddNestedType(NetTypeDefinition nestedType, string namePrefix, NetModule module, ref string fullNestedTypeName)
 {
     if (typeDef.IsInterface)
     {
         // Add to my parent
         parent.AddNestedType(nestedType, cf.Name + "_" + namePrefix, module, ref fullNestedTypeName);
     }
     else
     {
         typeDef.NestedTypes.Add(nestedType);
     }
 }
Example #29
0
        public static bool IsNameClash(NetTypeDefinition typeDef, NetPropertyDefinition prop)
        {
            if ((prop.Getter ?? prop.Setter).InterfaceType != null)
            {
                return(false);
            }

            var name = prop.Name;

            return(prop.Name == typeDef.Name ||
                   typeDef.NestedTypes.Any(x => x.Name == name) ||
                   typeDef.Methods.Any(x => (x != prop.Getter && x != prop.Setter) && (x.Name == name)));
        }
Example #30
0
        /// <summary>
        /// Prepare the given type.
        /// This is called just after the type is created and before nested classes are created.
        /// </summary>
        protected void CreateGenericParameters(ClassFile cf, NetTypeDefinition typeDef)
        {
            // Implemented generic attributes
            var signature = cf.Signature;

            if (AddGenericParameters)
            {
                foreach (var tp in signature.TypeParameters)
                {
                    typeDef.GenericParameters.Add(new NetGenericParameter(tp.Name, tp.Name, typeDef));
                }
            }
        }
Example #31
0
 /// <summary>
 /// Create nested types
 /// </summary>
 protected virtual void CreateNestedTypes(ClassFile cf, NetTypeDefinition declaringType, string parentFullName, NetModule module, TargetFramework target)
 {
     foreach (var inner in cf.InnerClasses)
     {
         ClassFile innerCf;
         if (cf.Loader.TryLoadClass(inner.Inner.ClassName, out innerCf) && (innerCf.DeclaringClass == cf) && ShouldImplement(inner, target))
         {
             foreach (var typeBuilder in NestedTypeBuilder.Create(this, parentFullName, innerCf, inner))
             {
                 typeBuilder.CreateType(declaringType, module, target);
                 nestedTypeBuilders.Add(typeBuilder);
             }
         }
     }
 }
Example #32
0
 /// <summary>
 /// Default ctor
 /// </summary>
 public NetMethodDefinition(string name, JvmClassLib.MethodDefinition javaMethod, NetTypeDefinition declaringType, TargetFramework target, SignedByteMode signMode, string createReason)
 {
     if (name == null)
         throw new ArgumentNullException("name");
     if (declaringType == null)
         throw new ArgumentNullException("declaringType");
     if (target == null)
         throw new ArgumentNullException("target");
     Name = name;
     DeclaringType = declaringType;
     this.javaMethod = javaMethod; // Can be null
     this.target = target;
     this.signMode = signMode;
     this.createReason = createReason;
     overrides = new OverrideCollection(this);
 }
Example #33
0
 /// <summary>
 /// Adds the given nested type to my type declaration.
 /// </summary>
 protected internal override void AddNestedType(NetTypeDefinition nestedType, string namePrefix, NetModule module, ref string fullNestedTypeName)
 {
     if (TypeDefinition.IsInterface)
     {
         // Add to namespace instead (alter name to avoid duplicates)
         nestedType.Name          = typeDef.Name + "_" + namePrefix + nestedType.Name;
         nestedType.Namespace     = typeDef.Namespace;
         nestedType.DeclaringType = null;
         fullNestedTypeName       = nestedType.FullName;
         module.Types.Add(nestedType);
     }
     else
     {
         TypeDefinition.NestedTypes.Add(nestedType);
     }
 }
Example #34
0
        /// <summary>
        /// Create a type defrinition for the given class file and all inner classes.
        /// </summary>
        public override void CreateType(NetTypeDefinition declaringType, NetModule module, TargetFramework target)
        {
            if (declaringType == null)
                throw new ArgumentNullException("declaringType");
            docClass = target.GetXmlClass(cf);

            var name = NameConverter.UpperCamelCase(inner.IsAnonymous ? cf.Name : inner.Name);
            name = CreateTypeName(declaringType, cf, name, null);

            var finalFullName = parentFullName + "/" + name;

            var attributes = GetAttributes(cf);
            typeDef = new NetTypeDefinition(cf, target, module.Scope) { Name = name, Attributes = attributes };
            typeDef.OriginalJavaClassName = cf.ClassName;
            typeDef.Description = (docClass != null) ? docClass.Description : null;
            parent.AddNestedType(typeDef, "", module, ref finalFullName);

            // Prepare generics
            CreateGenericParameters(cf, typeDef);

            // Add mapping
            RegisterType(target, cf, typeDef);
            CreateNestedTypes(cf, typeDef, finalFullName, module, target);
        }
 /// <summary>
 /// Default ctor
 /// </summary>
 public SkipSpecifiedPropertyBuilder(NetTypeDefinition typeDef, TypeBuilder declaringTypeBuilder, Func<NetMethodDefinition, bool?> isPropertyPredicate)
     : base(typeDef, declaringTypeBuilder)
 {
     _isPropertyPredicate = isPropertyPredicate;
 }
 /// <summary>
 /// Default ctor
 /// </summary>
 public SkipSpecifiedPropertyBuilder(NetTypeDefinition typeDef, TypeBuilder declaringTypeBuilder, params string[] skipOriginalJavaProperties)
     : base(typeDef, declaringTypeBuilder)
 {
     _skipOriginalJavaProperties = skipOriginalJavaProperties;
 }
Example #37
0
        /// <summary>
        /// Create the method in the given type
        /// </summary>
        public void Create(NetTypeDefinition declaringType, TargetFramework target)
        {
            try
            {
                // Do not add private methods
                if (javaMethod.IsPrivate)
                {
                    if (javaMethod.Name != "<init>")
                    {
                        return;
                    }
                }

                // Do not add useless bridges methods
                if (javaMethod.IsBridge)
                {
                    var targetMethod = javaMethod.DeclaringClass.Methods.FirstOrDefault(x => javaMethod.IsBridgeFor(x));
                    /*if (javaMethod.DeclaringClass.Methods.Any(x =>
                            (x != javaMethod) && (x.Name == javaMethod.Name) &&
                            (x.Parameters.Count == javaMethod.Parameters.Count) &&
                            (x.Descriptor != javaMethod.Descriptor)))*/
                    if (targetMethod != null)
                    {
                        if (!(targetMethod.IsAbstract && !javaMethod.IsAbstract))
                        {
                            return;
                        }
                    }
                }

                // We're using a dummy return type first.
                // Otherwise we cannot resolve generic return types.
                var signature = javaMethod.Signature;
                var nameInfo = declaringTypeBuilder.GetMethodName(javaMethod);

                var name = nameInfo.Name;
                if (nameInfo.IsConstructor)
                {
                    method = new NetMethodDefinition(".ctor", javaMethod, declaringType, target, convertSignedBytes, "MethodBuilder.Create")
                    {
                        AccessFlags = (int) javaMethod.AccessFlags,
                        EditorBrowsableState = nameInfo.EditorBrowsableState
                    };
                }
                else if (nameInfo.IsDeconstructor)
                {
                    method = new NetMethodDefinition("Finalize", javaMethod, declaringType, target, convertSignedBytes, "MethodBuilder.Create")
                    {
                        AccessFlags = (int) javaMethod.AccessFlags,
                        EditorBrowsableState = EditorBrowsableState.Always,
                        IsDeconstructor = true
                    };
                }
                else
                {
                    method = new NetMethodDefinition(name, javaMethod, declaringType, target, convertSignedBytes, "MethodBuilder.Create")
                    {
                        AccessFlags = (int) javaMethod.AccessFlags,
                        EditorBrowsableState = nameInfo.EditorBrowsableState
                    };
                    foreach (var typeParam in signature.TypeParameters)
                    {
                        method.GenericParameters.Add(
                            new NetGenericParameter(
                                TypeBuilder.GetMethodGenericParameterName(declaringType, typeParam.Name),
                                typeParam.Name, method));
                    }
                    var javaReturnType = signature.ReturnType;
                    NetTypeReference returnType;
                    if (!javaReturnType.TryResolve(target, this, convertSignedBytes, out returnType))
                    {
                        method = null;
                        return;
                    }
                    method.ReturnType = returnType;
                }
                method.OriginalJavaName = javaMethod.Name;

                // Find documentation
                var docClass = declaringTypeBuilder.Documentation;
                if (docClass != null)
                {
                    // Look for matches by name and parameter count first.
                    // If there is more then 1 match, we look to the parameter types.
                    var model = target.XmlModel;
                    var matches = docClass.Methods.Where(x => Matches(x, false, model)).ToList();
                    if (matches.Count == 1)
                    {
                        docMethod = matches[0];
                    }
                    else if (matches.Count > 0)
                    {
                        docMethod = matches.FirstOrDefault(x => Matches(x, true, model));
                    }
                }

                method.Attributes = declaringTypeBuilder.GetMethodAttributes(javaMethod, GetAttributes(declaringType, method, javaMethod, name, target.TypeNameMap));
                var paramIndex = 0;
                foreach (var iterator in signature.Parameters)
                {
                    var paramType = iterator;
                    if (paramType.IsJavaLangVoid())
                    {
                        paramType = new ObjectTypeReference("java/lang/Object", null);
                    }
                    NetTypeReference resolvedParamType;
                    if (!paramType.TryResolve(target, this, convertSignedBytes, out resolvedParamType))
                    {
                        method = null;
                        return; // Sometimes public methods used parameters with internal types
                    }
                    var docParam = (docMethod != null)
                                       ? docMethod.Parameters.ElementAtOrDefault(method.Parameters.Count)
                                       : null;
                    var paramName = MakeParameterNameUnique(CreateParameterName(resolvedParamType, docParam, target),
                                                            method);
                    var isParams = javaMethod.IsVarArgs && (paramIndex == signature.Parameters.Count - 1);
                    method.Parameters.Add(new NetParameterDefinition(paramName, resolvedParamType, isParams));
                    paramIndex++;
                }
                method.Description = (docMethod != null) ? docMethod.Description : null;
                declaringType.Methods.Add(method);
                if (!convertSignedBytes)
                {
                    target.MethodMap.Add(javaMethod, method);
                }
            }
            catch (ClassNotFoundException ex)
            {
                Console.WriteLine("Class {0} not found in {1}", ex.ClassName, javaMethod.Descriptor);
                method = null;
            }
        }
Example #38
0
        /// <summary>
        /// Gets a mapping.
        /// Throws an error if not found.
        /// </summary>
        public bool TryGetByJavaClassName(string javaClassName, out NetTypeDefinition result)
        {
            if (map.TryGetValue(javaClassName, out result))
                return true;
            if (resolver != null)
            {
                // Try to resolve
                resolver.TryResolve(javaClassName, this);

                // Try the get again
                if (map.TryGetValue(javaClassName, out result))
                    return true;
            }
            #if DEBUG
            var names = map.Keys.OrderBy(x => x).ToArray();
            #endif
            return false;
        }
Example #39
0
 /// <summary>
 /// Are this member an the given type definition in the same scope?
 /// </summary>
 public bool HasSameScope(NetTypeDefinition type)
 {
     return (DeclaringType != null) && (DeclaringType.HasSameScope(type));
 }
Example #40
0
 /// <summary>
 /// Register the given type in the type map.
 /// </summary>
 protected virtual void RegisterType(TargetFramework target, ClassFile classFile, NetTypeDefinition typeDef)
 {
     target.TypeNameMap.Add(classFile.ClassName, typeDef);
 }
Example #41
0
        /// <summary>
        /// Create a type definition for the given class file and all inner classes.
        /// </summary>
        public override void CreateType(NetTypeDefinition declaringType, NetModule module, TargetFramework target)
        {
            if (declaringType != null)
                throw new ArgumentException("Declaring type should be null");
            docClass = target.GetXmlClass(cf);

            var fullName = GetFullName();
            var dotIndex = fullName.LastIndexOf('.');
            var ns = (dotIndex > 0) ? ConvertNamespace(fullName, dotIndex) : String.Empty;
            var name = (dotIndex > 0) ? NameConverter.UpperCamelCase(fullName.Substring(dotIndex + 1)) : fullName;

            name = CreateTypeName(null, cf, name, ns);

            typeDef = new NetTypeDefinition(cf, target, module.Scope);
            typeDef.Name = name;
            typeDef.Namespace = ns;
            typeDef.OriginalJavaClassName = cf.ClassName;
            typeDef.Attributes = GetAttributes(cf, cf.Fields.Any());
            typeDef.IgnoreGenericArguments = !AddGenericParameters;
            typeDef.Description = (docClass != null) ? docClass.Description : null;
            module.Types.Add(typeDef);

            // Prepare generics
            CreateGenericParameters(cf, typeDef);

            // Add mapping
            var finalFullName = string.IsNullOrEmpty(ns) ? name : ns + "." + name;
            RegisterType(target, cf, typeDef);
            CreateNestedTypes(cf, typeDef, finalFullName, module, target);
        }
Example #42
0
 /// <summary>
 /// Adds the given nested type to my type declaration.
 /// </summary>
 protected internal override void AddNestedType(NetTypeDefinition nestedType, string namePrefix, NetModule module, ref string fullNestedTypeName)
 {
     if (typeDef.IsInterface)
     {
         // Add to my parent
         parent.AddNestedType(nestedType, cf.Name + "_" + namePrefix, module, ref fullNestedTypeName);
     }
     else
     {
         typeDef.NestedTypes.Add(nestedType);
     }
 }
Example #43
0
 /// <summary>
 /// Create a property builder for this type builder.
 /// </summary>
 protected override PropertyBuilder CreatePropertyBuilder(NetTypeDefinition typeDef)
 {
     return new UriPropertyBuilder(typeDef, this);
 }
Example #44
0
        /// <summary>
        /// Create type attributes
        /// </summary>
        private static MethodAttributes GetAttributes(NetTypeDefinition declaringType, NetMethodDefinition method, MethodDefinition javaMethod, string methodName, TypeNameMap typeNameMap)
        {
            var result = (MethodAttributes) 0;
            var isStatic = javaMethod.IsStatic;

            if (javaMethod.IsPublic) result |= MethodAttributes.Public;
            else if (javaMethod.IsProtected) result |= MethodAttributes.FamORAssem;
            else if (javaMethod.IsPrivate) result |= MethodAttributes.Private;
            else if (javaMethod.IsPackagePrivate) result |= MethodAttributes.Assembly;

            if (isStatic) result |= MethodAttributes.Static;
            if (javaMethod.IsAbstract) result |= MethodAttributes.Abstract;
            if (declaringType.IsInterface) result |= MethodAttributes.Abstract;

            if ((!javaMethod.IsFinal) && !isStatic && (methodName != ".ctor") && (!declaringType.IsStruct))
            {
                result |= MethodAttributes.Virtual;
            }
            else
            {
                result |= MethodAttributes.Final;
            }

            if (methodName == ".cctor")
            {
                result |= MethodAttributes.Static;
            }

            if (declaringType.IsSealed)
            {
                result &= ~MethodAttributes.Virtual;
            }

            return result;
        }
Example #45
0
 /// <summary>
 /// Adds the given nested type to my type declaration.
 /// </summary>
 protected internal override void AddNestedType(NetTypeDefinition nestedType, string namePrefix, NetModule module, ref string fullNestedTypeName)
 {
     TypeDefinition.NestedTypes.Add(nestedType);
 }
Example #46
0
 /// <summary>
 /// Default ctor
 /// </summary>
 public PropertyBuilder(NetTypeDefinition typeDef, TypeBuilder declaringTypeBuilder)
 {
     this.typeDef = typeDef;
     this.declaringTypeBuilder = declaringTypeBuilder;
 }
Example #47
0
        /// <summary>
        /// Create wrapper for given jar file
        /// </summary>
        private void CreateAssembly(JarFile jf, string folder)
        {
            // Create java type wrappers
            var module = new NetModule(jf.Scope);

            var classTypeBuilders = jf.ClassNames.SelectMany(n => StandardTypeBuilder.Create(jf.LoadClass(n), target));

            var typeBuilders = classTypeBuilders.OrderBy(x => x.Priority).ToList();
            typeBuilders.ForEach(x => x.CreateType(null, module, target));

            // Implement and finalize types
            Implement(typeBuilders, target);

            var assemblyAttributes = new List<NetCustomAttribute>();
            if (!importAsStubs)
            {
                // Import code
                var attrType = new NetTypeDefinition(ClassFile.Empty, target, AttributeConstants.Dot42Scope)
                {
                    Name = AttributeConstants.JavaCodeAttributeName,
                    Namespace = AttributeConstants.Dot42AttributeNamespace
                };
                var hash = JarReferenceHash.ComputeJarReferenceHash(jarFilePath);
                var attr = new NetCustomAttribute(attrType, hash);
                assemblyAttributes.Add(attr);
            }

            // Save
            CodeGenerator.Generate(folder, module.Types, assemblyAttributes, target, this, target);
        }
Example #48
0
 /// <summary>
 /// Gets the root part of the namespace.
 /// </summary>
 public string GetNamespaceRoot(NetTypeDefinition type)
 {
     var ns = type.Namespace;
     if (!string.IsNullOrEmpty(ns))
         return ns;
     return PossibleRoots[0];
 }
Example #49
0
 /// <summary>
 /// Try to resolve the given NET name.
 /// </summary>
 void ITypeMapResolver.TryResolve(Type netType, TypeNameMap typeNameMap)
 {
     // Auto create a typedef.
     var typeDef = new NetTypeDefinition(ClassFile.Empty, target, AttributeConstants.Dot42Scope) { Namespace = netType.Namespace, Name = netType.Name};
     typeNameMap.Add(netType.FullName, typeDef);
 }
Example #50
0
 /// <summary>
 /// Fix base type relations.
 /// </summary>
 protected override void FixBaseType(NetTypeDefinition typeDef, TargetFramework target)
 {
     if ((typeDef.BaseType != null) && (typeDef.BaseType.FullName == "Java.Lang.Number"))
         typeDef.BaseType = null;
     base.FixBaseType(typeDef, target);
 }
Example #51
0
 /// <summary>
 /// Gets the root part of the namespace.
 /// The result of this method is used for the name of the source file in which the type is placed.
 /// </summary>
 string ICodeGeneratorContext.GetNamespaceRoot(NetTypeDefinition type)
 {
     return libraryName;
 }
 /// <summary>
 /// Create a property builder for this type builder.
 /// </summary>
 protected override PropertyBuilder CreatePropertyBuilder(NetTypeDefinition typeDef)
 {
     return new JavaLangConcurrentAtomicAtomicIntegerPropertyBuilder(typeDef, this);
 }
 /// <summary>
 /// Default ctor
 /// </summary>
 public JavaLangConcurrentAtomicAtomicIntegerPropertyBuilder(NetTypeDefinition typeDef, TypeBuilder declaringTypeBuilder)
     : base(typeDef, declaringTypeBuilder)
 {
 }
 protected override string CreateTypeName(NetTypeDefinition declaringType, ClassFile classFile, string name, string @namespace)
 {
     return base.CreateTypeName(declaringType, classFile, name, @namespace) + "Constants";
 }
Example #55
0
 /// <summary>
 /// Adds the given nested type to my type declaration.
 /// </summary>
 protected internal override void AddNestedType(NetTypeDefinition nestedType, string namePrefix, NetModule module, ref string fullNestedTypeName)
 {
     if (TypeDefinition.IsInterface)
     {
         // Add to namespace instead (alter name to avoid duplicates)
         nestedType.Name = typeDef.Name + "_" + namePrefix + nestedType.Name;
         nestedType.Namespace = typeDef.Namespace;
         nestedType.DeclaringType = null;
         fullNestedTypeName = nestedType.FullName;
         module.Types.Add(nestedType);
     }
     else
     {
         TypeDefinition.NestedTypes.Add(nestedType);
     }
 }
 /// <summary>
 /// Create a property builder for this type builder.
 /// </summary>
 protected override PropertyBuilder CreatePropertyBuilder(NetTypeDefinition typeDef)
 {
     return new SkipSpecifiedPropertyBuilder (typeDef, this, "setTitle", "getTitle");
 }
Example #57
0
        /// <summary>
        /// Create the field in the given type
        /// </summary>
        public void Create(NetTypeDefinition declaringType, TargetFramework target)
        {
            // Do not add private fields
            if ((javaField.AccessFlags & FieldAccessFlags.Private) != 0)
                return;

            // Find documentation
            var docClass = declaringTypeBuilder.Documentation;
            docField = (docClass != null) ? docClass.Fields.FirstOrDefault(x => x.Name == javaField.Name) : null;

            //var fieldType = declaringType.IsEnum ? target.TypeNameMap.GetByType(typeof(int)) : javaField.Signature.Resolve(target, declaringTypeBuilder);
            NetTypeReference fieldType;
            if (!javaField.Signature.TryResolve(target, declaringTypeBuilder, false, out fieldType))
                return;

            //var fieldTypeIsValueType = declaringType.IsEnum ? true : javaField.FieldType.
            var name = declaringTypeBuilder.GetFieldName(javaField);
            field = new NetFieldDefinition();
            field.Name = name;
            field.OriginalJavaName = javaField.Name;
            field.FieldType = fieldType;
            field.Attributes = GetAttributes(javaField, false);
            field.Description = (docField != null) ? docField.Description : null;
            declaringType.Fields.Add(field);
        }
Example #58
0
 /// <summary>
 /// Add the given mapping.
 /// </summary>
 /// <remarks>
 /// External jars might include some standard classes which we also
 /// have included in our libraries. Since the classnames can be taken
 /// as unique (for example org.xmlpull.v1.XmlSerializer), we should
 /// be able to safely overwrite the first addition of the class.
 /// The MS .net compiler will use the one in the external jar, not the
 /// one in the dot42 library. So that also suggests we need to ignore
 /// the first addition (Peter Laudy).
 /// </remarks>
 public void Add(string javaClassName, NetTypeDefinition clrType)
 {
     map[javaClassName] = clrType;
 }
Example #59
0
 /// <summary>
 /// Default ctor
 /// </summary>
 public UriPropertyBuilder(NetTypeDefinition typeDef, TypeBuilder declaringTypeBuilder)
     : base(typeDef, declaringTypeBuilder)
 {
 }
 protected override PropertyBuilder CreatePropertyBuilder(NetTypeDefinition typeDef)
 {
     return new SkipSpecifiedPropertyBuilder(typeDef, this, m=>m.OriginalJavaName.StartsWith("get")?(bool?)false:null);
 }