Free cookie consent management tool by TermsFeed Policy Generator

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

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

statically initialize list of assemblies and plugins (#842)

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