Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Operators.Programmable/3.2/ProgrammableOperator.cs @ 2678

Last change on this file since 2678 was 2678, checked in by epitzer, 14 years ago

Filter out generated assemblies during discovery (#842)

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