Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Operators.Programmable/3.3/ProgrammableOperator.cs @ 16832

Last change on this file since 16832 was 16832, checked in by gkronber, 5 years ago

#2967: merged r16528 from trunk to stable

File size: 16.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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 HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
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  [StorableClass]
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    }
132
133    public void UnselectNamespace(string ns) {
134      namespaces.Remove(ns);
135    }
136
137    public IEnumerable<string> GetAllNamespaces(bool selectedAssembliesOnly) {
138      var namespaces = new HashSet<string>();
139      foreach (var a in Assemblies) {
140        if (!selectedAssembliesOnly || a.Value) {
141          foreach (var t in a.Key.GetTypes()) {
142            if (t.IsPublic) {
143              foreach (string ns in GetNamespaceHierachy(t.Namespace)) {
144                namespaces.Add(ns);
145              }
146            }
147          }
148        }
149      }
150      return namespaces;
151    }
152
153    private IEnumerable<string> GetNamespaceHierachy(string ns) {
154      if (ns != null) {
155        for (int i = ns.Length; i != -1; i = ns.LastIndexOf('.', i - 1)) {
156          yield return ns.Substring(0, i);
157        }
158      }
159    }
160
161    #endregion
162
163    #region Construction & Initialization
164
165    [StorableConstructor]
166    protected ProgrammableOperator(bool deserializing)
167      : base(deserializing) {
168      ProgrammableOperator.StaticInitialize();
169      Assemblies = defaultAssemblyDict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
170      Plugins = defaultPluginDict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToList());
171    }
172
173    protected ProgrammableOperator(ProgrammableOperator original, Cloner cloner)
174      : base(original, cloner) {
175      code = original.Code;
176      executeMethod = original.executeMethod;
177      Assemblies = original.Assemblies.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
178      Plugins = original.Plugins.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
179      namespaces = new HashSet<string>(original.namespaces);
180      CompilationUnitCode = original.CompilationUnitCode;
181      if (original.CompileErrors != null)
182        CompileErrors = new CompilerErrorCollection(original.CompileErrors);
183      RegisterEvents();
184    }
185
186    public ProgrammableOperator() {
187      code = "";
188      executeMethod = null;
189      ProgrammableOperator.StaticInitialize();
190      Assemblies = defaultAssemblyDict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
191      Plugins = defaultPluginDict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToList());
192      namespaces = new HashSet<string>(DiscoverNamespaces());
193      RegisterEvents();
194    }
195
196    [StorableHook(HookType.AfterDeserialization)]
197    private void AfterDeserialization() {
198      // ensure default namespaces and assemblies are present if deserializing old operators
199      namespaces.Add("HeuristicLab.Operators.Programmable");
200      Assemblies[typeof(HeuristicLab.Operators.Operator).Assembly] = true;
201      Assemblies[typeof(HeuristicLab.Operators.Programmable.ProgrammableOperator).Assembly] = true;
202      Assemblies[typeof(System.Threading.Barrier).Assembly] = true; // ensure new System assembly is selected (4.0.0.0)
203      RegisterEvents();
204    }
205
206    public override IDeepCloneable Clone(Cloner cloner) {
207      return new ProgrammableOperator(this, cloner);
208    }
209
210    private void RegisterEvents() {
211      Parameters.ItemsAdded += Parameters_Changed;
212      Parameters.ItemsRemoved += Parameters_Changed;
213      Parameters.ItemsReplaced += Parameters_Changed;
214      Parameters.CollectionReset += Parameters_Changed;
215    }
216
217    private void Parameters_Changed(object sender, CollectionItemsChangedEventArgs<IParameter> args) {
218      OnSignatureChanged();
219    }
220
221    protected void OnSignatureChanged() {
222      executeMethod = null;
223      EventHandler handler = SignatureChanged;
224      if (handler != null) handler(this, EventArgs.Empty);
225    }
226
227    private static void StaticInitialize() {
228      lock (initLock) {
229        if (defaultPluginDict != null && defaultAssemblyDict != null)
230          return;
231        defaultAssemblyDict = DiscoverAssemblies();
232        defaultPluginDict = GroupAssemblies(defaultAssemblyDict.Keys);
233      }
234    }
235
236    private static Dictionary<string, List<Assembly>> GroupAssemblies(IEnumerable<Assembly> assemblies) {
237      var plugins = new Dictionary<string, List<Assembly>>();
238      var locationTable = assemblies.ToDictionary(a => a.Location, a => a);
239
240      foreach (var plugin in ApplicationManager.Manager.Plugins) {
241        var aList = new List<Assembly>();
242        foreach (var aName in from file in plugin.Files
243                              where file.Type == PluginFileType.Assembly
244                              select file.Name) {
245          Assembly a;
246          locationTable.TryGetValue(aName, out a);
247          if (a != null) {
248            aList.Add(a);
249            locationTable.Remove(aName);
250          }
251        }
252        plugins[plugin.Name] = aList;
253      }
254
255      plugins["other"] = locationTable.Values.ToList();
256      return plugins;
257    }
258
259    protected static List<Assembly> defaultAssemblies = new List<Assembly>() {
260      // mscorlib automatically included (would cause duplicate)
261      typeof(System.ComponentModel.INotifyPropertyChanged).Assembly, // System.dll
262      typeof(System.Linq.Enumerable).Assembly,  // System.Core.dll
263      typeof(System.Data.Linq.DataContext).Assembly, // System.Data.Linq.dll
264      typeof(HeuristicLab.Common.IDeepCloneable).Assembly,
265      typeof(HeuristicLab.Core.Item).Assembly,
266      typeof(HeuristicLab.Data.IntValue).Assembly,
267      typeof(HeuristicLab.Parameters.ValueParameter<IItem>).Assembly,
268      typeof(HeuristicLab.Collections.ObservableList<IItem>).Assembly,
269      typeof(HeuristicLab.Operators.Operator).Assembly,
270      typeof(HeuristicLab.Operators.Programmable.ProgrammableOperator).Assembly,
271    };
272
273    protected static Dictionary<Assembly, bool> DiscoverAssemblies() {
274      var assemblies = new Dictionary<Assembly, bool>();
275      foreach (var a in AppDomain.CurrentDomain.GetAssemblies()) {
276        try {
277          if (File.Exists(a.Location)) {
278            assemblies.Add(a, false);
279          }
280        } catch (NotSupportedException) {
281          // NotSupportedException is thrown while accessing
282          // the Location property of the anonymously hosted
283          // dynamic methods assembly, which is related to
284          // LINQ queries
285        }
286      }
287      foreach (var a in defaultAssemblies) {
288        if (assemblies.ContainsKey(a)) {
289          assemblies[a] = true;
290        } else {
291          assemblies.Add(a, true);
292        }
293      }
294      return assemblies;
295    }
296
297    protected static List<string> DiscoverNamespaces() {
298      return new List<string>() {
299        "HeuristicLab.Common",
300        "HeuristicLab.Core",
301        "HeuristicLab.Data",
302        "HeuristicLab.Parameters",
303        "HeuristicLab.Operators.Programmable",
304        "System",
305        "System.Collections.Generic",
306        "System.Text",
307        "System.Linq",
308        "System.Data.Linq",
309      };
310    }
311
312    #endregion
313
314    #region Compilation
315
316    private static CSharpCodeProvider codeProvider =
317      new CSharpCodeProvider(
318        new Dictionary<string, string>() {
319          { "CompilerVersion", "v4.0" },  // support C# 4.0 syntax
320        });
321
322    private CompilerResults DoCompile() {
323      CompilerParameters parameters = new CompilerParameters();
324      parameters.GenerateExecutable = false;
325      parameters.GenerateInMemory = true;
326      parameters.IncludeDebugInformation = false;
327      parameters.ReferencedAssemblies.AddRange(SelectedAssemblies.Select(a => a.Location).ToArray());
328      var unit = CreateCompilationUnit();
329      var writer = new StringWriter();
330      codeProvider.GenerateCodeFromCompileUnit(
331        unit,
332        writer,
333        new CodeGeneratorOptions() {
334          BracingStyle = "C",
335          ElseOnClosing = true,
336          IndentString = "  ",
337        });
338      CompilationUnitCode = writer.ToString();
339      return codeProvider.CompileAssemblyFromDom(parameters, unit);
340    }
341
342    public virtual void Compile() {
343      var results = DoCompile();
344      executeMethod = null;
345      CompileErrors = results.Errors;
346      if (results.Errors.HasErrors) {
347        StringBuilder sb = new StringBuilder();
348        foreach (CompilerError error in results.Errors) {
349          sb.Append(error.Line).Append(':')
350            .Append(error.Column).Append(": ")
351            .AppendLine(error.ErrorText);
352        }
353        throw new Exception(string.Format(
354          "Compilation of \"{0}\" failed:{1}{2}",
355          Name, Environment.NewLine,
356          sb.ToString()));
357      } else {
358        Assembly assembly = results.CompiledAssembly;
359        Type[] types = assembly.GetTypes();
360        executeMethod = types[0].GetMethod("Execute");
361      }
362    }
363
364    private CodeCompileUnit CreateCompilationUnit() {
365      CodeNamespace ns = new CodeNamespace("HeuristicLab.Operators.Programmable.CustomOperators");
366      ns.Types.Add(CreateType());
367      ns.Imports.AddRange(
368        GetSelectedAndValidNamespaces()
369        .Select(n => new CodeNamespaceImport(n))
370        .ToArray());
371      CodeCompileUnit unit = new CodeCompileUnit();
372      unit.Namespaces.Add(ns);
373      return unit;
374    }
375
376    public IEnumerable<string> GetSelectedAndValidNamespaces() {
377      var possibleNamespaces = new HashSet<string>(GetAllNamespaces(true));
378      foreach (var ns in Namespaces)
379        if (possibleNamespaces.Contains(ns))
380          yield return ns;
381    }
382
383    public static readonly Regex SafeTypeNameCharRegex = new Regex("[_a-zA-Z0-9]+");
384    public static readonly Regex SafeTypeNameRegex = new Regex("[_a-zA-Z][_a-zA-Z0-9]*");
385
386    public string CompiledTypeName {
387      get {
388        var sb = new StringBuilder();
389        foreach (string s in SafeTypeNameCharRegex.Matches(Name).Cast<Match>().Select(m => m.Value)) {
390          sb.Append(s);
391        }
392        return SafeTypeNameRegex.Match(sb.ToString()).Value;
393      }
394    }
395
396    private CodeTypeDeclaration CreateType() {
397      CodeTypeDeclaration typeDecl = new CodeTypeDeclaration(CompiledTypeName) {
398        IsClass = true,
399        TypeAttributes = TypeAttributes.Public,
400      };
401      typeDecl.Members.Add(CreateMethod());
402      return typeDecl;
403    }
404
405    public string Signature {
406      get {
407        var sb = new StringBuilder()
408        .Append("public static IOperation Execute(")
409        .Append(TypeNameParser.Parse(GetType().FullName).GetTypeNameInCode(namespaces))
410        .Append(" op, ")
411        .Append(TypeNameParser.Parse(typeof(IExecutionContext).FullName).GetTypeNameInCode(namespaces))
412        .Append(" context");
413        foreach (IParameter param in Parameters) {
414          sb.Append(String.Format(", {0} {1}",
415            TypeNameParser.Parse(param.GetType().FullName).GetTypeNameInCode(namespaces),
416            param.Name));
417        }
418        return sb.Append(")").ToString();
419      }
420    }
421
422    public event EventHandler SignatureChanged;
423
424    private static Regex lineSplitter = new Regex(@"\r\n|\r|\n");
425
426    private CodeMemberMethod CreateMethod() {
427      CodeMemberMethod method = new CodeMemberMethod();
428      method.Name = "Execute";
429      method.ReturnType = new CodeTypeReference(typeof(IOperation));
430      method.Attributes = MemberAttributes.Public | MemberAttributes.Static;
431      method.Parameters.Add(new CodeParameterDeclarationExpression(GetType(), "op"));
432      method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IExecutionContext), "context"));
433      foreach (var param in Parameters)
434        method.Parameters.Add(new CodeParameterDeclarationExpression(param.GetType(), param.Name));
435      string[] codeLines = lineSplitter.Split(code);
436      for (int i = 0; i < codeLines.Length; i++) {
437        codeLines[i] = string.Format("#line {0} \"ProgrammableOperator\"{1}{2}", i + 1, "\r\n", codeLines[i]);
438      }
439      method.Statements.Add(new CodeSnippetStatement(string.Join("\r\n", codeLines) + MethodSuffix));
440      return method;
441    }
442
443    public virtual string MethodSuffix {
444      get { return "return null;"; }
445    }
446
447    #endregion
448
449    #region HeuristicLab interfaces
450
451    public override IOperation Apply() {
452      lock (syncRoot) {
453        if (executeMethod == null) {
454          Compile();
455        }
456      }
457
458      var parameters = new List<object>() { this, ExecutionContext };
459      parameters.AddRange(Parameters.Select(p => (object)p));
460      return (IOperation)executeMethod.Invoke(null, parameters.ToArray());
461    }
462
463    public event EventHandler CodeChanged;
464    protected virtual void OnCodeChanged() {
465      EventHandler handler = CodeChanged;
466      if (handler != null) handler(this, EventArgs.Empty);
467    }
468
469    #endregion
470  }
471}
Note: See TracBrowser for help on using the repository browser.