Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OptimizationNetworks/HeuristicLab.Scripting/3.3/Script.cs @ 14604

Last change on this file since 14604 was 11576, checked in by swagner, 10 years ago

#2205: Merged changes r11062:11557 from trunk/sources into branches/OptimizationNetworks

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