ScriptDocument.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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. public List<Diagnostic> Diagnostics { get; } = new();
  78. private static MethodInfo HasSubmissionResult { get; } =
  79. typeof(Compilation).GetMethod(nameof(HasSubmissionResult), BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
  80. ?? throw new NullReferenceException();
  81. private static PrintOptions PrintOptions { get; } = new() { MemberDisplayFormat = MemberDisplayFormat.SeparateLines };
  82. public List<ScriptProperty> Properties { get; }
  83. public event PropertyChangedEventHandler? PropertyChanged;
  84. private static IEnumerable<MetadataReference> CompilationReferences;
  85. private static Task<RoslynHost> InitializeHost()
  86. {
  87. _hostTask ??= Task.Run(() =>
  88. {
  89. using var profiler = new Profiler(true, "ScriptDocument");
  90. var assemblies = new HashSet<Assembly>();
  91. var typelist = CoreUtils.TypeList(
  92. AppDomain.CurrentDomain.GetAssemblies(),
  93. x =>
  94. {
  95. if (x.IsClass && !x.IsGenericType && x.IsSubclassOf(typeof(BaseObject)))
  96. {
  97. var module = x.Assembly.Modules.FirstOrDefault();
  98. if(module != null && !module.FullyQualifiedName.Equals("<Unknown>"))
  99. {
  100. assemblies.Add(x.Assembly);
  101. return true;
  102. }
  103. }
  104. return false;
  105. });
  106. DefaultAssemblies.AddRange(assemblies);
  107. var references = Directory.GetFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "refs"), "*.dll")
  108. .Select(x => MetadataReference.CreateFromFile(x)).ToArray();
  109. var files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll").Where(
  110. x => !Path.GetFileName(x).ToLower().StartsWith("gsdll")
  111. && !Path.GetFileName(x).ToLower().StartsWith("pdfium")
  112. && !Path.GetFileName(x).ToLower().StartsWith("ikvm-native")
  113. && !Path.GetFileName(x).ToLower().StartsWith("sqlite.interop")
  114. && !Path.GetFileName(x).ToLower().StartsWith("microsoft.codeanalysis")
  115. );
  116. var hostReferences = RoslynHostReferences.NamespaceDefault.With(
  117. typeNamespaceImports: typelist
  118. //, assemblyReferences: DefaultAssemblies
  119. , assemblyPathReferences: files,
  120. references: references
  121. );
  122. CompilationReferences = RoslynHostReferences.NamespaceDefault.With(
  123. typeNamespaceImports: typelist
  124. , assemblyReferences: DefaultAssemblies
  125. , assemblyPathReferences: files
  126. ).GetReferences();
  127. _host = new RoslynHost(
  128. DefaultAssemblies.ToArray(),
  129. hostReferences
  130. );
  131. return _host;
  132. });
  133. return _hostTask;
  134. }
  135. public static void Initialize()
  136. {
  137. if(_hostTask is null)
  138. {
  139. InitializeHost();
  140. }
  141. }
  142. public class Diagnostic(DiagnosticSeverity severity, string contents)
  143. {
  144. public DiagnosticSeverity Severity { get; } = severity;
  145. public string Contents { get; } = contents;
  146. }
  147. static ScriptOptions AddTrustedPlatformAssemblies(ScriptOptions options)
  148. {
  149. var tpa = (string?)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES");
  150. if (string.IsNullOrWhiteSpace(tpa))
  151. return options;
  152. var paths = tpa.Split(Path.PathSeparator);
  153. return options.AddReferences(paths.Select(p => MetadataReference.CreateFromFile(p)));
  154. }
  155. public bool Compile()
  156. {
  157. Result = null;
  158. compiled = null;
  159. var options = AddTrustedPlatformAssemblies(ScriptOptions.Default);
  160. Script = CSharpScript.Create(Text, options
  161. .AddReferences(CompilationReferences)
  162. .AddImports(Host.DefaultImports)
  163. .AddImports(
  164. "System",
  165. "System.Net",
  166. "System.Net.Http",
  167. "System.Net.Http.Headers",
  168. "System.Globalization"
  169. )
  170. );
  171. var compilation = Script.GetCompilation();
  172. var hasResult = (bool)HasSubmissionResult.Invoke(compilation, null);
  173. var diagnostics = Script.Compile();
  174. Diagnostics.Clear();
  175. foreach(var diagnostic in diagnostics)
  176. {
  177. var formatted = FormatObject(diagnostic);
  178. if (!formatted.StartsWith("CSDiagnostic(")) continue;
  179. var content = formatted.Split(new[] { Environment.NewLine }, StringSplitOptions.None).First().Replace("CSDiagnostic(", "").Replace(") {", "");
  180. Diagnostics.Add(new(diagnostic.Severity, content));
  181. }
  182. if (Diagnostics.Any(x => x.Severity == DiagnosticSeverity.Error))
  183. {
  184. var result = new List<string>();
  185. foreach (var diagnostic in Diagnostics)
  186. result.Add(diagnostic.Contents);
  187. Result = string.Join(Environment.NewLine, result);
  188. return false;
  189. }
  190. return true;
  191. }
  192. public void SetValue(string name, object? value)
  193. {
  194. var prop = Properties.FirstOrDefault(x => x.Name.Equals(name));
  195. if (prop == null)
  196. Properties.Add(new ScriptProperty(name, value));
  197. else
  198. prop.Value = value;
  199. }
  200. public object? GetValue(string name, object? defaultvalue = null)
  201. {
  202. var prop = Properties.FirstOrDefault(x => x.Name.Equals(name));
  203. return prop != null ? prop.Value : defaultvalue;
  204. }
  205. public Type? GetClassType(string className = "Module")
  206. {
  207. if (!compiled.HasValue)
  208. {
  209. compiled = false;
  210. var stream = new MemoryStream();
  211. var emitResult = Script.GetCompilation().Emit(stream);
  212. if (emitResult.Success)
  213. {
  214. var asm = Assembly.Load(stream.ToArray());
  215. type = asm.GetTypes().Where(x => x.Name.Equals(className)).FirstOrDefault();
  216. if (type != null)
  217. {
  218. obj = Activator.CreateInstance(type);
  219. compiled = true;
  220. }
  221. }
  222. }
  223. return type;
  224. }
  225. public object? GetObject(string className = "Module")
  226. {
  227. GetClassType(className);
  228. return obj;
  229. }
  230. public MethodInfo? GetMethod(string className = "Module", string methodName = "Execute")
  231. {
  232. var type = GetClassType(className);
  233. if (compiled == true && type != null)
  234. {
  235. return type.GetMethod(methodName);
  236. }
  237. else
  238. {
  239. return null;
  240. }
  241. }
  242. public bool Execute(string classname = "Module", string methodname = "Execute", object?[]? parameters = null, bool defaultResult = false)
  243. {
  244. var result = defaultResult;
  245. var type = GetClassType(classname);
  246. var obj = GetObject(classname);
  247. var method = GetMethod(classname, methodname);
  248. if (compiled == true && type != null && method != null)
  249. {
  250. foreach (var property in Properties)
  251. {
  252. var prop = type.GetProperty(property.Name);
  253. prop?.SetValue(obj, property.Value);
  254. }
  255. if (method.ReturnType == typeof(bool))
  256. {
  257. result = (bool)(method.Invoke(obj, parameters ?? []) ?? false);
  258. }
  259. else
  260. {
  261. method.Invoke(obj, parameters ?? []);
  262. result = true;
  263. }
  264. if (result)
  265. {
  266. foreach (var property in Properties)
  267. {
  268. var prop = type.GetProperty(property.Name);
  269. if (prop != null)
  270. property.Value = prop.GetValue(obj);
  271. }
  272. }
  273. }
  274. return result;
  275. }
  276. private static string FormatException(Exception ex)
  277. {
  278. return CSharpObjectFormatter.Instance.FormatException(ex);
  279. }
  280. private static string FormatObject(object o)
  281. {
  282. return CSharpObjectFormatter.Instance.FormatObject(o, PrintOptions);
  283. }
  284. protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
  285. {
  286. if (!EqualityComparer<T>.Default.Equals(field, value))
  287. {
  288. field = value;
  289. // ReSharper disable once ExplicitCallerInfoArgument
  290. OnPropertyChanged(propertyName);
  291. return true;
  292. }
  293. return false;
  294. }
  295. protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
  296. {
  297. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  298. }
  299. public static bool RunCustomModule(DataModel model, Dictionary<string, object[]> selected, string code)
  300. {
  301. var script = new ScriptDocument(code);
  302. if (!script.Compile())
  303. {
  304. throw new CompileException();
  305. }
  306. script.SetValue("Data", selected);
  307. script.SetValue("Model", model);
  308. script.Execute(methodname: "BeforeLoad");
  309. var tableNames = model.DefaultTableNames.ToList();
  310. script.Execute(methodname: "CheckTables", parameters: new[] { tableNames });
  311. model.LoadModel(tableNames);
  312. return script.Execute();
  313. }
  314. }