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