Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Scripting/3.3/Script.cs @ 10680

Last change on this file since 10680 was 10577, checked in by abeham, 11 years ago

#2136:

  • Fixed drag-drop behavior in VariableStoreView
  • Added additional information to Script and changed setting name and description
File size: 9.6 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("C# 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 variables in the script's variable store
48// vars has a Contains(string) method to check if a variable exists and implements IEnumerable
49
50using System;
51using System.Linq;
52using System.Collections.Generic;
53using HeuristicLab.Common;
54using HeuristicLab.Core;
55using HeuristicLab.Data;
56
57public class UserScript : HeuristicLab.Scripting.UserScriptBase {
58  public override void Main() {
59    // type your code here
60  }
61
62  // implement further classes and methods
63
64}";
65    #endregion
66
67    #region Fields & Properties
68    private UserScriptBase compiledScript;
69
70    public string Filename { get; set; }
71
72    public static new Image StaticItemImage {
73      get { return VSImageLibrary.Script; }
74    }
75
76    [Storable]
77    private VariableStore variableStore;
78    public VariableStore VariableStore {
79      get { return variableStore; }
80    }
81
82    [Storable]
83    private string code;
84    public string Code {
85      get { return code; }
86      set {
87        if (value == code) return;
88        code = value;
89        compiledScript = null;
90        OnCodeChanged();
91      }
92    }
93
94    private string compilationUnitCode;
95    public string CompilationUnitCode {
96      get { return compilationUnitCode; }
97    }
98
99    private CompilerErrorCollection compileErrors;
100    public CompilerErrorCollection CompileErrors {
101      get { return compileErrors; }
102      private set {
103        compileErrors = value;
104        OnCompileErrorsChanged();
105      }
106    }
107    #endregion
108
109    #region Construction & Initialization
110    [StorableConstructor]
111    private Script(bool deserializing) : base(deserializing) { }
112    private Script(Script original, Cloner cloner)
113      : base(original, cloner) {
114      code = original.code;
115      variableStore = new VariableStore();
116      compilationUnitCode = original.compilationUnitCode;
117      if (original.compileErrors != null)
118        compileErrors = new CompilerErrorCollection(original.compileErrors);
119    }
120    public Script() {
121      name = ItemName;
122      description = ItemDescription;
123      code = CodeTemplate;
124      variableStore = new VariableStore();
125    }
126    public Script(string code)
127      : this() {
128      this.code = code;
129    }
130
131    public override IDeepCloneable Clone(Cloner cloner) {
132      return new Script(this, cloner);
133    }
134    #endregion
135
136    private void RegisterScriptEvents() {
137      if (compiledScript == null) return;
138      compiledScript.ConsoleOutputChanged += compiledScript_ConsoleOutputChanged;
139    }
140
141    private void DeregisterScriptEvents() {
142      if (compiledScript == null) return;
143      compiledScript.ConsoleOutputChanged -= compiledScript_ConsoleOutputChanged;
144    }
145
146    #region Compilation
147    private CSharpCodeProvider codeProvider =
148      new CSharpCodeProvider(
149        new Dictionary<string, string> {
150          { "CompilerVersion", "v4.0" },  // support C# 4.0 syntax
151        });
152
153    private CompilerResults DoCompile() {
154      var parameters = new CompilerParameters {
155        GenerateExecutable = false,
156        GenerateInMemory = true,
157        IncludeDebugInformation = true,
158        WarningLevel = 4
159      };
160      parameters.ReferencedAssemblies.AddRange(
161        GetAssemblies()
162        .Select(a => a.Location)
163        .ToArray());
164      var unit = CreateCompilationUnit();
165      var writer = new StringWriter();
166      codeProvider.GenerateCodeFromCompileUnit(
167        unit,
168        writer,
169        new CodeGeneratorOptions {
170          ElseOnClosing = true,
171          IndentString = "  ",
172        });
173      compilationUnitCode = writer.ToString();
174      return codeProvider.CompileAssemblyFromDom(parameters, unit);
175    }
176
177    public void Compile() {
178      var results = DoCompile();
179      compiledScript = null;
180      CompileErrors = results.Errors;
181      if (results.Errors.HasErrors) {
182        var sb = new StringBuilder();
183        foreach (CompilerError error in results.Errors) {
184          sb.Append(error.Line).Append(':')
185            .Append(error.Column).Append(": ")
186            .AppendLine(error.ErrorText);
187        }
188        throw new Exception(string.Format(
189          "Compilation of \"{0}\" failed:{1}{2}",
190          Name, Environment.NewLine,
191          sb.ToString()));
192      } else {
193        var assembly = results.CompiledAssembly;
194        var types = assembly.GetTypes();
195        DeregisterScriptEvents();
196        compiledScript = (UserScriptBase)Activator.CreateInstance(types[0]);
197        RegisterScriptEvents();
198      }
199    }
200
201    public IEnumerable<Assembly> GetAssemblies() {
202      var assemblies = new List<Assembly>();
203      foreach (var a in AppDomain.CurrentDomain.GetAssemblies()) {
204        try {
205          if (File.Exists(a.Location)) assemblies.Add(a);
206        } catch (NotSupportedException) {
207          // NotSupportedException is thrown while accessing
208          // the Location property of the anonymously hosted
209          // dynamic methods assembly, which is related to
210          // LINQ queries
211        }
212      }
213      assemblies.Add(typeof(Microsoft.CSharp.RuntimeBinder.Binder).Assembly); // for dlr functionality
214      return assemblies;
215    }
216
217    private readonly Regex SafeTypeNameCharRegex = new Regex("[_a-zA-Z0-9]+");
218    private readonly Regex SafeTypeNameRegex = new Regex("[_a-zA-Z][_a-zA-Z0-9]*");
219
220    private CodeCompileUnit CreateCompilationUnit() {
221      var unit = new CodeSnippetCompileUnit(code);
222      return unit;
223    }
224
225    public string CompiledTypeName {
226      get {
227        var sb = new StringBuilder();
228        var strings = SafeTypeNameCharRegex.Matches(Name)
229                                           .Cast<Match>()
230                                           .Select(m => m.Value);
231        foreach (string s in strings)
232          sb.Append(s);
233        return SafeTypeNameRegex.Match(sb.ToString()).Value;
234      }
235    }
236    #endregion
237
238    private Thread scriptThread;
239    public void Execute() {
240      if (compiledScript == null) return;
241      var executeMethod = typeof(UserScriptBase).GetMethod(ExecuteMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
242      if (executeMethod != null) {
243        scriptThread = new Thread(() => {
244          Exception ex = null;
245          try {
246            OnScriptExecutionStarted();
247            executeMethod.Invoke(compiledScript, new[] { VariableStore });
248          } catch (ThreadAbortException) {
249            // the execution was cancelled by the user
250          } catch (TargetInvocationException e) {
251            ex = e.InnerException;
252          } finally {
253            OnScriptExecutionFinished(ex);
254          }
255        });
256        scriptThread.Start();
257      }
258    }
259
260    public void Kill() {
261      if (scriptThread.IsAlive)
262        scriptThread.Abort();
263    }
264
265    private void compiledScript_ConsoleOutputChanged(object sender, EventArgs<string> e) {
266      OnConsoleOutputChanged(e.Value);
267    }
268
269    public event EventHandler CodeChanged;
270    private void OnCodeChanged() {
271      var handler = CodeChanged;
272      if (handler != null) handler(this, EventArgs.Empty);
273    }
274
275    public event EventHandler CompileErrorsChanged;
276    private void OnCompileErrorsChanged() {
277      var handler = CompileErrorsChanged;
278      if (handler != null) handler(this, EventArgs.Empty);
279    }
280
281    public event EventHandler ScriptExecutionStarted;
282    private void OnScriptExecutionStarted() {
283      var handler = ScriptExecutionStarted;
284      if (handler != null) handler(this, EventArgs.Empty);
285    }
286
287    public event EventHandler<EventArgs<Exception>> ScriptExecutionFinished;
288    private void OnScriptExecutionFinished(Exception e) {
289      var handler = ScriptExecutionFinished;
290      if (handler != null) handler(this, new EventArgs<Exception>(e));
291    }
292
293    public event EventHandler<EventArgs<string>> ConsoleOutputChanged;
294    private void OnConsoleOutputChanged(string args) {
295      var handler = ConsoleOutputChanged;
296      if (handler != null) handler(this, new EventArgs<string>(args));
297    }
298  }
299}
Note: See TracBrowser for help on using the repository browser.