Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 15962 was 15584, checked in by swagner, 7 years ago

#2640: Updated year of copyrights in license headers on stable

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