Free cookie consent management tool by TermsFeed Policy Generator

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

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

Operator architecture refactoring (#95)

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