Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 12734 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
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;
[11576]26using System.Diagnostics;
[10332]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
[10506]38namespace HeuristicLab.Scripting {
[10332]39  [StorableClass]
[10731]40  public class Script : NamedItem {
41    protected virtual string CodeTemplate {
42      get { return string.Empty; }
43    }
[10332]44
45    #region Fields & Properties
46    public static new Image StaticItemImage {
47      get { return VSImageLibrary.Script; }
48    }
49
50    [Storable]
51    private string code;
[10857]52    public string Code {
[10332]53      get { return code; }
54      set {
55        if (value == code) return;
56        code = value;
57        OnCodeChanged();
58      }
59    }
60
61    private CompilerErrorCollection compileErrors;
[10857]62    public CompilerErrorCollection CompileErrors {
[10332]63      get { return compileErrors; }
64      private set {
65        compileErrors = value;
66        OnCompileErrorsChanged();
67      }
68    }
69    #endregion
70
71    #region Construction & Initialization
72    [StorableConstructor]
[10731]73    protected Script(bool deserializing) : base(deserializing) { }
74    protected Script(Script original, Cloner cloner)
[10332]75      : base(original, cloner) {
76      code = original.code;
77      if (original.compileErrors != null)
78        compileErrors = new CompilerErrorCollection(original.compileErrors);
79    }
[10857]80    public Script()
81      : base("Script", "An empty script.") {
82      code = string.Empty;
[10332]83    }
[10577]84    public Script(string code)
85      : this() {
86      this.code = code;
87    }
[10332]88
89    public override IDeepCloneable Clone(Cloner cloner) {
[10401]90      return new Script(this, cloner);
[10332]91    }
92    #endregion
93
[10731]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      }
[10332]102    }
103
[10731]104    protected virtual CompilerResults DoCompile() {
[10332]105      var parameters = new CompilerParameters {
106        GenerateExecutable = false,
107        GenerateInMemory = true,
[10506]108        IncludeDebugInformation = true,
109        WarningLevel = 4
[10332]110      };
111      parameters.ReferencedAssemblies.AddRange(
112        GetAssemblies()
113        .Select(a => a.Location)
114        .ToArray());
115      var unit = CreateCompilationUnit();
116      var writer = new StringWriter();
[10731]117      CodeProvider.GenerateCodeFromCompileUnit(
[10332]118        unit,
119        writer,
120        new CodeGeneratorOptions {
121          ElseOnClosing = true,
122          IndentString = "  ",
123        });
[10731]124      return CodeProvider.CompileAssemblyFromDom(parameters, unit);
[10332]125    }
126
[10731]127    public virtual Assembly Compile() {
[10332]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        }
[10731]137        throw new Exception(string.Format("Compilation of \"{0}\" failed:{1}{2}",
138          Name, Environment.NewLine, sb.ToString()));
[10332]139      } else {
[10731]140        return results.CompiledAssembly;
[10332]141      }
142    }
143
[10731]144    public virtual IEnumerable<Assembly> GetAssemblies() {
[11576]145      var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic && File.Exists(a.Location)).ToList();   
[10358]146      assemblies.Add(typeof(Microsoft.CSharp.RuntimeBinder.Binder).Assembly); // for dlr functionality
147      return assemblies;
148    }
149
[10731]150    protected virtual CodeCompileUnit CreateCompilationUnit() {
[10401]151      var unit = new CodeSnippetCompileUnit(code);
[10332]152      return unit;
153    }
154    #endregion
155
156    public event EventHandler CodeChanged;
[10731]157    protected virtual void OnCodeChanged() {
[10332]158      var handler = CodeChanged;
159      if (handler != null) handler(this, EventArgs.Empty);
160    }
161
162    public event EventHandler CompileErrorsChanged;
[10731]163    protected virtual void OnCompileErrorsChanged() {
[10332]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.