Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Scripting/3.3/Script.cs @ 10857

Last change on this file since 10857 was 10857, checked in by jkarder, 10 years ago

#2136: implemented review comments from mkommend in comment:32:ticket:2136

File size: 5.5 KB
RevLine 
[10506]1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2014 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;
[10332]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 HeuristicLab.Common;
32using HeuristicLab.Common.Resources;
33using HeuristicLab.Core;
34using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
35using Microsoft.CSharp;
36
[10506]37namespace HeuristicLab.Scripting {
[10332]38  [StorableClass]
[10731]39  public class Script : NamedItem {
40    protected virtual string CodeTemplate {
41      get { return string.Empty; }
42    }
[10332]43
44    #region Fields & Properties
45    public static new Image StaticItemImage {
46      get { return VSImageLibrary.Script; }
47    }
48
49    [Storable]
50    private string code;
[10857]51    public string Code {
[10332]52      get { return code; }
53      set {
54        if (value == code) return;
55        code = value;
56        OnCodeChanged();
57      }
58    }
59
60    private CompilerErrorCollection compileErrors;
[10857]61    public CompilerErrorCollection CompileErrors {
[10332]62      get { return compileErrors; }
63      private set {
64        compileErrors = value;
65        OnCompileErrorsChanged();
66      }
67    }
68    #endregion
69
70    #region Construction & Initialization
71    [StorableConstructor]
[10731]72    protected Script(bool deserializing) : base(deserializing) { }
73    protected Script(Script original, Cloner cloner)
[10332]74      : base(original, cloner) {
75      code = original.code;
76      if (original.compileErrors != null)
77        compileErrors = new CompilerErrorCollection(original.compileErrors);
78    }
[10857]79    public Script()
80      : base("Script", "An empty script.") {
81      code = string.Empty;
[10332]82    }
[10577]83    public Script(string code)
84      : this() {
85      this.code = code;
86    }
[10332]87
88    public override IDeepCloneable Clone(Cloner cloner) {
[10401]89      return new Script(this, cloner);
[10332]90    }
91    #endregion
92
[10731]93    #region Compilation
94    protected virtual CSharpCodeProvider CodeProvider {
95      get {
96        return new CSharpCodeProvider(
97          new Dictionary<string, string> {
98                {"CompilerVersion", "v4.0"}, // support C# 4.0 syntax
99              });
100      }
[10332]101    }
102
[10731]103    protected virtual CompilerResults DoCompile() {
[10332]104      var parameters = new CompilerParameters {
105        GenerateExecutable = false,
106        GenerateInMemory = true,
[10506]107        IncludeDebugInformation = true,
108        WarningLevel = 4
[10332]109      };
110      parameters.ReferencedAssemblies.AddRange(
111        GetAssemblies()
112        .Select(a => a.Location)
113        .ToArray());
114      var unit = CreateCompilationUnit();
115      var writer = new StringWriter();
[10731]116      CodeProvider.GenerateCodeFromCompileUnit(
[10332]117        unit,
118        writer,
119        new CodeGeneratorOptions {
120          ElseOnClosing = true,
121          IndentString = "  ",
122        });
[10731]123      return CodeProvider.CompileAssemblyFromDom(parameters, unit);
[10332]124    }
125
[10731]126    public virtual Assembly Compile() {
[10332]127      var results = DoCompile();
128      CompileErrors = results.Errors;
129      if (results.Errors.HasErrors) {
130        var sb = new StringBuilder();
131        foreach (CompilerError error in results.Errors) {
132          sb.Append(error.Line).Append(':')
133            .Append(error.Column).Append(": ")
134            .AppendLine(error.ErrorText);
135        }
[10731]136        throw new Exception(string.Format("Compilation of \"{0}\" failed:{1}{2}",
137          Name, Environment.NewLine, sb.ToString()));
[10332]138      } else {
[10731]139        return results.CompiledAssembly;
[10332]140      }
141    }
142
[10731]143    public virtual IEnumerable<Assembly> GetAssemblies() {
[10358]144      var assemblies = new List<Assembly>();
145      foreach (var a in AppDomain.CurrentDomain.GetAssemblies()) {
146        try {
147          if (File.Exists(a.Location)) assemblies.Add(a);
148        } catch (NotSupportedException) {
149          // NotSupportedException is thrown while accessing
150          // the Location property of the anonymously hosted
151          // dynamic methods assembly, which is related to
152          // LINQ queries
153        }
154      }
155      assemblies.Add(typeof(Microsoft.CSharp.RuntimeBinder.Binder).Assembly); // for dlr functionality
156      return assemblies;
157    }
158
[10731]159    protected virtual CodeCompileUnit CreateCompilationUnit() {
[10401]160      var unit = new CodeSnippetCompileUnit(code);
[10332]161      return unit;
162    }
163    #endregion
164
165    public event EventHandler CodeChanged;
[10731]166    protected virtual void OnCodeChanged() {
[10332]167      var handler = CodeChanged;
168      if (handler != null) handler(this, EventArgs.Empty);
169    }
170
171    public event EventHandler CompileErrorsChanged;
[10731]172    protected virtual void OnCompileErrorsChanged() {
[10332]173      var handler = CompileErrorsChanged;
174      if (handler != null) handler(this, EventArgs.Empty);
175    }
176  }
177}
Note: See TracBrowser for help on using the repository browser.