Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Scripting/3.3/Script.cs @ 17329

Last change on this file since 17329 was 17329, checked in by abeham, 4 years ago

#3037: added ability to exclude assemblies

File size: 5.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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.CodeDom;
24using System.CodeDom.Compiler;
25using System.Collections.Generic;
26using System.Drawing;
27using System.IO;
28using System.Linq;
29using System.Reflection;
30using System.Text;
31using System.Text.RegularExpressions;
32using HEAL.Attic;
33using HeuristicLab.Common;
34using HeuristicLab.Common.Resources;
35using HeuristicLab.Core;
36using Microsoft.CSharp;
37
38namespace HeuristicLab.Scripting {
39  [StorableType("0FA4F218-E1F5-4C09-9C2F-12B32D4EC373")]
40  public abstract class Script : NamedItem, IProgrammableItem {
41    #region Fields & Properties
42    public static readonly HashSet<string> ExcludedAssemblyFileNames = new HashSet<string> { "IKVM.OpenJDK.ClassLibrary.dll" };
43    public static new Image StaticItemImage {
44      get { return VSImageLibrary.Script; }
45    }
46
47    [Storable]
48    private string code;
49    public string Code {
50      get { return code; }
51      set {
52        if (value == code) return;
53        code = value;
54        OnCodeChanged();
55      }
56    }
57
58    private CompilerErrorCollection compileErrors;
59    public CompilerErrorCollection CompileErrors {
60      get { return compileErrors; }
61      private set {
62        compileErrors = value;
63        OnCompileErrorsChanged();
64      }
65    }
66    #endregion
67
68    #region Construction & Initialization
69    [StorableConstructor]
70    protected Script(StorableConstructorFlag _) : base(_) { }
71    protected Script(Script original, Cloner cloner)
72      : base(original, cloner) {
73      code = original.code;
74      if (original.compileErrors != null)
75        compileErrors = new CompilerErrorCollection(original.compileErrors);
76    }
77    protected Script()
78      : base("Script", "An empty script.") {
79    }
80    protected Script(string code)
81      : this() {
82      this.code = code;
83    }
84    #endregion
85
86    #region Compilation
87    protected virtual CompilerResults DoCompile() {
88      var parameters = new CompilerParameters {
89        GenerateExecutable = false,
90        GenerateInMemory = true,
91        IncludeDebugInformation = true,
92        WarningLevel = 4
93      };
94
95      parameters.ReferencedAssemblies.AddRange(
96        GetAssemblies()
97        .Select(a => a.Location)
98        .ToArray());
99
100      var codeProvider = new CSharpCodeProvider(
101        new Dictionary<string, string> {
102          { "CompilerVersion", "v4.0"} // support C# 4.0 syntax
103        });
104
105      return codeProvider.CompileAssemblyFromSource(parameters, code);
106    }
107
108    public virtual Assembly Compile() {
109      var results = DoCompile();
110      CompileErrors = results.Errors;
111      if (results.Errors.HasErrors) {
112        var sb = new StringBuilder();
113        foreach (CompilerError error in results.Errors) {
114          sb.Append(error.Line).Append(':')
115            .Append(error.Column).Append(": ")
116            .AppendLine(error.ErrorText);
117        }
118        throw new CompilationException(string.Format("Compilation of \"{0}\" failed:{1}{2}",
119          Name, Environment.NewLine, sb.ToString()));
120      } else {
121        return results.CompiledAssembly;
122      }
123    }
124
125    public virtual IEnumerable<Assembly> GetAssemblies() {
126      var assemblies = AppDomain.CurrentDomain.GetAssemblies()
127        .Where(a => !a.IsDynamic && File.Exists(a.Location)
128                 && !ExcludedAssemblyFileNames.Contains(Path.GetFileName(a.Location)))
129        .GroupBy(x => Regex.Replace(Path.GetFileName(x.Location), @"-[\d.]+\.dll$", ""))
130        .Select(x => x.OrderByDescending(y => y.GetName().Version).First())
131        .ToList();
132      assemblies.Add(typeof(Microsoft.CSharp.RuntimeBinder.Binder).Assembly); // for dlr functionality
133      return assemblies;
134    }
135
136    protected virtual CodeCompileUnit CreateCompilationUnit() {
137      var unit = new CodeSnippetCompileUnit(code);
138      return unit;
139    }
140    #endregion
141
142    public event EventHandler CodeChanged;
143    protected virtual void OnCodeChanged() {
144      var handler = CodeChanged;
145      if (handler != null) handler(this, EventArgs.Empty);
146    }
147
148    public event EventHandler CompileErrorsChanged;
149    protected virtual void OnCompileErrorsChanged() {
150      var handler = CompileErrorsChanged;
151      if (handler != null) handler(this, EventArgs.Empty);
152    }
153  }
154}
Note: See TracBrowser for help on using the repository browser.