ScriptDocument.cs 10 KB

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