ScriptDocument.cs 10 KB

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