ScriptDocument.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Linq.Expressions;
  9. using System.Reflection;
  10. using System.Runtime.CompilerServices;
  11. using System.Text.RegularExpressions;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using InABox.Core;
  15. using Microsoft.CodeAnalysis;
  16. using Microsoft.CodeAnalysis.CSharp;
  17. using Microsoft.CodeAnalysis.CSharp.Scripting;
  18. using Microsoft.CodeAnalysis.CSharp.Scripting.Hosting;
  19. using Microsoft.CodeAnalysis.Scripting;
  20. using Microsoft.CodeAnalysis.Scripting.Hosting;
  21. using RoslynPad.Roslyn;
  22. namespace InABox.Scripting;
  23. public class ScriptProperty : Dictionary<string, object>
  24. {
  25. public ScriptProperty(string name, object? value)
  26. {
  27. Name = name;
  28. Value = value;
  29. }
  30. public string Name { get; set; }
  31. public object? Value { get; set; }
  32. }
  33. public class CompileException : Exception
  34. {
  35. public CompileException() : base("Unable to compile script!") { }
  36. }
  37. public class ScriptDocument : INotifyPropertyChanged
  38. {
  39. private string _result;
  40. private string _text = "";
  41. private bool? compiled;
  42. private object? obj;
  43. private Type? type;
  44. static ScriptDocument()
  45. {
  46. DefaultAssemblies = new FluentList<Assembly>()
  47. .Add(typeof(object).Assembly)
  48. .Add(typeof(Regex).Assembly)
  49. .Add(typeof(List<>).Assembly)
  50. .Add(typeof(Enumerable).Assembly)
  51. .Add(typeof(Bitmap).Assembly)
  52. .Add(typeof(Expression).Assembly)
  53. .Add(typeof(DataTable).Assembly);
  54. }
  55. public ScriptDocument(string text)
  56. {
  57. if (Host == null)
  58. Initialize();
  59. Text = text;
  60. Properties = new List<ScriptProperty>();
  61. }
  62. private static Task<RoslynHost> _hostTask;
  63. private static RoslynHost? _host;
  64. public static RoslynHost Host => _host ?? InitializeHost().Result;
  65. public static FluentList<Assembly> DefaultAssemblies { get; }
  66. public Script<object> Script { get; private set; }
  67. public string Text
  68. {
  69. get => _text;
  70. set => SetProperty(ref _text, value);
  71. }
  72. public DocumentId Id { get; set; }
  73. public string Result
  74. {
  75. get => _result;
  76. private set => SetProperty(ref _result, value);
  77. }
  78. public List<Diagnostic> Diagnostics { get; } = new();
  79. private static MethodInfo HasSubmissionResult { get; } =
  80. typeof(Compilation).GetMethod(nameof(HasSubmissionResult), BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
  81. ?? throw new NullReferenceException();
  82. private static PrintOptions PrintOptions { get; } = new() { MemberDisplayFormat = MemberDisplayFormat.SeparateLines };
  83. public List<ScriptProperty> Properties { get; }
  84. public event PropertyChangedEventHandler? PropertyChanged;
  85. private static IEnumerable<MetadataReference> CompilationReferences;
  86. private static Task<RoslynHost> InitializeHost()
  87. {
  88. _hostTask ??= Task.Run(() =>
  89. {
  90. using var profiler = new Profiler(true, "ScriptDocument");
  91. var assemblies = new HashSet<Assembly>();
  92. var typelist = CoreUtils.TypeList(
  93. AppDomain.CurrentDomain.GetAssemblies(),
  94. x =>
  95. {
  96. if (x.IsClass && !x.IsGenericType && x.IsSubclassOf(typeof(BaseObject)))
  97. {
  98. var module = x.Assembly.Modules.FirstOrDefault();
  99. if(module != null && !module.FullyQualifiedName.Equals("<Unknown>"))
  100. {
  101. assemblies.Add(x.Assembly);
  102. return true;
  103. }
  104. }
  105. return false;
  106. });
  107. DefaultAssemblies.AddRange(assemblies);
  108. var references = Directory.GetFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "refs"), "*.dll")
  109. .Select(x => MetadataReference.CreateFromFile(x)).ToArray();
  110. var files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll").Where(
  111. x => !Path.GetFileName(x).ToLower().StartsWith("gsdll")
  112. && !Path.GetFileName(x).ToLower().StartsWith("pdfium")
  113. && !Path.GetFileName(x).ToLower().StartsWith("ikvm-native")
  114. && !Path.GetFileName(x).ToLower().StartsWith("sqlite.interop")
  115. && !Path.GetFileName(x).ToLower().StartsWith("microsoft.codeanalysis")
  116. );
  117. var hostReferences = RoslynHostReferences.NamespaceDefault.With(
  118. typeNamespaceImports: typelist
  119. //, assemblyReferences: DefaultAssemblies
  120. , assemblyPathReferences: files,
  121. references: references
  122. );
  123. CompilationReferences = RoslynHostReferences.NamespaceDefault.With(
  124. typeNamespaceImports: typelist
  125. , assemblyReferences: DefaultAssemblies
  126. , assemblyPathReferences: files
  127. ).GetReferences();
  128. _host = new RoslynHost(
  129. DefaultAssemblies.ToArray(),
  130. hostReferences
  131. );
  132. return _host;
  133. });
  134. return _hostTask;
  135. }
  136. public static void Initialize()
  137. {
  138. if(_hostTask is null)
  139. {
  140. InitializeHost();
  141. }
  142. }
  143. public class Diagnostic(DiagnosticSeverity severity, string contents)
  144. {
  145. public DiagnosticSeverity Severity { get; } = severity;
  146. public string Contents { get; } = contents;
  147. }
  148. public bool Compile()
  149. {
  150. Result = null;
  151. compiled = null;
  152. Script = CSharpScript.Create($"#nullable enable {Text}", ScriptOptions.Default
  153. .AddReferences(CompilationReferences)
  154. .AddImports(Host.DefaultImports));
  155. var compilation = Script.GetCompilation();
  156. var hasResult = (bool)HasSubmissionResult.Invoke(compilation, null);
  157. var diagnostics = Script.Compile();
  158. Diagnostics.Clear();
  159. foreach(var diagnostic in diagnostics)
  160. {
  161. var argsProperty = typeof(Microsoft.CodeAnalysis.Diagnostic).GetProperty("Arguments", BindingFlags.Instance | BindingFlags.NonPublic);
  162. if(argsProperty is not null)
  163. {
  164. var value = (argsProperty.GetValue(diagnostic) as IEnumerable<object?>) ?? [];
  165. var message = string.Format(diagnostic.Descriptor.MessageFormat.ToString(), value.ToArray());
  166. var span = diagnostic.Location.GetMappedLineSpan();
  167. Diagnostics.Add(new(diagnostic.Severity, $"({span.StartLinePosition.Line},{span.StartLinePosition.Character}): " +
  168. $"{diagnostic.Severity.ToString().ToLower()} {diagnostic.Id}: " +
  169. $"{message}"));
  170. }
  171. else
  172. {
  173. var formatted = FormatObject(diagnostic);
  174. if (!formatted.StartsWith("CSDiagnostic(")) continue;
  175. var content = formatted.Split(new[] { Environment.NewLine }, StringSplitOptions.None).First().Replace("CSDiagnostic(", "").Replace(") {", "");
  176. Diagnostics.Add(new(diagnostic.Severity, content));
  177. }
  178. }
  179. if (Diagnostics.Any(x => x.Severity == DiagnosticSeverity.Error))
  180. {
  181. var result = new List<string>();
  182. foreach (var diagnostic in Diagnostics)
  183. result.Add(diagnostic.Contents);
  184. Result = string.Join(Environment.NewLine, result);
  185. return false;
  186. }
  187. return true;
  188. }
  189. public void SetValue(string name, object? value)
  190. {
  191. var prop = Properties.FirstOrDefault(x => x.Name.Equals(name));
  192. if (prop == null)
  193. Properties.Add(new ScriptProperty(name, value));
  194. else
  195. prop.Value = value;
  196. }
  197. public object? GetValue(string name, object? defaultvalue = null)
  198. {
  199. var prop = Properties.FirstOrDefault(x => x.Name.Equals(name));
  200. return prop != null ? prop.Value : defaultvalue;
  201. }
  202. public Type? GetClassType(string className = "Module")
  203. {
  204. if (!compiled.HasValue)
  205. {
  206. compiled = false;
  207. var stream = new MemoryStream();
  208. var emitResult = Script.GetCompilation().Emit(stream);
  209. if (emitResult.Success)
  210. {
  211. var asm = Assembly.Load(stream.ToArray());
  212. type = asm.GetTypes().Where(x => x.Name.Equals(className)).FirstOrDefault();
  213. if (type != null)
  214. {
  215. obj = Activator.CreateInstance(type);
  216. compiled = true;
  217. }
  218. }
  219. }
  220. return type;
  221. }
  222. public object? GetObject(string className = "Module")
  223. {
  224. GetClassType(className);
  225. return obj;
  226. }
  227. public MethodInfo? GetMethod(string className = "Module", string methodName = "Execute")
  228. {
  229. var type = GetClassType(className);
  230. if (compiled == true && type != null)
  231. {
  232. return type.GetMethod(methodName);
  233. }
  234. else
  235. {
  236. return null;
  237. }
  238. }
  239. public bool Execute(string classname = "Module", string methodname = "Execute", object?[]? parameters = null, bool defaultResult = false)
  240. {
  241. var result = defaultResult;
  242. var type = GetClassType(classname);
  243. var obj = GetObject(classname);
  244. var method = GetMethod(classname, methodname);
  245. if (compiled == true && type != null && method != null)
  246. {
  247. foreach (var property in Properties)
  248. {
  249. var prop = type.GetProperty(property.Name);
  250. prop?.SetValue(obj, property.Value);
  251. }
  252. if (method.ReturnType == typeof(bool))
  253. {
  254. result = (bool)(method.Invoke(obj, parameters ?? []) ?? false);
  255. }
  256. else
  257. {
  258. method.Invoke(obj, parameters ?? []);
  259. result = true;
  260. }
  261. if (result)
  262. {
  263. foreach (var property in Properties)
  264. {
  265. var prop = type.GetProperty(property.Name);
  266. if (prop != null)
  267. property.Value = prop.GetValue(obj);
  268. }
  269. }
  270. }
  271. return result;
  272. }
  273. private static string FormatException(Exception ex)
  274. {
  275. return CSharpObjectFormatter.Instance.FormatException(ex);
  276. }
  277. private static string FormatObject(object o)
  278. {
  279. return CSharpObjectFormatter.Instance.FormatObject(o, PrintOptions);
  280. }
  281. protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
  282. {
  283. if (!EqualityComparer<T>.Default.Equals(field, value))
  284. {
  285. field = value;
  286. // ReSharper disable once ExplicitCallerInfoArgument
  287. OnPropertyChanged(propertyName);
  288. return true;
  289. }
  290. return false;
  291. }
  292. protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
  293. {
  294. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  295. }
  296. public static bool RunCustomModule(DataModel model, Dictionary<string, object[]> selected, string code)
  297. {
  298. var script = new ScriptDocument(code);
  299. if (!script.Compile())
  300. {
  301. throw new CompileException();
  302. }
  303. script.SetValue("Data", selected);
  304. script.SetValue("Model", model);
  305. script.Execute(methodname: "BeforeLoad");
  306. var tableNames = model.DefaultTableNames.ToList();
  307. script.Execute(methodname: "CheckTables", parameters: new[] { tableNames });
  308. model.LoadModel(tableNames);
  309. return script.Execute();
  310. }
  311. }