Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Operators.Programmable/3.3/ProgrammableOperator.cs @ 4419

Last change on this file since 4419 was 4419, checked in by swagner, 14 years ago

Enabled saving only for some specific items (#1193)

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