예제 #1
0
        protected List <GenBase> ParseApiDefinition(string xml)
        {
            var doc  = XDocument.Parse(xml);
            var gens = XmlApiImporter.Parse(doc, options);

            foreach (var gen in gens)
            {
                options.SymbolTable.AddType(gen);
            }

            foreach (var gen in gens)
            {
                gen.Validate(options, new GenericParameterDefinitionList(), generator.Context);
            }

            foreach (var gen in gens)
            {
                gen.FillProperties();
            }

            foreach (var gen in gens)
            {
                gen.FixupMethodOverrides(options);
            }

            return(gens);
        }
예제 #2
0
        public void IgnoreUserObfuscatedTypes()
        {
            var xml = XDocument.Parse(@"
				<api>
					<package name='com.example.test' jni-name='com/example/test'>
						<class name='MyClass' visibility='public' obfuscated='true' />
						<interface name='MyInterface' visibility='public' obfuscated='true' />
					</package>
				</api>"                );

            var gens = XmlApiImporter.Parse(xml, opt);

            // None of these should be parsed because the user has said they are obfuscated
            Assert.AreEqual(0, gens.Count);
        }
예제 #3
0
        public void IgnoreTypesWithInvalidNames()
        {
            var xml = XDocument.Parse(@"
				<api>
					<package name='com.example.test' jni-name='com/example/test'>
						<class name='' visibility='public' />
						<class name='Document.' visibility='public' />
						<interface name='' visibility='public' />
						<interface name='Document.' visibility='public' />
					</package>
				</api>"                );

            var gens = XmlApiImporter.Parse(xml, opt);

            // None of these should be parsed because they have invalid names
            Assert.AreEqual(0, gens.Count);
        }
예제 #4
0
        public void IgnoreKotlinInternalMembers()
        {
            var xml = XDocument.Parse(@"
				<api>
					<package name='com.example.test' jni-name='com/example/test'>
						<class name='Test' visibility='public'>
							<constructor name='Test' visibility='kotlin-internal' />
							<method name='DoStuff' visibility='kotlin-internal' />
							<field name='MyField' visibility='kotlin-internal' />
						</class>
					</package>
				</api>"                );

            var gens  = XmlApiImporter.Parse(xml, opt);
            var klass = gens.Single();

            Assert.AreEqual(0, klass.Fields.Count);
            Assert.AreEqual(0, klass.Methods.Count);
        }
예제 #5
0
        static void Run(CodeGeneratorOptions options, DirectoryAssemblyResolver resolver)
        {
            string assemblyQN              = options.AssemblyQualifiedName;
            string api_level               = options.ApiLevel;
            int    product_version         = options.ProductVersion;
            bool   preserve_enums          = options.PreserveEnums;
            string csdir                   = options.ManagedCallableWrapperSourceOutputDirectory ?? "cs";
            string javadir                 = "java";
            string enumdir                 = options.EnumOutputDirectory ?? "enum";
            string enum_metadata           = options.EnumMetadataOutputFile ?? "enummetadata";
            var    references              = options.AssemblyReferences;
            string enum_fields_map         = options.EnumFieldsMapFile;
            string enum_flags              = options.EnumFlagsFile;
            string enum_methods_map        = options.EnumMethodsMapFile;
            var    fixups                  = options.FixupFiles;
            var    annotations_zips        = options.AnnotationsZipFiles;
            string filename                = options.ApiDescriptionFile;
            string mapping_file            = options.MappingReportFile;
            bool   only_xml_adjuster       = options.OnlyRunApiXmlAdjuster;
            string api_xml_adjuster_output = options.ApiXmlAdjusterOutput;
            var    apiSource               = "";
            var    opt = new CodeGenerationOptions()
            {
                ApiXmlFile                     = options.ApiDescriptionFile,
                CodeGenerationTarget           = options.CodeGenerationTarget,
                UseGlobal                      = options.GlobalTypeNames,
                IgnoreNonPublicType            = true,
                UseShortFileNames              = options.UseShortFileNames,
                ProductVersion                 = options.ProductVersion,
                SupportInterfaceConstants      = options.SupportInterfaceConstants,
                SupportDefaultInterfaceMethods = options.SupportDefaultInterfaceMethods,
                SupportNestedInterfaceTypes    = options.SupportNestedInterfaceTypes,
                SupportNullableReferenceTypes  = options.SupportNullableReferenceTypes,
            };
            var resolverCache = new TypeDefinitionCache();

            // Load reference libraries

            foreach (var lib in options.LibraryPaths)
            {
                resolver.SearchDirectories.Add(lib);
            }
            foreach (var reference in references)
            {
                resolver.SearchDirectories.Add(Path.GetDirectoryName(reference));
            }

            // Figure out if this is class-parse
            string apiXmlFile    = filename;
            string apiSourceAttr = null;

            using (var xr = XmlReader.Create(filename, new XmlReaderSettings {
                XmlResolver = null
            })) {
                xr.MoveToContent();
                apiSourceAttr = xr.GetAttribute("api-source");
            }

            var is_classparse = apiSourceAttr == "class-parse";

            // Resolve types using Java.Interop.Tools.JavaTypeSystem
            if (is_classparse && !options.UseLegacyJavaResolver)
            {
                var output_xml = api_xml_adjuster_output ?? Path.Combine(Path.GetDirectoryName(filename), Path.GetFileName(filename) + ".adjusted");
                JavaTypeResolutionFixups.Fixup(filename, output_xml, resolver, references.Distinct().ToArray());

                if (only_xml_adjuster)
                {
                    return;
                }

                // Use this output for future steps
                filename      = output_xml;
                apiXmlFile    = filename;
                is_classparse = false;
            }

            // We don't use shallow referenced types with class-parse because the Adjuster process
            // enumerates every ctor/method/property/field to build its model, so we will need
            // every type to be fully populated.
            opt.UseShallowReferencedTypes = !is_classparse;

            foreach (var reference in references.Distinct())
            {
                try {
                    Report.Verbose(0, "resolving assembly {0}.", reference);
                    var assembly = resolver.Load(reference);
                    foreach (var md in assembly.Modules)
                    {
                        foreach (var td in md.Types)
                        {
                            // FIXME: at some stage we want to import generic types.
                            // For now generator fails to load generic types that have conflicting type e.g.
                            // AdapterView`1 and AdapterView cannot co-exist.
                            // It is mostly because generator primarily targets jar (no real generics land).
                            var nonGenericOverload = td.HasGenericParameters
                                                                ? md.GetType(td.FullName.Substring(0, td.FullName.IndexOf('`')))
                                                                : null;
                            if (BindSameType(td, nonGenericOverload, resolverCache))
                            {
                                continue;
                            }
                            ProcessReferencedType(td, opt);
                        }
                    }
                } catch (Exception ex) {
                    Report.LogCodedWarning(0, Report.WarningAssemblyParseFailure, ex, reference, ex.Message);
                }
            }

            // For class-parse API description, transform it to jar2xml style.
            // Resolve types using ApiXmlAdjuster
            if (is_classparse && options.UseLegacyJavaResolver)
            {
                apiXmlFile = api_xml_adjuster_output ?? Path.Combine(Path.GetDirectoryName(filename), Path.GetFileName(filename) + ".adjusted");
                new Adjuster().Process(filename, opt, opt.SymbolTable.AllRegisteredSymbols(opt).OfType <GenBase> ().ToArray(), apiXmlFile, Report.Verbosity ?? 0);
            }

            if (only_xml_adjuster)
            {
                return;
            }

            // load XML API definition with fixups.

            Dictionary <string, EnumMappings.EnumDescription> enums = null;

            EnumMappings enummap = null;

            if (enum_fields_map != null || enum_methods_map != null)
            {
                enummap = new EnumMappings(enumdir, enum_metadata, api_level, preserve_enums);
                enums   = enummap.Process(enum_fields_map, enum_flags, enum_methods_map);
                fixups.Add(enum_metadata);
            }

            // Load the API XML document
            var api = ApiXmlDocument.Load(apiXmlFile, api_level, product_version);

            if (api is null)
            {
                return;
            }

            // Apply metadata fixups
            foreach (var fixup in fixups)
            {
                api.ApplyFixupFile(fixup);
            }

            api.ApiDocument.Save(apiXmlFile + ".fixed");

            // Parse API XML
            var gens = XmlApiImporter.Parse(api.ApiDocument, opt);

            if (gens is null)
            {
                return;
            }

            apiSource = api.ApiSource;

            // disable interface default methods here, especially before validation.
            gens = gens.Where(g => !g.IsObfuscated && g.Visibility != "private").ToList();
            foreach (var gen in gens)
            {
                gen.StripNonBindables(opt);
                if (gen.IsGeneratable)
                {
                    AddTypeToTable(opt, gen);
                }
            }

            // Apply fixups
            KotlinFixups.Fixup(gens);

            Validate(gens, opt, new CodeGeneratorContext());

            foreach (var api_versions_xml in options.ApiVersionsXmlFiles)
            {
                ApiVersionsSupport.AssignApiLevels(gens, api_versions_xml);
            }

            foreach (GenBase gen in gens)
            {
                gen.FillProperties();
            }

            var cache = new AncestorDescendantCache(gens);

            foreach (var gen in gens)
            {
                gen.UpdateEnums(opt, cache);
            }

            foreach (GenBase gen in gens)
            {
                gen.FixupMethodOverrides(opt);
            }

            foreach (GenBase gen in gens)
            {
                gen.FixupExplicitImplementation();
            }

            SealedProtectedFixups.Fixup(gens);

            GenerateAnnotationAttributes(gens, annotations_zips);
            JavadocFixups.Fixup(gens, options);

            //SymbolTable.Dump ();

            GenerationInfo gen_info = new GenerationInfo(csdir, javadir, assemblyQN);

            opt.AssemblyName = gen_info.Assembly;

            if (mapping_file != null)
            {
                GenerateMappingReportFile(gens, mapping_file);
            }

            foreach (IGeneratable gen in gens)
            {
                if (gen.IsGeneratable)
                {
                    gen.Generate(opt, gen_info);
                }
            }

            new NamespaceMapping(gens).Generate(opt, gen_info);


            ClassGen.GenerateTypeRegistrations(opt, gen_info);
            ClassGen.GenerateEnumList(gen_info);

            // Create the .cs files for the enums
            var enumFiles = enums == null
                                ? null
                                : enummap.WriteEnumerations(enumdir, enums, FlattenNestedTypes(gens).ToArray(), opt);

            gen_info.GenerateLibraryProjectFile(options, enumFiles);
        }