Free cookie consent management tool by TermsFeed Policy Generator

source: branches/WebJobManager/HeuristicLab.Operators.Programmable/3.3/ProgrammableOperator.cs @ 13656

Last change on this file since 13656 was 13656, checked in by ascheibe, 8 years ago

#2582 created branch for Hive Web Job Manager

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