Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.HLScript/3.3/Script.cs @ 10891

Last change on this file since 10891 was 10891, checked in by abeham, 10 years ago

#2136: merged r10359, r10391, r10401, r10506 to stable

File size: 9.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.CodeDom;
24using System.CodeDom.Compiler;
25using System.Collections.Generic;
26using System.Drawing;
27using System.IO;
28using System.Linq;
29using System.Reflection;
30using System.Text;
31using System.Text.RegularExpressions;
32using System.Threading;
33using HeuristicLab.Common;
34using HeuristicLab.Common.Resources;
35using HeuristicLab.Core;
36using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
37using Microsoft.CSharp;
38
39namespace HeuristicLab.Scripting {
40  [Item("Script", "An empty C# script.")]
41  [Creatable("Scripts")]
42  [StorableClass]
43  public sealed class Script : NamedItem, IStorableContent {
44    #region Constants
45    private const string ExecuteMethodName = "Execute";
46    private const string CodeTemplate =
47@"// use 'vars' to access global variables in the variable store
48
49using System;
50using System.Linq;
51using System.Collections.Generic;
52using HeuristicLab.Common;
53using HeuristicLab.Core;
54using HeuristicLab.Data;
55
56public class UserScript : HeuristicLab.Scripting.UserScriptBase {
57  public override void Main() {
58    // type your code here
59  }
60
61  // further classes and methods
62
63}";
64    #endregion
65
66    #region Fields & Properties
67    private UserScriptBase compiledScript;
68
69    public string Filename { get; set; }
70
71    public static new Image StaticItemImage {
72      get { return VSImageLibrary.Script; }
73    }
74
75    [Storable]
76    private VariableStore variableStore;
77    public VariableStore VariableStore {
78      get { return variableStore; }
79    }
80
81    [Storable]
82    private string code;
83    public string Code {
84      get { return code; }
85      set {
86        if (value == code) return;
87        code = value;
88        compiledScript = null;
89        OnCodeChanged();
90      }
91    }
92
93    private string compilationUnitCode;
94    public string CompilationUnitCode {
95      get { return compilationUnitCode; }
96    }
97
98    private CompilerErrorCollection compileErrors;
99    public CompilerErrorCollection CompileErrors {
100      get { return compileErrors; }
101      private set {
102        compileErrors = value;
103        OnCompileErrorsChanged();
104      }
105    }
106    #endregion
107
108    #region Construction & Initialization
109    [StorableConstructor]
110    private Script(bool deserializing) : base(deserializing) { }
111    private Script(Script original, Cloner cloner)
112      : base(original, cloner) {
113      code = original.code;
114      variableStore = new VariableStore();
115      compilationUnitCode = original.compilationUnitCode;
116      if (original.compileErrors != null)
117        compileErrors = new CompilerErrorCollection(original.compileErrors);
118    }
119
120    public Script()
121      : base("Script", "A HeuristicLab script.") {
122      code = CodeTemplate;
123      variableStore = new VariableStore();
124    }
125
126    public override IDeepCloneable Clone(Cloner cloner) {
127      return new Script(this, cloner);
128    }
129    #endregion
130
131    private void RegisterScriptEvents() {
132      if (compiledScript == null) return;
133      compiledScript.ConsoleOutputChanged += compiledScript_ConsoleOutputChanged;
134    }
135
136    private void DeregisterScriptEvents() {
137      if (compiledScript == null) return;
138      compiledScript.ConsoleOutputChanged -= compiledScript_ConsoleOutputChanged;
139    }
140
141    #region Compilation
142    private CSharpCodeProvider codeProvider =
143      new CSharpCodeProvider(
144        new Dictionary<string, string> {
145          { "CompilerVersion", "v4.0" },  // support C# 4.0 syntax
146        });
147
148    private CompilerResults DoCompile() {
149      var parameters = new CompilerParameters {
150        GenerateExecutable = false,
151        GenerateInMemory = true,
152        IncludeDebugInformation = true,
153        WarningLevel = 4
154      };
155      parameters.ReferencedAssemblies.AddRange(
156        GetAssemblies()
157        .Select(a => a.Location)
158        .ToArray());
159      var unit = CreateCompilationUnit();
160      var writer = new StringWriter();
161      codeProvider.GenerateCodeFromCompileUnit(
162        unit,
163        writer,
164        new CodeGeneratorOptions {
165          ElseOnClosing = true,
166          IndentString = "  ",
167        });
168      compilationUnitCode = writer.ToString();
169      return codeProvider.CompileAssemblyFromDom(parameters, unit);
170    }
171
172    public void Compile() {
173      var results = DoCompile();
174      compiledScript = null;
175      CompileErrors = results.Errors;
176      if (results.Errors.HasErrors) {
177        var sb = new StringBuilder();
178        foreach (CompilerError error in results.Errors) {
179          sb.Append(error.Line).Append(':')
180            .Append(error.Column).Append(": ")
181            .AppendLine(error.ErrorText);
182        }
183        throw new Exception(string.Format(
184          "Compilation of \"{0}\" failed:{1}{2}",
185          Name, Environment.NewLine,
186          sb.ToString()));
187      } else {
188        var assembly = results.CompiledAssembly;
189        var types = assembly.GetTypes();
190        DeregisterScriptEvents();
191        compiledScript = (UserScriptBase)Activator.CreateInstance(types[0]);
192        RegisterScriptEvents();
193      }
194    }
195
196    public IEnumerable<Assembly> GetAssemblies() {
197      var assemblies = new List<Assembly>();
198      foreach (var a in AppDomain.CurrentDomain.GetAssemblies()) {
199        try {
200          if (File.Exists(a.Location)) assemblies.Add(a);
201        } catch (NotSupportedException) {
202          // NotSupportedException is thrown while accessing
203          // the Location property of the anonymously hosted
204          // dynamic methods assembly, which is related to
205          // LINQ queries
206        }
207      }
208      assemblies.Add(typeof(Microsoft.CSharp.RuntimeBinder.Binder).Assembly); // for dlr functionality
209      return assemblies;
210    }
211
212    private readonly Regex SafeTypeNameCharRegex = new Regex("[_a-zA-Z0-9]+");
213    private readonly Regex SafeTypeNameRegex = new Regex("[_a-zA-Z][_a-zA-Z0-9]*");
214
215    private CodeCompileUnit CreateCompilationUnit() {
216      var unit = new CodeSnippetCompileUnit(code);
217      return unit;
218    }
219
220    public string CompiledTypeName {
221      get {
222        var sb = new StringBuilder();
223        var strings = SafeTypeNameCharRegex.Matches(Name)
224                                           .Cast<Match>()
225                                           .Select(m => m.Value);
226        foreach (string s in strings)
227          sb.Append(s);
228        return SafeTypeNameRegex.Match(sb.ToString()).Value;
229      }
230    }
231    #endregion
232
233    private Thread scriptThread;
234    public void Execute() {
235      if (compiledScript == null) return;
236      var executeMethod = typeof(UserScriptBase).GetMethod(ExecuteMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
237      if (executeMethod != null) {
238        scriptThread = new Thread(() => {
239          Exception ex = null;
240          try {
241            OnScriptExecutionStarted();
242            executeMethod.Invoke(compiledScript, new[] { VariableStore });
243          } catch (ThreadAbortException) {
244            // the execution was cancelled by the user
245          } catch (TargetInvocationException e) {
246            ex = e.InnerException;
247          } finally {
248            OnScriptExecutionFinished(ex);
249          }
250        });
251        scriptThread.Start();
252      }
253    }
254
255    public void Kill() {
256      if (scriptThread.IsAlive)
257        scriptThread.Abort();
258    }
259
260    private void compiledScript_ConsoleOutputChanged(object sender, EventArgs<string> e) {
261      OnConsoleOutputChanged(e.Value);
262    }
263
264    public event EventHandler CodeChanged;
265    private void OnCodeChanged() {
266      var handler = CodeChanged;
267      if (handler != null) handler(this, EventArgs.Empty);
268    }
269
270    public event EventHandler CompileErrorsChanged;
271    private void OnCompileErrorsChanged() {
272      var handler = CompileErrorsChanged;
273      if (handler != null) handler(this, EventArgs.Empty);
274    }
275
276    public event EventHandler ScriptExecutionStarted;
277    private void OnScriptExecutionStarted() {
278      var handler = ScriptExecutionStarted;
279      if (handler != null) handler(this, EventArgs.Empty);
280    }
281
282    public event EventHandler<EventArgs<Exception>> ScriptExecutionFinished;
283    private void OnScriptExecutionFinished(Exception e) {
284      var handler = ScriptExecutionFinished;
285      if (handler != null) handler(this, new EventArgs<Exception>(e));
286    }
287
288    public event EventHandler<EventArgs<string>> ConsoleOutputChanged;
289    private void OnConsoleOutputChanged(string args) {
290      var handler = ConsoleOutputChanged;
291      if (handler != null) handler(this, new EventArgs<string>(args));
292    }
293  }
294}
Note: See TracBrowser for help on using the repository browser.