XamlCompilerTaskExecutor.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. using Avalonia.Markup.Xaml.XamlIl.CompilerExtensions;
  8. using Microsoft.Build.Framework;
  9. using Mono.Cecil;
  10. using Avalonia.Utilities;
  11. using Mono.Cecil.Cil;
  12. using Mono.Cecil.Rocks;
  13. using XamlX;
  14. using XamlX.Ast;
  15. using XamlX.Parsers;
  16. using XamlX.Transform;
  17. using XamlX.TypeSystem;
  18. using FieldAttributes = Mono.Cecil.FieldAttributes;
  19. using MethodAttributes = Mono.Cecil.MethodAttributes;
  20. using TypeAttributes = Mono.Cecil.TypeAttributes;
  21. using XamlX.IL;
  22. namespace Avalonia.Build.Tasks
  23. {
  24. public static partial class XamlCompilerTaskExecutor
  25. {
  26. static bool CheckXamlName(IResource r) => r.Name.ToLowerInvariant().EndsWith(".xaml")
  27. || r.Name.ToLowerInvariant().EndsWith(".paml")
  28. || r.Name.ToLowerInvariant().EndsWith(".axaml");
  29. public class CompileResult
  30. {
  31. public bool Success { get; set; }
  32. public bool WrittenFile { get; }
  33. public CompileResult(bool success, bool writtenFile = false)
  34. {
  35. Success = success;
  36. WrittenFile = writtenFile;
  37. }
  38. }
  39. public static CompileResult Compile(IBuildEngine engine, string input, string[] references,
  40. string projectDirectory,
  41. string output, bool verifyIl, MessageImportance logImportance, string strongNameKey, bool patchCom,
  42. bool skipXamlCompilation)
  43. {
  44. var typeSystem = new CecilTypeSystem(references
  45. .Where(r => !r.ToLowerInvariant().EndsWith("avalonia.build.tasks.dll"))
  46. .Concat(new[] { input }), input);
  47. var asm = typeSystem.TargetAssemblyDefinition;
  48. if (!skipXamlCompilation)
  49. {
  50. var compileRes = CompileCore(engine, typeSystem, projectDirectory, verifyIl, logImportance);
  51. if (compileRes == null && !patchCom)
  52. return new CompileResult(true);
  53. if (compileRes == false)
  54. return new CompileResult(false);
  55. }
  56. if (patchCom)
  57. ComInteropHelper.PatchAssembly(asm, typeSystem);
  58. var writerParameters = new WriterParameters { WriteSymbols = asm.MainModule.HasSymbols };
  59. if (!string.IsNullOrWhiteSpace(strongNameKey))
  60. writerParameters.StrongNameKeyBlob = File.ReadAllBytes(strongNameKey);
  61. asm.Write(output, writerParameters);
  62. return new CompileResult(true, true);
  63. }
  64. static bool? CompileCore(IBuildEngine engine, CecilTypeSystem typeSystem,
  65. string projectDirectory, bool verifyIl,
  66. MessageImportance logImportance)
  67. {
  68. var asm = typeSystem.TargetAssemblyDefinition;
  69. var emres = new EmbeddedResources(asm);
  70. var avares = new AvaloniaResources(asm, projectDirectory);
  71. if (avares.Resources.Count(CheckXamlName) == 0 && emres.Resources.Count(CheckXamlName) == 0)
  72. // Nothing to do
  73. return null;
  74. var clrPropertiesDef = new TypeDefinition("CompiledAvaloniaXaml", "XamlIlHelpers",
  75. TypeAttributes.Class, asm.MainModule.TypeSystem.Object);
  76. asm.MainModule.Types.Add(clrPropertiesDef);
  77. var indexerAccessorClosure = new TypeDefinition("CompiledAvaloniaXaml", "!IndexerAccessorFactoryClosure",
  78. TypeAttributes.Class, asm.MainModule.TypeSystem.Object);
  79. asm.MainModule.Types.Add(indexerAccessorClosure);
  80. var (xamlLanguage , emitConfig) = AvaloniaXamlIlLanguage.Configure(typeSystem);
  81. var compilerConfig = new AvaloniaXamlIlCompilerConfiguration(typeSystem,
  82. typeSystem.TargetAssembly,
  83. xamlLanguage,
  84. XamlXmlnsMappings.Resolve(typeSystem, xamlLanguage),
  85. AvaloniaXamlIlLanguage.CustomValueConverter,
  86. new XamlIlClrPropertyInfoEmitter(typeSystem.CreateTypeBuilder(clrPropertiesDef)),
  87. new XamlIlPropertyInfoAccessorFactoryEmitter(typeSystem.CreateTypeBuilder(indexerAccessorClosure)),
  88. new DeterministicIdGenerator());
  89. var contextDef = new TypeDefinition("CompiledAvaloniaXaml", "XamlIlContext",
  90. TypeAttributes.Class, asm.MainModule.TypeSystem.Object);
  91. asm.MainModule.Types.Add(contextDef);
  92. var contextClass = XamlILContextDefinition.GenerateContextClass(typeSystem.CreateTypeBuilder(contextDef), typeSystem,
  93. xamlLanguage, emitConfig);
  94. var compiler = new AvaloniaXamlIlCompiler(compilerConfig, emitConfig, contextClass) { EnableIlVerification = verifyIl };
  95. var editorBrowsableAttribute = typeSystem
  96. .GetTypeReference(typeSystem.FindType("System.ComponentModel.EditorBrowsableAttribute"))
  97. .Resolve();
  98. var editorBrowsableCtor =
  99. asm.MainModule.ImportReference(editorBrowsableAttribute.GetConstructors()
  100. .First(c => c.Parameters.Count == 1));
  101. var runtimeHelpers = typeSystem.GetType("Avalonia.Markup.Xaml.XamlIl.Runtime.XamlIlRuntimeHelpers");
  102. var createRootServiceProviderMethod = asm.MainModule.ImportReference(
  103. typeSystem.GetTypeReference(runtimeHelpers).Resolve().Methods
  104. .First(x => x.Name == "CreateRootServiceProviderV2"));
  105. var loaderDispatcherDef = new TypeDefinition("CompiledAvaloniaXaml", "!XamlLoader",
  106. TypeAttributes.Class, asm.MainModule.TypeSystem.Object);
  107. loaderDispatcherDef.CustomAttributes.Add(new CustomAttribute(editorBrowsableCtor)
  108. {
  109. ConstructorArguments = {new CustomAttributeArgument(editorBrowsableCtor.Parameters[0].ParameterType, 1)}
  110. });
  111. var loaderDispatcherMethod = new MethodDefinition("TryLoad",
  112. MethodAttributes.Static | MethodAttributes.Public,
  113. asm.MainModule.TypeSystem.Object)
  114. {
  115. Parameters = {new ParameterDefinition(asm.MainModule.TypeSystem.String)}
  116. };
  117. loaderDispatcherDef.Methods.Add(loaderDispatcherMethod);
  118. asm.MainModule.Types.Add(loaderDispatcherDef);
  119. var stringEquals = asm.MainModule.ImportReference(asm.MainModule.TypeSystem.String.Resolve().Methods.First(
  120. m =>
  121. m.IsStatic && m.Name == "Equals" && m.Parameters.Count == 2 &&
  122. m.ReturnType.FullName == "System.Boolean"
  123. && m.Parameters[0].ParameterType.FullName == "System.String"
  124. && m.Parameters[1].ParameterType.FullName == "System.String"));
  125. bool CompileGroup(IResourceGroup group)
  126. {
  127. var typeDef = new TypeDefinition("CompiledAvaloniaXaml", "!"+ group.Name,
  128. TypeAttributes.Class, asm.MainModule.TypeSystem.Object);
  129. typeDef.CustomAttributes.Add(new CustomAttribute(editorBrowsableCtor)
  130. {
  131. ConstructorArguments = {new CustomAttributeArgument(editorBrowsableCtor.Parameters[0].ParameterType, 1)}
  132. });
  133. asm.MainModule.Types.Add(typeDef);
  134. var builder = typeSystem.CreateTypeBuilder(typeDef);
  135. foreach (var res in group.Resources.Where(CheckXamlName).OrderBy(x=>x.FilePath.ToLowerInvariant()))
  136. {
  137. try
  138. {
  139. engine.LogMessage($"XAMLIL: {res.Name} -> {res.Uri}", logImportance);
  140. // StreamReader is needed here to handle BOM
  141. var xaml = new StreamReader(new MemoryStream(res.FileContents)).ReadToEnd();
  142. var parsed = XDocumentXamlParser.Parse(xaml);
  143. var initialRoot = (XamlAstObjectNode)parsed.Root;
  144. var precompileDirective = initialRoot.Children.OfType<XamlAstXmlDirective>()
  145. .FirstOrDefault(d => d.Namespace == XamlNamespaces.Xaml2006 && d.Name == "Precompile");
  146. if (precompileDirective != null)
  147. {
  148. var precompileText = (precompileDirective.Values[0] as XamlAstTextNode)?.Text.Trim()
  149. .ToLowerInvariant();
  150. if (precompileText == "false")
  151. continue;
  152. if (precompileText != "true")
  153. throw new XamlParseException("Invalid value for x:Precompile", precompileDirective);
  154. }
  155. var classDirective = initialRoot.Children.OfType<XamlAstXmlDirective>()
  156. .FirstOrDefault(d => d.Namespace == XamlNamespaces.Xaml2006 && d.Name == "Class");
  157. IXamlType classType = null;
  158. if (classDirective != null)
  159. {
  160. if (classDirective.Values.Count != 1 || !(classDirective.Values[0] is XamlAstTextNode tn))
  161. throw new XamlParseException("x:Class should have a string value", classDirective);
  162. classType = typeSystem.TargetAssembly.FindType(tn.Text);
  163. if (classType == null)
  164. throw new XamlParseException($"Unable to find type `{tn.Text}`", classDirective);
  165. compiler.OverrideRootType(parsed,
  166. new XamlAstClrTypeReference(classDirective, classType, false));
  167. initialRoot.Children.Remove(classDirective);
  168. }
  169. compiler.Transform(parsed);
  170. var populateName = classType == null ? "Populate:" + res.Name : "!XamlIlPopulate";
  171. var buildName = classType == null ? "Build:" + res.Name : null;
  172. var classTypeDefinition =
  173. classType == null ? null : typeSystem.GetTypeReference(classType).Resolve();
  174. var populateBuilder = classTypeDefinition == null ?
  175. builder :
  176. typeSystem.CreateTypeBuilder(classTypeDefinition);
  177. compiler.Compile(parsed, contextClass,
  178. compiler.DefinePopulateMethod(populateBuilder, parsed, populateName,
  179. classTypeDefinition == null),
  180. buildName == null ? null : compiler.DefineBuildMethod(builder, parsed, buildName, true),
  181. builder.DefineSubType(compilerConfig.WellKnownTypes.Object, "NamespaceInfo:" + res.Name,
  182. true),
  183. (closureName, closureBaseType) =>
  184. populateBuilder.DefineSubType(closureBaseType, closureName, false),
  185. res.Uri, res
  186. );
  187. if (classTypeDefinition != null)
  188. {
  189. var compiledPopulateMethod = typeSystem.GetTypeReference(populateBuilder).Resolve()
  190. .Methods.First(m => m.Name == populateName);
  191. var designLoaderFieldType = typeSystem
  192. .GetType("System.Action`1")
  193. .MakeGenericType(typeSystem.GetType("System.Object"));
  194. var designLoaderFieldTypeReference = (GenericInstanceType)typeSystem.GetTypeReference(designLoaderFieldType);
  195. designLoaderFieldTypeReference.GenericArguments[0] =
  196. asm.MainModule.ImportReference(designLoaderFieldTypeReference.GenericArguments[0]);
  197. designLoaderFieldTypeReference = (GenericInstanceType)
  198. asm.MainModule.ImportReference(designLoaderFieldTypeReference);
  199. var designLoaderLoad =
  200. typeSystem.GetMethodReference(
  201. designLoaderFieldType.Methods.First(m => m.Name == "Invoke"));
  202. designLoaderLoad =
  203. asm.MainModule.ImportReference(designLoaderLoad);
  204. designLoaderLoad.DeclaringType = designLoaderFieldTypeReference;
  205. var designLoaderField = new FieldDefinition("!XamlIlPopulateOverride",
  206. FieldAttributes.Static | FieldAttributes.Private, designLoaderFieldTypeReference);
  207. classTypeDefinition.Fields.Add(designLoaderField);
  208. const string TrampolineName = "!XamlIlPopulateTrampoline";
  209. var trampoline = new MethodDefinition(TrampolineName,
  210. MethodAttributes.Static | MethodAttributes.Private, asm.MainModule.TypeSystem.Void);
  211. trampoline.Parameters.Add(new ParameterDefinition(classTypeDefinition));
  212. classTypeDefinition.Methods.Add(trampoline);
  213. var regularStart = Instruction.Create(OpCodes.Call, createRootServiceProviderMethod);
  214. trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Ldsfld, designLoaderField));
  215. trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Brfalse, regularStart));
  216. trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Ldsfld, designLoaderField));
  217. trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
  218. trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Call, designLoaderLoad));
  219. trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
  220. trampoline.Body.Instructions.Add(regularStart);
  221. trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
  222. trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Call, compiledPopulateMethod));
  223. trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
  224. CopyDebugDocument(trampoline, compiledPopulateMethod);
  225. var foundXamlLoader = false;
  226. // Find AvaloniaXamlLoader.Load(this) and replace it with !XamlIlPopulateTrampoline(this)
  227. foreach (var method in classTypeDefinition.Methods
  228. .Where(m => !m.Attributes.HasFlag(MethodAttributes.Static)))
  229. {
  230. var i = method.Body.Instructions;
  231. for (var c = 1; c < i.Count; c++)
  232. {
  233. if (i[c].OpCode == OpCodes.Call)
  234. {
  235. var op = i[c].Operand as MethodReference;
  236. // TODO: Throw an error
  237. // This usually happens when same XAML resource was added twice for some weird reason
  238. // We currently support it for dual-named default theme resource
  239. if (op != null
  240. && op.Name == TrampolineName)
  241. {
  242. foundXamlLoader = true;
  243. break;
  244. }
  245. if (op != null
  246. && op.Name == "Load"
  247. && op.Parameters.Count == 1
  248. && op.Parameters[0].ParameterType.FullName == "System.Object"
  249. && op.DeclaringType.FullName == "Avalonia.Markup.Xaml.AvaloniaXamlLoader")
  250. {
  251. if (MatchThisCall(i, c - 1))
  252. {
  253. i[c].Operand = trampoline;
  254. foundXamlLoader = true;
  255. }
  256. }
  257. }
  258. }
  259. }
  260. if (!foundXamlLoader)
  261. {
  262. var ctors = classTypeDefinition.GetConstructors()
  263. .Where(c => !c.IsStatic).ToList();
  264. // We can inject xaml loader into default constructor
  265. if (ctors.Count == 1 && ctors[0].Body.Instructions.Count(o=>o.OpCode != OpCodes.Nop) == 3)
  266. {
  267. var i = ctors[0].Body.Instructions;
  268. var retIdx = i.IndexOf(i.Last(x => x.OpCode == OpCodes.Ret));
  269. i.Insert(retIdx, Instruction.Create(OpCodes.Call, trampoline));
  270. i.Insert(retIdx, Instruction.Create(OpCodes.Ldarg_0));
  271. }
  272. else
  273. {
  274. throw new InvalidProgramException(
  275. $"No call to AvaloniaXamlLoader.Load(this) call found anywhere in the type {classType.FullName} and type seems to have custom constructors.");
  276. }
  277. }
  278. }
  279. if (buildName != null || classTypeDefinition != null)
  280. {
  281. var compiledBuildMethod = buildName == null ?
  282. null :
  283. typeSystem.GetTypeReference(builder).Resolve()
  284. .Methods.First(m => m.Name == buildName);
  285. var parameterlessConstructor = compiledBuildMethod != null ?
  286. null :
  287. classTypeDefinition.GetConstructors().FirstOrDefault(c =>
  288. c.IsPublic && !c.IsStatic && !c.HasParameters);
  289. if (compiledBuildMethod != null || parameterlessConstructor != null)
  290. {
  291. var i = loaderDispatcherMethod.Body.Instructions;
  292. var nop = Instruction.Create(OpCodes.Nop);
  293. i.Add(Instruction.Create(OpCodes.Ldarg_0));
  294. i.Add(Instruction.Create(OpCodes.Ldstr, res.Uri));
  295. i.Add(Instruction.Create(OpCodes.Call, stringEquals));
  296. i.Add(Instruction.Create(OpCodes.Brfalse, nop));
  297. if (parameterlessConstructor != null)
  298. i.Add(Instruction.Create(OpCodes.Newobj, parameterlessConstructor));
  299. else
  300. {
  301. i.Add(Instruction.Create(OpCodes.Call, createRootServiceProviderMethod));
  302. i.Add(Instruction.Create(OpCodes.Call, compiledBuildMethod));
  303. }
  304. i.Add(Instruction.Create(OpCodes.Ret));
  305. i.Add(nop);
  306. }
  307. }
  308. }
  309. catch (Exception e)
  310. {
  311. int lineNumber = 0, linePosition = 0;
  312. if (e is XamlParseException xe)
  313. {
  314. lineNumber = xe.LineNumber;
  315. linePosition = xe.LinePosition;
  316. }
  317. engine.LogErrorEvent(new BuildErrorEventArgs("Avalonia", "XAMLIL", res.FilePath,
  318. lineNumber, linePosition, lineNumber, linePosition,
  319. e.Message, "", "Avalonia"));
  320. return false;
  321. }
  322. res.Remove();
  323. }
  324. // Technically that's a hack, but it fixes corert incompatibility caused by deterministic builds
  325. int dupeCounter = 1;
  326. foreach (var grp in typeDef.NestedTypes.GroupBy(x => x.Name))
  327. {
  328. if (grp.Count() > 1)
  329. {
  330. foreach (var dupe in grp)
  331. dupe.Name += "_dup" + dupeCounter++;
  332. }
  333. }
  334. return true;
  335. }
  336. if (emres.Resources.Count(CheckXamlName) != 0)
  337. if (!CompileGroup(emres))
  338. return false;
  339. if (avares.Resources.Count(CheckXamlName) != 0)
  340. {
  341. if (!CompileGroup(avares))
  342. return false;
  343. avares.Save();
  344. }
  345. loaderDispatcherMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldnull));
  346. loaderDispatcherMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
  347. return true;
  348. }
  349. }
  350. }