Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2582 created branch for Hive Web Job Manager

File size: 16.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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 HeuristicLab.Collections;
33using HeuristicLab.Common;
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    {
52      get { return base.Parameters; }
53    }
54
55    public static new System.Drawing.Image StaticItemImage { get { return new Bitmap(25, 25); } }
56
57    private MethodInfo executeMethod;
58    public CompilerErrorCollection CompileErrors { get; private set; }
59    public string CompilationUnitCode { get; private set; }
60
61    [Storable]
62    private string code;
63    public string Code
64    {
65      get { return code; }
66      set
67      {
68        if (value != code) {
69          code = value;
70          executeMethod = null;
71          OnCodeChanged();
72        }
73      }
74    }
75
76    private object syncRoot = new object();
77
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
85    [Storable(Name = "SelectedAssemblies")]
86    private List<string> _selectedAssemblyNames_persistence
87    {
88      get
89      {
90        return Assemblies.Where(a => a.Value).Select(a => a.Key.FullName).ToList();
91      }
92      set
93      {
94        var selectedAssemblyNames = new HashSet<string>(value.Select(n => new AssemblyName(n).Name));
95        foreach (var a in Assemblies.Keys.ToList()) {
96          Assemblies[a] = selectedAssemblyNames.Contains(new AssemblyName(a.FullName).Name);
97        }
98      }
99    }
100
101    public IEnumerable<Assembly> AvailableAssemblies
102    {
103      get { return Assemblies.Keys; }
104    }
105
106    public IEnumerable<Assembly> SelectedAssemblies
107    {
108      get { return Assemblies.Where(kvp => kvp.Value).Select(kvp => kvp.Key); }
109    }
110
111    [Storable]
112    private HashSet<string> namespaces;
113    public IEnumerable<string> Namespaces
114    {
115      get { return namespaces; }
116    }
117
118    public override bool CanChangeDescription
119    {
120      get { return true; }
121    }
122
123    #endregion
124
125    #region Extended Accessors
126
127    public void SelectAssembly(Assembly a) {
128      if (a != null && Assemblies.ContainsKey(a) && !Assemblies[a]) {
129        Assemblies[a] = true;
130      }
131    }
132
133    public void UnselectAssembly(Assembly a) {
134      if (a != null && Assemblies.ContainsKey(a) && Assemblies[a]) {
135        Assemblies[a] = false;
136      }
137    }
138
139    public void SelectNamespace(string ns) {
140      namespaces.Add(ns);
141      OnSignatureChanged();
142    }
143
144    public void UnselectNamespace(string ns) {
145      namespaces.Remove(ns);
146      OnSignatureChanged();
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        }
161      }
162      return namespaces;
163    }
164
165    private IEnumerable<string> GetNamespaceHierachy(string ns) {
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        }
170      }
171    }
172
173    #endregion
174
175    #region Construction & Initialization
176
177    [StorableConstructor]
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());
183    }
184
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);
190      Plugins = original.Plugins.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
191      namespaces = new HashSet<string>(original.namespaces);
192      CompilationUnitCode = original.CompilationUnitCode;
193      if (original.CompileErrors != null)
194        CompileErrors = new CompilerErrorCollection(original.CompileErrors);
195      RegisterEvents();
196    }
197
198    public ProgrammableOperator() {
199      code = "";
200      executeMethod = null;
201      ProgrammableOperator.StaticInitialize();
202      Assemblies = defaultAssemblyDict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
203      Plugins = defaultPluginDict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToList());
204      namespaces = new HashSet<string>(DiscoverNamespaces());
205      RegisterEvents();
206    }
207
208    [StorableHook(HookType.AfterDeserialization)]
209    private void AfterDeserialization() {
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;
214      Assemblies[typeof(System.Threading.Barrier).Assembly] = true; // ensure new System assembly is selected (4.0.0.0)
215      RegisterEvents();
216    }
217
218    public override IDeepCloneable Clone(Cloner cloner) {
219      return new ProgrammableOperator(this, cloner);
220    }
221
222    private void RegisterEvents() {
223      Parameters.ItemsAdded += Parameters_Changed;
224      Parameters.ItemsRemoved += Parameters_Changed;
225      Parameters.ItemsReplaced += Parameters_Changed;
226      Parameters.CollectionReset += Parameters_Changed;
227    }
228
229    private void Parameters_Changed(object sender, CollectionItemsChangedEventArgs<IParameter> args) {
230      OnSignatureChanged();
231    }
232
233    protected void OnSignatureChanged() {
234      executeMethod = null;
235      EventHandler handler = SignatureChanged;
236      if (handler != null) handler(this, EventArgs.Empty);
237    }
238
239    private static void StaticInitialize() {
240      lock (initLock) {
241        if (defaultPluginDict != null && defaultAssemblyDict != null)
242          return;
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);
251
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);
262          }
263        }
264        plugins[plugin.Name] = aList;
265      }
266
267      plugins["other"] = locationTable.Values.ToList();
268      return plugins;
269    }
270
271    protected static List<Assembly> defaultAssemblies = new List<Assembly>() {
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
276      typeof(HeuristicLab.Common.IDeepCloneable).Assembly,
277      typeof(HeuristicLab.Core.Item).Assembly,
278      typeof(HeuristicLab.Data.IntValue).Assembly,
279      typeof(HeuristicLab.Parameters.ValueParameter<IItem>).Assembly,
280      typeof(HeuristicLab.Collections.ObservableList<IItem>).Assembly,
281      typeof(HeuristicLab.Operators.Operator).Assembly,
282      typeof(HeuristicLab.Operators.Programmable.ProgrammableOperator).Assembly,
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          }
292        }
293        catch (NotSupportedException) {
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>() {
312        "HeuristicLab.Common",
313        "HeuristicLab.Core",
314        "HeuristicLab.Data",
315        "HeuristicLab.Parameters",
316        "HeuristicLab.Operators.Programmable",
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>() {
332          { "CompilerVersion", "v4.0" },  // support C# 4.0 syntax
333        });
334
335    private CompilerResults DoCompile() {
336      CompilerParameters parameters = new CompilerParameters();
337      parameters.GenerateExecutable = false;
338      parameters.GenerateInMemory = true;
339      parameters.IncludeDebugInformation = false;
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    }
354
355    public virtual void Compile() {
356      var results = DoCompile();
357      executeMethod = null;
358      CompileErrors = results.Errors;
359      if (results.Errors.HasErrors) {
360        StringBuilder sb = new StringBuilder();
361        foreach (CompilerError error in results.Errors) {
362          sb.Append(error.Line).Append(':')
363            .Append(error.Column).Append(": ")
364            .AppendLine(error.ErrorText);
365        }
366        throw new Exception(string.Format(
367          "Compilation of \"{0}\" failed:{1}{2}",
368          Name, Environment.NewLine,
369          sb.ToString()));
370      } else {
371        Assembly assembly = results.CompiledAssembly;
372        Type[] types = assembly.GetTypes();
373        executeMethod = types[0].GetMethod("Execute");
374      }
375    }
376
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;
387    }
388
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
399    public string CompiledTypeName
400    {
401      get
402      {
403        var sb = new StringBuilder();
404        foreach (string s in SafeTypeNameCharRegex.Matches(Name).Cast<Match>().Select(m => m.Value)) {
405          sb.Append(s);
406        }
407        return SafeTypeNameRegex.Match(sb.ToString()).Value;
408      }
409    }
410
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
420    public string Signature
421    {
422      get
423      {
424        var sb = new StringBuilder()
425        .Append("public static IOperation Execute(")
426        .Append(TypeNameParser.Parse(GetType().FullName).GetTypeNameInCode(namespaces))
427        .Append(" op, ")
428        .Append(TypeNameParser.Parse(typeof(IExecutionContext).FullName).GetTypeNameInCode(namespaces))
429        .Append(" context");
430        foreach (IParameter param in Parameters) {
431          sb.Append(String.Format(", {0} {1}",
432            TypeNameParser.Parse(param.GetType().FullName).GetTypeNameInCode(namespaces),
433            param.Name));
434        }
435        return sb.Append(")").ToString();
436      }
437    }
438
439    public event EventHandler SignatureChanged;
440
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";
446      method.ReturnType = new CodeTypeReference(typeof(IOperation));
447      method.Attributes = MemberAttributes.Public | MemberAttributes.Static;
448      method.Parameters.Add(new CodeParameterDeclarationExpression(GetType(), "op"));
449      method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IExecutionContext), "context"));
450      foreach (var param in Parameters)
451        method.Parameters.Add(new CodeParameterDeclarationExpression(param.GetType(), param.Name));
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      }
456      method.Statements.Add(new CodeSnippetStatement(string.Join("\r\n", codeLines) + MethodSuffix));
457      return method;
458    }
459
460    public virtual string MethodSuffix
461    {
462      get { return "return null;"; }
463    }
464
465    #endregion
466
467    #region HeuristicLab interfaces
468
469    public override IOperation Apply() {
470      lock (syncRoot) {
471        if (executeMethod == null) {
472          Compile();
473        }
474      }
475
476      var parameters = new List<object>() { this, ExecutionContext };
477      parameters.AddRange(Parameters.Select(p => (object)p));
478      return (IOperation)executeMethod.Invoke(null, parameters.ToArray());
479    }
480
481    public event EventHandler CodeChanged;
482    protected virtual void OnCodeChanged() {
483      EventHandler handler = CodeChanged;
484      if (handler != null) handler(this, EventArgs.Empty);
485    }
486
487    #endregion
488  }
489}
Note: See TracBrowser for help on using the repository browser.