Free cookie consent management tool by TermsFeed Policy Generator

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

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

New ProgrammableOperator with syntax highlighting, code completion, configurable assemblies and namespaces (#842)

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