|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.IO; |
| 4 | +using System.Linq; |
| 5 | + |
| 6 | +namespace Microsoft.Android.Sdk.TrimmableTypeMap; |
| 7 | + |
| 8 | +/// <summary> |
| 9 | +/// Core logic for generating trimmable TypeMap assemblies, JCW Java sources, and acw-map files. |
| 10 | +/// Extracted from the MSBuild task so it can be tested directly without MSBuild ceremony. |
| 11 | +/// </summary> |
| 12 | +public class TrimmableTypeMapGenerator |
| 13 | +{ |
| 14 | + readonly Action<string> log; |
| 15 | + |
| 16 | + public TrimmableTypeMapGenerator (Action<string> log) |
| 17 | + { |
| 18 | + if (log is null) { |
| 19 | + throw new ArgumentNullException (nameof (log)); |
| 20 | + } |
| 21 | + this.log = log; |
| 22 | + } |
| 23 | + |
| 24 | + /// <summary> |
| 25 | + /// Runs the full generation pipeline: scan assemblies, generate typemap |
| 26 | + /// assemblies, generate JCW Java sources, and write acw-map files. |
| 27 | + /// </summary> |
| 28 | + public TrimmableTypeMapResult Execute ( |
| 29 | + IReadOnlyList<string> assemblyPaths, |
| 30 | + string outputDirectory, |
| 31 | + string javaSourceOutputDirectory, |
| 32 | + Version systemRuntimeVersion, |
| 33 | + HashSet<string> frameworkAssemblyNames, |
| 34 | + string? acwMapOutputPath = null) |
| 35 | + { |
| 36 | + Directory.CreateDirectory (outputDirectory); |
| 37 | + Directory.CreateDirectory (javaSourceOutputDirectory); |
| 38 | + |
| 39 | + var allPeers = ScanAssemblies (assemblyPaths); |
| 40 | + |
| 41 | + if (allPeers.Count == 0) { |
| 42 | + log ("No Java peer types found, skipping typemap generation."); |
| 43 | + return new TrimmableTypeMapResult ([], []); |
| 44 | + } |
| 45 | + |
| 46 | + var generatedAssemblies = GenerateTypeMapAssemblies (allPeers, systemRuntimeVersion, assemblyPaths, outputDirectory); |
| 47 | + |
| 48 | + // Generate JCW .java files for user assemblies + framework Implementor types. |
| 49 | + // Framework binding types already have compiled JCWs in the SDK but their constructors |
| 50 | + // use the legacy TypeManager.Activate() JNI native which isn't available in the |
| 51 | + // trimmable runtime. Implementor types (View_OnClickListenerImplementor, etc.) are |
| 52 | + // in the mono.* Java package so we use the mono/ prefix to identify them. |
| 53 | + // We generate fresh JCWs that use Runtime.registerNatives() for activation. |
| 54 | + var jcwPeers = allPeers.Where (p => |
| 55 | + !frameworkAssemblyNames.Contains (p.AssemblyName) |
| 56 | + || p.JavaName.StartsWith ("mono/", StringComparison.Ordinal)).ToList (); |
| 57 | + log ($"Generating JCW files for {jcwPeers.Count} types (filtered from {allPeers.Count} total)."); |
| 58 | + var generatedJavaFiles = GenerateJcwJavaSources (jcwPeers, javaSourceOutputDirectory); |
| 59 | + |
| 60 | + // Write acw-map.txt so _ConvertCustomView and _UpdateAndroidResgen can resolve custom view names. |
| 61 | + if (!acwMapOutputPath.IsNullOrEmpty ()) { |
| 62 | + using var writer = new StreamWriter (acwMapOutputPath, append: false); |
| 63 | + AcwMapWriter.Write (writer, allPeers); |
| 64 | + log ($"Written acw-map.txt with {allPeers.Count} entries to {acwMapOutputPath}."); |
| 65 | + } |
| 66 | + |
| 67 | + return new TrimmableTypeMapResult (generatedAssemblies, generatedJavaFiles); |
| 68 | + } |
| 69 | + |
| 70 | + // Future optimization: the scanner currently scans all assemblies on every run. |
| 71 | + // For incremental builds, we could: |
| 72 | + // 1. Add a Scan(allPaths, changedPaths) overload that only produces JavaPeerInfo |
| 73 | + // for changed assemblies while still indexing all assemblies for cross-assembly |
| 74 | + // resolution (base types, interfaces, activation ctors). |
| 75 | + // 2. Cache scan results per assembly to skip PE I/O entirely for unchanged assemblies. |
| 76 | + // Both require profiling to determine if they meaningfully improve build times. |
| 77 | + List<JavaPeerInfo> ScanAssemblies (IReadOnlyList<string> assemblyPaths) |
| 78 | + { |
| 79 | + using var scanner = new JavaPeerScanner (); |
| 80 | + var peers = scanner.Scan (assemblyPaths); |
| 81 | + log ($"Scanned {assemblyPaths.Count} assemblies, found {peers.Count} Java peer types."); |
| 82 | + return peers; |
| 83 | + } |
| 84 | + |
| 85 | + List<string> GenerateTypeMapAssemblies (List<JavaPeerInfo> allPeers, Version systemRuntimeVersion, |
| 86 | + IReadOnlyList<string> assemblyPaths, string outputDir) |
| 87 | + { |
| 88 | + // Build a map from assembly name → source path for timestamp comparison |
| 89 | + var sourcePathByName = new Dictionary<string, string> (StringComparer.Ordinal); |
| 90 | + foreach (var path in assemblyPaths) { |
| 91 | + var name = Path.GetFileNameWithoutExtension (path); |
| 92 | + sourcePathByName [name] = path; |
| 93 | + } |
| 94 | + |
| 95 | + var peersByAssembly = allPeers |
| 96 | + .GroupBy (p => p.AssemblyName, StringComparer.Ordinal) |
| 97 | + .OrderBy (g => g.Key, StringComparer.Ordinal); |
| 98 | + |
| 99 | + var generatedAssemblies = new List<string> (); |
| 100 | + var perAssemblyNames = new List<string> (); |
| 101 | + var generator = new TypeMapAssemblyGenerator (systemRuntimeVersion); |
| 102 | + bool anyRegenerated = false; |
| 103 | + |
| 104 | + foreach (var group in peersByAssembly) { |
| 105 | + string assemblyName = $"_{group.Key}.TypeMap"; |
| 106 | + string outputPath = Path.Combine (outputDir, assemblyName + ".dll"); |
| 107 | + perAssemblyNames.Add (assemblyName); |
| 108 | + |
| 109 | + if (IsUpToDate (outputPath, group.Key, sourcePathByName)) { |
| 110 | + log ($" {assemblyName}: up to date, skipping"); |
| 111 | + generatedAssemblies.Add (outputPath); |
| 112 | + continue; |
| 113 | + } |
| 114 | + |
| 115 | + var peers = group.ToList (); |
| 116 | + generator.Generate (peers, outputPath, assemblyName); |
| 117 | + generatedAssemblies.Add (outputPath); |
| 118 | + anyRegenerated = true; |
| 119 | + |
| 120 | + log ($" {assemblyName}: {peers.Count} types"); |
| 121 | + } |
| 122 | + |
| 123 | + // Root assembly references all per-assembly typemaps — regenerate if any changed |
| 124 | + string rootOutputPath = Path.Combine (outputDir, "_Microsoft.Android.TypeMaps.dll"); |
| 125 | + if (anyRegenerated || !File.Exists (rootOutputPath)) { |
| 126 | + var rootGenerator = new RootTypeMapAssemblyGenerator (systemRuntimeVersion); |
| 127 | + rootGenerator.Generate (perAssemblyNames, rootOutputPath); |
| 128 | + log ($" Root: {perAssemblyNames.Count} per-assembly refs"); |
| 129 | + } else { |
| 130 | + log (" Root: up to date, skipping"); |
| 131 | + } |
| 132 | + generatedAssemblies.Add (rootOutputPath); |
| 133 | + |
| 134 | + log ($"Generated {generatedAssemblies.Count} typemap assemblies."); |
| 135 | + return generatedAssemblies; |
| 136 | + } |
| 137 | + |
| 138 | + internal static bool IsUpToDate (string outputPath, string assemblyName, Dictionary<string, string> sourcePathByName) |
| 139 | + { |
| 140 | + if (!File.Exists (outputPath)) { |
| 141 | + return false; |
| 142 | + } |
| 143 | + if (!sourcePathByName.TryGetValue (assemblyName, out var sourcePath)) { |
| 144 | + return false; |
| 145 | + } |
| 146 | + return File.GetLastWriteTimeUtc (outputPath) >= File.GetLastWriteTimeUtc (sourcePath); |
| 147 | + } |
| 148 | + |
| 149 | + List<string> GenerateJcwJavaSources (List<JavaPeerInfo> allPeers, string javaSourceOutputDirectory) |
| 150 | + { |
| 151 | + var jcwGenerator = new JcwJavaSourceGenerator (); |
| 152 | + var files = jcwGenerator.Generate (allPeers, javaSourceOutputDirectory); |
| 153 | + log ($"Generated {files.Count} JCW Java source files."); |
| 154 | + return files.ToList (); |
| 155 | + } |
| 156 | + |
| 157 | + public static Version ParseTargetFrameworkVersion (string tfv) |
| 158 | + { |
| 159 | + if (tfv.Length > 0 && (tfv [0] == 'v' || tfv [0] == 'V')) { |
| 160 | + tfv = tfv.Substring (1); |
| 161 | + } |
| 162 | + if (Version.TryParse (tfv, out var version)) { |
| 163 | + return version; |
| 164 | + } |
| 165 | + throw new ArgumentException ($"Cannot parse TargetFrameworkVersion '{tfv}' as a Version."); |
| 166 | + } |
| 167 | +} |
0 commit comments