Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2520_PersistenceReintegration/HeuristicLab.Operators.Programmable/3.3/ProgrammableOperator.cs @ 16474

Last change on this file since 16474 was 16462, checked in by jkarder, 5 years ago

#2520: worked on reintegration of new persistence

  • added nuget references to HEAL.Fossil
  • added StorableType attributes to many classes
  • changed signature of StorableConstructors
  • removed some classes in old persistence
  • removed some unnecessary usings
File size: 16.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2019 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.IO;
27using System.Linq;
28using System.Reflection;
29using System.Text;
30using System.Text.RegularExpressions;
31using HeuristicLab.Collections;
32using HeuristicLab.Common;
33using HeuristicLab.Common.Resources;
34using HeuristicLab.Core;
35using HeuristicLab.Persistence.Auxiliary;
36using HEAL.Fossil;
37using HeuristicLab.PluginInfrastructure;
38using Microsoft.CSharp;
39
40namespace HeuristicLab.Operators.Programmable {
41
42  [Item("ProgrammableOperator", "An operator that can be programmed for arbitrary needs.")]
43  [StorableType("741279E4-4C38-4D66-B9F1-03E0F8B47A78")]
44  public class ProgrammableOperator : Operator, IParameterizedNamedItem, IStorableContent, IProgrammableItem {
45
46    #region Fields & Properties
47
48    public string Filename { get; set; }
49
50    public new ParameterCollection Parameters {
51      get { return base.Parameters; }
52    }
53
54    public static new System.Drawing.Image StaticItemImage { get { return VSImageLibrary.Script; } }
55
56    private MethodInfo executeMethod;
57    public CompilerErrorCollection CompileErrors { get; private set; }
58    public string CompilationUnitCode { get; private set; }
59
60    [Storable]
61    private string code;
62    public string Code {
63      get { return code; }
64      set {
65        if (value != code) {
66          code = value;
67          executeMethod = null;
68          OnCodeChanged();
69        }
70      }
71    }
72
73    private object syncRoot = new object();
74
75    private static object initLock = new object();
76    private static Dictionary<string, List<Assembly>> defaultPluginDict;
77    private static Dictionary<Assembly, bool> defaultAssemblyDict;
78
79    public readonly Dictionary<string, List<Assembly>> Plugins;
80    protected Dictionary<Assembly, bool> Assemblies;
81
82    [Storable(Name = "SelectedAssemblies")]
83    private List<string> _selectedAssemblyNames_persistence {
84      get {
85        return Assemblies.Where(a => a.Value).Select(a => a.Key.FullName).ToList();
86      }
87      set {
88        var selectedAssemblyNames = new HashSet<string>(value.Select(n => new AssemblyName(n).Name));
89        foreach (var a in Assemblies.Keys.ToList()) {
90          Assemblies[a] = selectedAssemblyNames.Contains(new AssemblyName(a.FullName).Name);
91        }
92      }
93    }
94
95    public IEnumerable<Assembly> AvailableAssemblies {
96      get { return Assemblies.Keys; }
97    }
98
99    public IEnumerable<Assembly> SelectedAssemblies {
100      get { return Assemblies.Where(kvp => kvp.Value).Select(kvp => kvp.Key); }
101    }
102
103    [Storable]
104    private HashSet<string> namespaces;
105    public IEnumerable<string> Namespaces {
106      get { return namespaces; }
107    }
108
109    public override bool CanChangeDescription {
110      get { return true; }
111    }
112
113    #endregion
114
115    #region Extended Accessors
116
117    public void SelectAssembly(Assembly a) {
118      if (a != null && Assemblies.ContainsKey(a) && !Assemblies[a]) {
119        Assemblies[a] = true;
120      }
121    }
122
123    public void UnselectAssembly(Assembly a) {
124      if (a != null && Assemblies.ContainsKey(a) && Assemblies[a]) {
125        Assemblies[a] = false;
126      }
127    }
128
129    public void SelectNamespace(string ns) {
130      namespaces.Add(ns);
131      OnSignatureChanged();
132    }
133
134    public void UnselectNamespace(string ns) {
135      namespaces.Remove(ns);
136      OnSignatureChanged();
137    }
138
139    public IEnumerable<string> GetAllNamespaces(bool selectedAssembliesOnly) {
140      var namespaces = new HashSet<string>();
141      foreach (var a in Assemblies) {
142        if (!selectedAssembliesOnly || a.Value) {
143          foreach (var t in a.Key.GetTypes()) {
144            if (t.IsPublic) {
145              foreach (string ns in GetNamespaceHierachy(t.Namespace)) {
146                namespaces.Add(ns);
147              }
148            }
149          }
150        }
151      }
152      return namespaces;
153    }
154
155    private IEnumerable<string> GetNamespaceHierachy(string ns) {
156      if (ns != null) {
157        for (int i = ns.Length; i != -1; i = ns.LastIndexOf('.', i - 1)) {
158          yield return ns.Substring(0, i);
159        }
160      }
161    }
162
163    #endregion
164
165    #region Construction & Initialization
166
167    [StorableConstructor]
168    protected ProgrammableOperator(StorableConstructorFlag _) : base(_) {
169      ProgrammableOperator.StaticInitialize();
170      Assemblies = defaultAssemblyDict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
171      Plugins = defaultPluginDict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToList());
172    }
173
174    protected ProgrammableOperator(ProgrammableOperator original, Cloner cloner)
175      : base(original, cloner) {
176      code = original.Code;
177      executeMethod = original.executeMethod;
178      Assemblies = original.Assemblies.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
179      Plugins = original.Plugins.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
180      namespaces = new HashSet<string>(original.namespaces);
181      CompilationUnitCode = original.CompilationUnitCode;
182      if (original.CompileErrors != null)
183        CompileErrors = new CompilerErrorCollection(original.CompileErrors);
184      RegisterEvents();
185    }
186
187    public ProgrammableOperator() {
188      code = "";
189      executeMethod = null;
190      ProgrammableOperator.StaticInitialize();
191      Assemblies = defaultAssemblyDict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
192      Plugins = defaultPluginDict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToList());
193      namespaces = new HashSet<string>(DiscoverNamespaces());
194      RegisterEvents();
195    }
196
197    [StorableHook(HookType.AfterDeserialization)]
198    private void AfterDeserialization() {
199      // ensure default namespaces and assemblies are present if deserializing old operators
200      namespaces.Add("HeuristicLab.Operators.Programmable");
201      Assemblies[typeof(HeuristicLab.Operators.Operator).Assembly] = true;
202      Assemblies[typeof(HeuristicLab.Operators.Programmable.ProgrammableOperator).Assembly] = true;
203      Assemblies[typeof(System.Threading.Barrier).Assembly] = true; // ensure new System assembly is selected (4.0.0.0)
204      RegisterEvents();
205    }
206
207    public override IDeepCloneable Clone(Cloner cloner) {
208      return new ProgrammableOperator(this, cloner);
209    }
210
211    private void RegisterEvents() {
212      Parameters.ItemsAdded += Parameters_Changed;
213      Parameters.ItemsRemoved += Parameters_Changed;
214      Parameters.ItemsReplaced += Parameters_Changed;
215      Parameters.CollectionReset += Parameters_Changed;
216    }
217
218    private void Parameters_Changed(object sender, CollectionItemsChangedEventArgs<IParameter> args) {
219      OnSignatureChanged();
220    }
221
222    protected void OnSignatureChanged() {
223      executeMethod = null;
224      EventHandler handler = SignatureChanged;
225      if (handler != null) handler(this, EventArgs.Empty);
226    }
227
228    private static void StaticInitialize() {
229      lock (initLock) {
230        if (defaultPluginDict != null && defaultAssemblyDict != null)
231          return;
232        defaultAssemblyDict = DiscoverAssemblies();
233        defaultPluginDict = GroupAssemblies(defaultAssemblyDict.Keys);
234      }
235    }
236
237    private static Dictionary<string, List<Assembly>> GroupAssemblies(IEnumerable<Assembly> assemblies) {
238      var plugins = new Dictionary<string, List<Assembly>>();
239      var locationTable = assemblies.ToDictionary(a => a.Location, a => a);
240
241      foreach (var plugin in ApplicationManager.Manager.Plugins) {
242        var aList = new List<Assembly>();
243        foreach (var aName in from file in plugin.Files
244                              where file.Type == PluginFileType.Assembly
245                              select file.Name) {
246          Assembly a;
247          locationTable.TryGetValue(aName, out a);
248          if (a != null) {
249            aList.Add(a);
250            locationTable.Remove(aName);
251          }
252        }
253        plugins[plugin.Name] = aList;
254      }
255
256      plugins["other"] = locationTable.Values.ToList();
257      return plugins;
258    }
259
260    protected static List<Assembly> defaultAssemblies = new List<Assembly>() {
261      // mscorlib automatically included (would cause duplicate)
262      typeof(System.ComponentModel.INotifyPropertyChanged).Assembly, // System.dll
263      typeof(System.Linq.Enumerable).Assembly,  // System.Core.dll
264      typeof(System.Data.Linq.DataContext).Assembly, // System.Data.Linq.dll
265      typeof(HeuristicLab.Common.IDeepCloneable).Assembly,
266      typeof(HeuristicLab.Core.Item).Assembly,
267      typeof(HeuristicLab.Data.IntValue).Assembly,
268      typeof(HeuristicLab.Parameters.ValueParameter<IItem>).Assembly,
269      typeof(HeuristicLab.Collections.ObservableList<IItem>).Assembly,
270      typeof(HeuristicLab.Operators.Operator).Assembly,
271      typeof(HeuristicLab.Operators.Programmable.ProgrammableOperator).Assembly,
272    };
273
274    protected static Dictionary<Assembly, bool> DiscoverAssemblies() {
275      var assemblies = new Dictionary<Assembly, bool>();
276      foreach (var a in AppDomain.CurrentDomain.GetAssemblies()) {
277        try {
278          if (File.Exists(a.Location)) {
279            assemblies.Add(a, false);
280          }
281        } catch (NotSupportedException) {
282          // NotSupportedException is thrown while accessing
283          // the Location property of the anonymously hosted
284          // dynamic methods assembly, which is related to
285          // LINQ queries
286        }
287      }
288      foreach (var a in defaultAssemblies) {
289        if (assemblies.ContainsKey(a)) {
290          assemblies[a] = true;
291        } else {
292          assemblies.Add(a, true);
293        }
294      }
295      return assemblies;
296    }
297
298    protected static List<string> DiscoverNamespaces() {
299      return new List<string>() {
300        "HeuristicLab.Common",
301        "HeuristicLab.Core",
302        "HeuristicLab.Data",
303        "HeuristicLab.Parameters",
304        "HeuristicLab.Operators.Programmable",
305        "System",
306        "System.Collections.Generic",
307        "System.Text",
308        "System.Linq",
309        "System.Data.Linq",
310      };
311    }
312
313    #endregion
314
315    #region Compilation
316
317    private static CSharpCodeProvider codeProvider =
318      new CSharpCodeProvider(
319        new Dictionary<string, string>() {
320          { "CompilerVersion", "v4.0" },  // support C# 4.0 syntax
321        });
322
323    private CompilerResults DoCompile() {
324      CompilerParameters parameters = new CompilerParameters();
325      parameters.GenerateExecutable = false;
326      parameters.GenerateInMemory = true;
327      parameters.IncludeDebugInformation = false;
328      parameters.ReferencedAssemblies.AddRange(SelectedAssemblies.Select(a => a.Location).ToArray());
329      var unit = CreateCompilationUnit();
330      var writer = new StringWriter();
331      codeProvider.GenerateCodeFromCompileUnit(
332        unit,
333        writer,
334        new CodeGeneratorOptions() {
335          BracingStyle = "C",
336          ElseOnClosing = true,
337          IndentString = "  ",
338        });
339      CompilationUnitCode = writer.ToString();
340      return codeProvider.CompileAssemblyFromDom(parameters, unit);
341    }
342
343    public virtual void Compile() {
344      var results = DoCompile();
345      executeMethod = null;
346      CompileErrors = results.Errors;
347      if (results.Errors.HasErrors) {
348        StringBuilder sb = new StringBuilder();
349        foreach (CompilerError error in results.Errors) {
350          sb.Append(error.Line).Append(':')
351            .Append(error.Column).Append(": ")
352            .AppendLine(error.ErrorText);
353        }
354        throw new Exception(string.Format(
355          "Compilation of \"{0}\" failed:{1}{2}",
356          Name, Environment.NewLine,
357          sb.ToString()));
358      } else {
359        Assembly assembly = results.CompiledAssembly;
360        Type[] types = assembly.GetTypes();
361        executeMethod = types[0].GetMethod("Execute");
362      }
363    }
364
365    private CodeCompileUnit CreateCompilationUnit() {
366      CodeNamespace ns = new CodeNamespace("HeuristicLab.Operators.Programmable.CustomOperators");
367      ns.Types.Add(CreateType());
368      ns.Imports.AddRange(
369        GetSelectedAndValidNamespaces()
370        .Select(n => new CodeNamespaceImport(n))
371        .ToArray());
372      CodeCompileUnit unit = new CodeCompileUnit();
373      unit.Namespaces.Add(ns);
374      return unit;
375    }
376
377    public IEnumerable<string> GetSelectedAndValidNamespaces() {
378      var possibleNamespaces = new HashSet<string>(GetAllNamespaces(true));
379      foreach (var ns in Namespaces)
380        if (possibleNamespaces.Contains(ns))
381          yield return ns;
382    }
383
384    public static readonly Regex SafeTypeNameCharRegex = new Regex("[_a-zA-Z0-9]+");
385    public static readonly Regex SafeTypeNameRegex = new Regex("[_a-zA-Z][_a-zA-Z0-9]*");
386
387    public string CompiledTypeName {
388      get {
389        var sb = new StringBuilder();
390        foreach (string s in SafeTypeNameCharRegex.Matches(Name).Cast<Match>().Select(m => m.Value)) {
391          sb.Append(s);
392        }
393        return SafeTypeNameRegex.Match(sb.ToString()).Value;
394      }
395    }
396
397    private CodeTypeDeclaration CreateType() {
398      CodeTypeDeclaration typeDecl = new CodeTypeDeclaration(CompiledTypeName) {
399        IsClass = true,
400        TypeAttributes = TypeAttributes.Public,
401      };
402      typeDecl.Members.Add(CreateMethod());
403      return typeDecl;
404    }
405
406    public string Signature {
407      get {
408        var sb = new StringBuilder()
409        .Append("public static IOperation Execute(")
410        .Append(TypeNameParser.Parse(GetType().FullName).GetTypeNameInCode(namespaces))
411        .Append(" op, ")
412        .Append(TypeNameParser.Parse(typeof(IExecutionContext).FullName).GetTypeNameInCode(namespaces))
413        .Append(" context");
414        foreach (IParameter param in Parameters) {
415          sb.Append(String.Format(", {0} {1}",
416            TypeNameParser.Parse(param.GetType().FullName).GetTypeNameInCode(namespaces),
417            param.Name));
418        }
419        return sb.Append(")").ToString();
420      }
421    }
422
423    public event EventHandler SignatureChanged;
424
425    private static Regex lineSplitter = new Regex(@"\r\n|\r|\n");
426
427    private CodeMemberMethod CreateMethod() {
428      CodeMemberMethod method = new CodeMemberMethod();
429      method.Name = "Execute";
430      method.ReturnType = new CodeTypeReference(typeof(IOperation));
431      method.Attributes = MemberAttributes.Public | MemberAttributes.Static;
432      method.Parameters.Add(new CodeParameterDeclarationExpression(GetType(), "op"));
433      method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IExecutionContext), "context"));
434      foreach (var param in Parameters)
435        method.Parameters.Add(new CodeParameterDeclarationExpression(param.GetType(), param.Name));
436      string[] codeLines = lineSplitter.Split(code);
437      for (int i = 0; i < codeLines.Length; i++) {
438        codeLines[i] = string.Format("#line {0} \"ProgrammableOperator\"{1}{2}", i + 1, "\r\n", codeLines[i]);
439      }
440      method.Statements.Add(new CodeSnippetStatement(string.Join("\r\n", codeLines) + MethodSuffix));
441      return method;
442    }
443
444    public virtual string MethodSuffix {
445      get { return "return null;"; }
446    }
447
448    #endregion
449
450    #region HeuristicLab interfaces
451
452    public override IOperation Apply() {
453      lock (syncRoot) {
454        if (executeMethod == null) {
455          Compile();
456        }
457      }
458
459      var parameters = new List<object>() { this, ExecutionContext };
460      parameters.AddRange(Parameters.Select(p => (object)p));
461      return (IOperation)executeMethod.Invoke(null, parameters.ToArray());
462    }
463
464    public event EventHandler CodeChanged;
465    protected virtual void OnCodeChanged() {
466      EventHandler handler = CodeChanged;
467      if (handler != null) handler(this, EventArgs.Empty);
468    }
469
470    #endregion
471  }
472}
Note: See TracBrowser for help on using the repository browser.