Free cookie consent management tool by TermsFeed Policy Generator

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

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

Renamed classes of HeuristicLab.Data (#909)

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