Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 2911 was 2911, checked in by swagner, 15 years ago

Operator architecture refactoring (#95)

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